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.
Post a Comment