Share via


How to: Encode a Visual to an Image File

This example demonstrates how to encode a Visual object into an image file using a RenderTargetBitmapand a PngBitmapEncoder.

Example

The DrawingVisual is created using a BitmapImage and FormattedText which is rendered to a RenderTargetBitmap. The rendered bitmap is then used to create a BitmapFrame which is added to the PngBitmapEncoder to create a new Portable Network Graphics (PNG) file.

// Base Image
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("sampleImages/waterlilies.jpg",UriKind.Relative);
bi.DecodePixelWidth = 200;
bi.EndInit();

// Text to render on the image.
FormattedText text = new FormattedText("Waterlilies",
        new CultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
        this.FontSize,
        Brushes.White);

// The Visual to use as the source of the RenderTargetBitmap.
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawImage(bi,new Rect(0,0,bi.Width,bi.Height)); 
drawingContext.DrawText(text, new Point(bi.Height/2, 0));
drawingContext.Close();

// Our BitmapSource that is rendered with a Visual.
RenderTargetBitmap rtb = new RenderTargetBitmap(bi.PixelWidth, bi.PixelHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(drawingVisual);

// Encoding the RenderBitmapTarget as a PNG file.
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
using (Stream stm = File.Create("new.png"))
{
   png.Save(stm);
}

A PngBitmapEncoder was used in this example but any of the derived BitmapEncoder objects could have been used to create the image file.

See Also

Reference

DrawingContext

Concepts

Imaging Overview
Drawing Objects Overview
Using DrawingVisual Objects