Monday, May 16, 2011

Saving WPF Framework element as Image (In different formats)

In WPF, we have an option to set the object of DrawingBrush, RadialGradientBrush, LinearGradientBrush, etc., to the Background of FrameworkElements. We can save the element as an Image using the following code snippet.


        public static void SaveImage(string fileName, FrameworkElement element)
        {
            string imageExtension = null;
            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.

1 comment:

Anonymous said...

I tried this code but there is a problem: if I want to save a Page with a big background image (11952 x 6336 pixel), the result is an image with that resolution (if I bind width and height of the Page with width and height of the background image) but the only part of the background image that is visibile is the part that you see on the screen... How can I export the Page with the background image complete?