Ziemo
Ziemo

Reputation: 991

WPF: "edit" image and save

I want to do something like that: open an image in the <image> tag and add some other tags on it, for example green rectangle. After that I want to save it like image with rectangle on some part of it. In general user should drag&drop rectangle and could resize it. But the question is: How can I save it? I suppose that I should save parent tag for all of them, for example <grid> or <canvas> but is it possible?

Upvotes: 2

Views: 1678

Answers (1)

jle
jle

Reputation: 9489

Transform transform = myCanvas.LayoutTransform; 
myCanvas.LayoutTransform = null; Size size = new Size(myCanvas.Width,myCanvas.Height); myCanvas.Measure(size);    
myCanvas.Arrange(new Rect(size)); 
RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d,PixelFormats.Pbgra32); 
renderBitmap.Render(myCanvas);

using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))   
{ 
    PngBitmapEncoder encoder = new PngBitmapEncoder(); 
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); 
    encoder.Save(outStream);    
} 
myCanvas.LayoutTransform = transform;

For a detailed explanation (and the source of the above code), see this blog post:

http://denisvuyka.wordpress.com/2007/12/03/wpf-diagramming-saving-you-canvas-to-image-xps-document-or-raw-xaml/

You can save as PNG, JPG, etc depending on the encoder that you use

Upvotes: 1

Related Questions