2013-01-16 47 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