I want to save my canvas to bitmap. I found some examples in internet, but all of those saves only black image (with size of my canvas). What can I do with this?
Co
Try this answer:
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;
}
This answer was copied here for convenience from [this page.]<====LINK DEAD(http://denisvuyka.wordpress.com/2007/12/03/wpf-diagramming-saving-you-canvas-to-image-xps-document-or-raw-xaml/)
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);
try set the canvas background colour to white
If you are working with windows 10 UWP apps, check this page:
RenderTargetBitmap Class on Microsoft Docs
And as a bonus UWP have simplified the process.
PAY ATTENTION
if your render is a black image it is because of your incorrect sizing.
this is a good example for you:
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);
}
this code saves a png image from your bitmap that rendered from your canvas.
Hope helps you.
In my render-code i call target.UpdateLayout();
after target.Arrange(new Rect(size));
, maybe that will fix it. Also note that if the canvas background is not set it will be rendered as transparent, while encoding to BMP that might turn into solid black, so if you only have black objects they might be invisible.