tags:

views:

43

answers:

2

I need to save the content of a WPF Object as an image file. In my application I have a chart drawn on a canvas object. This is what I need to save. The canvas with all child objects.

+2  A: 

What you're looking for is the RenderTargetBitmap class. There's an example of its use on the MSDN page I linked, and there's another good example that includes saving to a file here: http://www.ericsink.com/wpf3d/3_Bitmap.html.

Groky
A: 

Here is the func which creates RenderTargetBitmap object, that will be used in further funcs.

public static RenderTargetBitmap ConvertToBitmap(UIElement uiElement, double resolution)
        {
            var scale = resolution / 96d;
            uiElement.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            var sz = uiElement.DesiredSize;
            var rect = new Rect(sz);
            uiElement.Arrange(rect);
            var bmp = new RenderTargetBitmap((int)(scale * (rect.Width)), (int)(scale * (rect.Height)), scale * 96, scale * 96, PixelFormats.Default);
            bmp.Render(uiElement);
            return bmp;
        }

This func creates jpeg string content of file and writes it to a file:

public static void ConvertToJpeg(UIElement uiElement, string path, double resolution)
        {
            var jpegString = CreateJpeg(ConvertToBitmap(uiElement, resolution));
            if (path != null)
            {
                try
                {
                    using (var fileStream = File.Create(path))
                    {
                        using (var streamWriter = new StreamWriter(fileStream, Encoding.Default))
                        {
                            streamWriter.Write(jpegString);
                            streamWriter.Close();
                        }
                        fileStream.Close();
                    }
                }
                catch(Exception ex)
                {
                    //TODO: handle exception here
                }
            }
        }

This func used above to create jpeg string representation of image content:

public static string CreateJpeg(RenderTargetBitmap bitmap)
        {
            var jpeg = new JpegBitmapEncoder();
            jpeg.Frames.Add(BitmapFrame.Create(bitmap));
            string result;
            using (var memoryStream = new MemoryStream())
            {
                jpeg.Save(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);
                using (var streamReader = new StreamReader(memoryStream, Encoding.Default))
                {
                    result = streamReader.ReadToEnd();
                    streamReader.Close();
                }
                memoryStream.Close();
            }
            return result;
        }

Hope this helps.

Eugene Cheverda