Set the background color in the bitmap

I want to save my canvas in an image. It works, but the background color is black. How should I add to change color?

I am using this code:

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); } 
+4
source share
2 answers

Try PixelFormats.Default or PixelFormats.Bgra32 or PixelFormats.Rgb24 instead of PixelFormats.Pbgra32 .

P means pre-multiplication - it is assumed that each channel is pre-multiplied by alpha.

MSDN Link

+2
source

Try

 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); } 
+3
source

Source: https://habr.com/ru/post/1415162/


All Articles