How to save to WPF FrameworkElement’s content as Image?


The article will help us to save the WPF FrameworkElement as Image in different image formats.

How to save to WPF FrameworkElement's content as Image?



In WPF, there is an option to set the DrawingBrush, RadialGradientBrush, LinearGradientBrush, etc., object as Background of Framework Elements such as Border, Rectangle, Grid, Canvas, etc., Sometimes, we are in need to save the FrameworkElement's design as image. We can use the following code snippet for saving the image from the Framework element.


public static void SaveImage(string fileName, FrameworkElement element)
{
string imageExtension = new FileInfo(fileName).Extension.ToLower(CultureInfo.InvariantCulture);

BitmapEncoder imgEncoder = null;
switch (imageExtension)
{
case ".bmp":
imgEncoder = new BmpBitmapEncoder();
break;

case ".jpg":
case ".jpeg":
imgEncoder = new JpegBitmapEncoder();
break;

case ".png":
imgEncoder = new PngBitmapEncoder();
break;

case ".gif":
imgEncoder = new GifBitmapEncoder();
break;

case ".tif":
case ".tiff":
imgEncoder = new TiffBitmapEncoder();
break;

case ".wdp":
imgEncoder = new WmpBitmapEncoder();
break;

default:
imgEncoder = new BmpBitmapEncoder();
break;
}

if (element != null)
{
RenderTargetBitmap bmpSource = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bmpSource.Render(element);

imgEncoder.Frames.Add(BitmapFrame.Create(bmpSource));
using (Stream stream = File.Create(fileName))
{
imgEncoder.Save(stream);
stream.Close();
}
}
}



Hope it will help you. Leave your comments about it. Happy coding.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: