I am creating a WPF application of a diagram designer and it only saved as .xml, I would also like to export it as png.
I have this code.
public static void ExportToPng(UIElement target, string ImagePath)
{
// Prepare target-layout
Size size = target.RenderSize;
target.Measure(size);
target.Arrange(new Rect(size));
// Render diagram to bitmap
RenderTargetBitmap renderBitmap =
new RenderTargetBitmap(
(int)size.Width,
(int)size.Height,
96, 96,
PixelFormats.Pbgra32);
renderBitmap.Render(target);
// Convert bitmap to png
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
I've searched for the code and it says that:
The final step is to save the image to the disk (or wherever you like). The PngBitmapEncoder provides the possibility to save to a stream. In this tutorial we’ll pass a StreamWriter to it, to save the image to the path we passed into the method. Add the following code to the method ExportToPng:
using (FileStream fileStream = new FileStream(ImagePath, FileMode.Create))
{
encoder.Save(fileStream);
}
}
}
I want to ask if this fileStream is really required or not. I'm sorry im just newbie in c# and also to WPF.
I included it also because it says so, the last part is like this:
With this you have the diagram-export method completed. Now how and where can you call it? Let me answer the first question first. You can call it like this:
SelectionService.ClearSelection(); // Unselect DesignerItems
DiagramDesignerExporter.ExportToPng(<DesignerCanvas-Object>, "<YourFullFilePath>");
It also says that:
Where you want to call the ExportToPng-method depends a lot on what kind of application you build. If you just enhance the original WPF Diagram Designer, then you most likely add a new button to the Ribbon-Toolbar and add a new method into the file DesignerCanvas.Commands.cs. If you do so, you can call the method simply like this:
DiagramDesignerExporter.ExportToPng(this, <YourFullFilePath>);
I also want to ask if what i want to place in the . And i assumed that it was a place on my laptop. so I called it like this:
DiagramDesignerExporter.ExportToPng(this, "C:/Users/Sony/Pictures");
I run it and I had an error like this:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\Users\Sony\Pictures' is denied.
I tried to call it like this:
DiagramDesignerExporter.ExportToPng(this, "C:/Users/Sony/Pictures");
but its not functioning. I hope someone could help me to this. Thanks.
You have to specify a full path including a file name, not only a folder path:
DiagramDesignerExporter.ExportToPng(this, @"C:\Users\Sony\Pictures\Image1.png");