03-17-2011, 11:12 PM
Rendering any WPF Visual element can be done with WPF's RenderTargetBitmap.
The following two methods can be used to render the element to a bitmap and to save the image to disk.
Note that the width and height that are passed to RenderImage method do not scale the element to be that size - its ActualWidtha and ActualHeight is used in the output image.
To render the element to a custom size a VisualBrush can be used - check the following: http://stackoverflow.com/questions/22275...-to-bitmap
The following two methods can be used to render the element to a bitmap and to save the image to disk.
Code:
public static BitmapSource RenderImage(FrameworkElement objectToRender, int width, int height, Brush backgroundBrush)
{
Rectangle backgroundRect = null;
// If the object was not measured and arranged yet we need to do this before rendering
if (objectToRender.ActualWidth == 0)
{
objectToRender.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
objectToRender.Arrange(new Rect(new Point(0, 0), objectToRender.DesiredSize));
}
if (backgroundBrush != null)
{
backgroundRect = new Rectangle();
backgroundRect.Width = width;
backgroundRect.Height = height;
backgroundRect.Fill = backgroundBrush;
backgroundRect.Arrange(new Rect(0, 0, width, backgroundRect.Height));
}
RenderTargetBitmap bitmap = new RenderTargetBitmap(width, height, 96, 96 /* standard WPF dpi setting 96 */, PixelFormats.Pbgra32);
if (backgroundRect != null)
bitmap.Render(backgroundRect);
bitmap.Render(objectToRender);
return bitmap;
}
public static void SaveImage(BitmapSource image, string resulImageFileName)
{
// write the bitmap to a file
using (System.IO.FileStream fs = new System.IO.FileStream(resulImageFileName, System.IO.FileMode.Create))
{
BitmapEncoder enc;
if (resulImageFileName.EndsWith("jpg"))
enc = new JpegBitmapEncoder();
else if (resulImageFileName.EndsWith("tif") || resulImageFileName.EndsWith("tiff"))
enc = new TiffBitmapEncoder();
else
enc = new PngBitmapEncoder();
BitmapFrame bitmapImage = BitmapFrame.Create(image);
enc.Frames.Add(bitmapImage);
enc.Save(fs);
}
}Note that the width and height that are passed to RenderImage method do not scale the element to be that size - its ActualWidtha and ActualHeight is used in the output image.
To render the element to a custom size a VisualBrush can be used - check the following: http://stackoverflow.com/questions/22275...-to-bitmap
Andrej Benedik

