Wednesday, July 27, 2011

Save and read images in WPF

To save WPF objects as an image, you need to render them first, encode the rendered image, and then save to a file through a filestream.

private void SaveTo(Visual v, string f)
{
/// get bound of the visual
Rect b = VisualTreeHelper.GetDescendantBounds(v);

/// new a RenderTargetBitmap with actual size
RenderTargetBitmap r = new RenderTargetBitmap(
(int)b.Width, (int)b.Height,
96, 96, PixelFormats.Pbgra32);

/// render visual
r.Render(v);

/// new a JpegBitmapEncoder and add r into it
JpegBitmapEncoder e = new JpegBitmapEncoder();
e.Frames.Add(BitmapFrame.Create(r));

/// new a FileStream to write the image file
FileStream s = new FileStream(f,
FileMode.OpenOrCreate, FileAccess.Write);
e.Save(s);
s.Close();
}

Remember the output control need to align its parent control, detail is reference to Problem of saving images in WPF (RenderTargetBitmap).

On the other hand, when you want to read an image and show it in WPF, just open the file through a filestream, decode it, and put it into Canvas.

private void LoadFrom(Canvas c, string f)
{
/// new a FileStream to write the image file
FileStream s = new FileStream(f,
FileMode.OpenOrCreate, FileAccess.Read);

/// new a decoder to decode image
BitmapDecoder d = BitmapDecoder.Create(s,
BitmapCreateOptions.None,
BitmapCacheOption.None);

/// new an image with decoded image
Image i = new Image();
i.Source = d.Frames[0];

/// add the image into canvas
c.Children.Add(i);
}

PS. If you close the FileStream during showing, there will cause an exception. So the close action need to be down after the image is no longer to be shown.

No comments:

Post a Comment