2012-05-30 44 views
4

我想將畫布保存爲圖像。它可以工作,但背景顏色是黑色的。如何添加以改變顏色?在位圖圖像中設置背景顏色

我用這個代碼:

Size size = new Size(surface.Width, surface.Height); 

surface.Measure(size); 
surface.Arrange(new Rect(size)); 

// Create a render bitmap and push the surface to it 
RenderTargetBitmap renderBitmap = 
    new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d, 
          PixelFormats.Pbgra32); 
renderBitmap.Render(surface); 

// Create a file stream for saving image 
using (FileStream outStream = new FileStream(filename, FileMode.Create)) 
{ 
    BmpBitmapEncoder encoder = new BmpBitmapEncoder(); 
    // push the rendered bitmap to it 
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); 
    // save the data to the stream 
    encoder.Save(outStream); 
} 

回答

2

嘗試PixelFormats.DefaultPixelFormats.Bgra32PixelFormats.Rgb24,而不是PixelFormats.Pbgra32

P代表預乘 - 假設每個通道都預乘了alpha。

MSDN reference

3

試試這個

Size size = new Size(surface.Width, surface.Height); 

surface.Measure(size); 
surface.Arrange(new Rect(size)); 

// Create a render bitmap and push the surface to it 
RenderTargetBitmap renderBitmap = 
    new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d, 
          PixelFormats.Pbgra32); 

DrawingVisual drawingVisual = new DrawingVisual(); 
using (DrawingContext drawingContext = drawingVisual.RenderOpen()) 
{ 
    VisualBrush visualBrush = new VisualBrush(surface); 
    drawingContext.DrawRectangle(visualBrush, null, 
     new Rect(new Point(), new Size(size.Width, size.Height))); 
} 

renderBitmap.Render(drawingVisual); 

// Create a file stream for saving image 
using (FileStream outStream = new FileStream(filename, FileMode.Create)) 
{ 
    BmpBitmapEncoder encoder = new BmpBitmapEncoder(); 
    // push the rendered bitmap to it 
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); 
    // save the data to the stream 
    encoder.Save(outStream); 
}