共用方式為


HOW TO:將 Visual 編碼為影像檔

更新:2007 年 11 月

本範例示範如何用使用 RenderTargetBitmapPngBitmapEncoder,將 Visual 物件編碼成影像檔。

範例

DrawingVisual 是使用 BitmapImageFormattedText 建立的,接著會呈現為 RenderTargetBitmap。呈現的點陣圖會用來建立 BitmapFrame,這會再加入到 PngBitmapEncoder,以建立新的 Portable Network Graphics (PNG) 檔案。

' Base Image
Dim bi As New BitmapImage()
bi.BeginInit()
bi.UriSource = New Uri("sampleImages/waterlilies.jpg", UriKind.Relative)
bi.DecodePixelWidth = 200
bi.EndInit()

' Text to render on the image.
Dim [text] As New FormattedText("Waterlilies", New CultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight, New Typeface(Me.FontFamily, FontStyles.Normal, FontWeights.Normal, New FontStretch()), Me.FontSize, Brushes.White)

' The Visual to use as the source of the RenderTargetBitmap.
Dim drawingVisual As New DrawingVisual()
Dim drawingContext As DrawingContext = drawingVisual.RenderOpen()
drawingContext.DrawImage(bi, New Rect(0, 0, bi.Width, bi.Height))
drawingContext.DrawText([text], New System.Windows.Point(bi.Height / 2, 0))
drawingContext.Close()

' The BitmapSource that is rendered with a Visual.
Dim rtb As New RenderTargetBitmap(bi.PixelWidth, bi.PixelHeight, 96, 96, PixelFormats.Pbgra32)
rtb.Render(drawingVisual)

' Encoding the RenderBitmapTarget as a PNG file.
Dim png As New PngBitmapEncoder()
png.Frames.Add(BitmapFrame.Create(rtb))
Dim stm As Stream = File.Create("new.png")
Try
    png.Save(stm)
Finally
    stm.Dispose()
End Try
// 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();

// The 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);
}

這個範例使用的是 PngBitmapEncoder,不過任何衍生的 BitmapEncoder 物件都可以用來建立影像檔。

請參閱

概念

影像處理概觀

繪圖物件概觀

使用 DrawingVisual 物件

參考

DrawingContext