将canvas保存到位图

我想将我的canvas保存到位图。 我在互联网上找到了一些例子,但所有这些都只保存了黑色图像(我的canvas大小)。 我该怎么办?

码:

public static void SaveCanvasToFile(Canvas surface, string filename) { Size size = new Size(surface.Width, surface.Height); surface.Measure(size); surface.Arrange(new Rect(size)); // Create a render bitmap and push the surface to it RenderTargetBitmap renderBitmap = new RenderTargetBitmap( (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32); renderBitmap.Render(surface); // Create a file stream for saving image using (FileStream outStream = new FileStream(filename, FileMode.Create)) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); // push the rendered bitmap to it encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); // save the data to the stream encoder.Save(outStream); }} 

试试这个答案:

 public void ExportToPng(Uri path, Canvas surface) { if (path == null) return; // Save current canvas transform Transform transform = surface.LayoutTransform; // reset current transform (in case it is scaled or rotated) surface.LayoutTransform = null; // Get the size of canvas Size size = new Size(surface.Width, surface.Height); // Measure and arrange the surface // VERY IMPORTANT surface.Measure(size); surface.Arrange(new Rect(size)); // Create a render bitmap and push the surface to it RenderTargetBitmap renderBitmap = new RenderTargetBitmap( (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32); renderBitmap.Render(surface); // Create a file stream for saving image using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create)) { // Use png encoder for our data PngBitmapEncoder encoder = new PngBitmapEncoder(); // push the rendered bitmap to it encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); // save the data to the stream encoder.Save(outStream); } // Restore previously saved layout surface.LayoutTransform = transform; } 

为方便起见, 此页面上复制了此答案。

在我的渲染代码中,我调用target.UpdateLayout();target.Arrange(new Rect(size));之后target.Arrange(new Rect(size)); ,也许这会解决它。 另请注意,如果未设置canvas背景,则会将其渲染为透明,而对BMP进行编码可能会变为纯黑色,因此如果您只有黑色对象,则它们可能不可见。

 var fileName = "img.jpg"; var bitMap = new WriteableBitmap(DrawCanvas, null); var ms = new MemoryStream(); System.Windows.Media.Imaging.Extensions.SaveJpeg(bitMap, ms, bitMap.PixelWidth, bitMap.PixelHeight, 0, 100); ms.Seek(0, SeekOrigin.Begin); var library = new MediaLibrary(); library.SavePicture(string.Format("{0}", fileName), ms); 

请注意

如果您的渲染是黑色图像,那是因为您的尺寸不正确。

这是一个很好的例子:

 RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, mXdpi, mYdpi, System.Windows.Media.PixelFormats.Default); rtb.Render(my_canvas); BitmapEncoder pngEncoder = new PngBitmapEncoder(); pngEncoder.Frames.Add(BitmapFrame.Create(rtb)); using (var fs = System.IO.File.OpenWrite("test.png")) { pngEncoder.Save(fs); } 

此代码从您的canvas渲染的位图中保存png图像。

希望能帮到你。

尝试将canvas背景颜色设置为白色