正如学习如何处理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);
}
答案 0 :(得分:1)
您应该使用BitmapEncoder
(BmpBitmapEncoder
代表* .bmp文件,但我建议您PngBitmapEncoder
,因为您的图片具有透明度,并且会转换为完全黑色的.bmp):< / p>
var enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bmp));
using(var fs = new FileStream("Test.png", FileMode.Create, FileAccess.Write))
{
enc.Save(fs);
}