2012-08-15 24 views
0

正如學習如何應付在WPF視覺對象我遇到了一個片段上MSDN如下。它運行但不知道如何序列化它。問題是我如何在這裏物理創建一個文件(* .bmp)?創建物理文件

URL

謝謝!

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

回答

1

您應該使用BitmapEncoderBmpBitmapEncoder爲* .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); 
} 
+0

@@ Max謝謝,雖然它一路走來並生成一個PNG文件,但是,它是空的。我的意思是沒有ABC。任何想法? – 2012-08-15 18:39:26

+0

不知道,你的代碼+我的代碼片段爲我製作了一個有透明背景的'ABC'的有效.png文件。 – max 2012-08-15 18:41:21

+0

我已經發布了完整的代碼。 – 2012-08-15 18:48:01

相關問題