2013-01-16 45 views
0

我正在使用SVG#(http://sharpvectors.codeplex.com/)來批量轉換SVG文件爲其他格式。被轉換的SVG圖像是沒有背景的黑色線條圖。我對WPF或System.Windows.Media命名空間有一點經驗,所以請原諒,如果這是一個基本問題。保存Windows.Media.Drawing與BmpBitmapEncoder黑色圖像 - 如何刪除alpha?

我使用從SVG#的ImageSvgConverter,它接受一個System.Windows.Media.Drawing對象,然後使用System.Windows.Media編碼器(BmpBitmapEncoderPngBitmapEncoder等)導出到所需的文件格式轉換的修改版本。

當我使用TiffBitmapEncoderor,PngBitmapEncoderGifBitmap導出時,圖像按預期生成。生成的圖像都具有透明背景。

但是,當我使用JpegBitmapEncoderBmpBitmapEncoder導出時,所有圖像都顯示爲黑色。由於tif,png和gif都具有透明背景,我認爲jpg/bmp圖像正在繪製正確,但是,由於alpha在這些文件格式中不受支持,具有黑色輸出很有意義,因爲透明度將被解釋因爲沒有/黑色。

我認爲這是在這些SO帖子Strange bmp black output from BitmapSource - any ideas?,Convert Transparent PNG to JPG with Non-Black Background ColorBackground Turns Black When Saving Bitmap - C#中描述的。

但是,我看不到應用解決方案的方式是這些帖子來我的問題。任何人都可以將我指向正確的方向嗎?

我已經嘗試對DrawingContext的PushOpacityMask方法應用一個白色的SolidColorBrush,但是,這沒有什麼區別。

真的很感謝任何指針。

 private Stream SaveImageFile(Drawing drawing) 
    { 
     // black output 
     BitmapEncoder bitmapEncoder = new BmpBitmapEncoder(); 

     // works 
     //bitmapEncoder = new PngBitmapEncoder(); 

     // The image parameters... 
     Rect drawingBounds = drawing.Bounds; 
     int pixelWidth = (int)drawingBounds.Width; 
     int pixelHeight = (int)drawingBounds.Height; 
     double dpiX = 96; 
     double dpiY = 96; 

     // The Visual to use as the source of the RenderTargetBitmap. 
     DrawingVisual drawingVisual = new DrawingVisual(); 
     DrawingContext drawingContext = drawingVisual.RenderOpen(); 

     // makes to difference - still black 
     //drawingContext.PushOpacityMask(new SolidColorBrush(System.Windows.Media.Color.FromRgb(255,255,255))); 

     drawingContext.DrawDrawing(drawing); 
     drawingContext.Close(); 

     // The BitmapSource that is rendered with a Visual. 
     RenderTargetBitmap targetBitmap = new RenderTargetBitmap(pixelWidth, pixelHeight, dpiX, dpiY, PixelFormats.Pbgra32); 

     targetBitmap.Render(drawingVisual); 

     // Encoding the RenderBitmapTarget as an image file. 
     bitmapEncoder.Frames.Add(BitmapFrame.Create(targetBitmap)); 

     MemoryStream stream = new MemoryStream(); 
     bitmapEncoder.Save(stream); 
     stream.Position = 0; 
     return stream; 
    } 

回答

2

你可以實際drawing對象之前繪製一個合適的尺寸填充「背景」矩形。

using (var drawingContext = drawingVisual.RenderOpen()) 
{ 
    drawingContext.DrawRectangle(Brushes.White, null, new Rect(drawingBounds.Size)); 
    drawingContext.DrawDrawing(drawing); 
} 
+0

我看不見樹木了!完美的工作,非常感謝。 – Jack