0

在学习如何处理 WPF 上的可视对象时,我遇到了 MSDN 上的一个片段,如下所示。它运行但不确定我如何序列化它。问题是如何在这里物理创建文件 (*.bmp)?

网址

谢谢!

Image myImage = new Image();
FormattedText text = new FormattedText("ABC",
        new CultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
        this.FontSize,
        this.Foreground);

DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawText(text, new Point(2, 2));
drawingContext.Close();

RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 120, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
myImage.Source = bmp;

添加 Save() 方法后:

    Image myImage = new Image();
    FormattedText text = new FormattedText("ABC",
        new CultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, 
        new FontStretch()),
        this.FontSize,
        this.Foreground);
    DrawingVisual drawingVisual = new DrawingVisual();
    DrawingContext drawingContext = drawingVisual.RenderOpen();
    drawingContext.Close();

    RenderTargetBitmap bmp = 
         new RenderTargetBitmap(180, 180, 120, 96, PixelFormats.Pbgra32);
    bmp.Render(drawingVisual);
    myImage.Source = bmp;

    var enc = new PngBitmapEncoder();
    enc.Frames.Add(BitmapFrame.Create(bmp));
    using (var fs = new FileStream("c:\\temp\\Test.png", 
                   FileMode.Create, FileAccess.Write))
    {
        enc.Save(fs);
    }
4

1 回答 1

1

您应该使用BitmapEncoder(BmpBitmapEncoder对于 *.bmp 文件,但我建议您使用,PngBitmapEncoder因为您的图像具有透明度并将转换为完全黑色的 .bmp):

var enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bmp));
using(var fs = new FileStream("Test.png", FileMode.Create, FileAccess.Write))
{
    enc.Save(fs);
}
于 2012-08-15T18:33:25.507 回答