C# 设置位图图像中的背景色

C# 设置位图图像中的背景色,c#,wpf,image,bitmap,C#,Wpf,Image,Bitmap,我想将画布保存为图像。它可以工作,但背景色是黑色的。我必须如何添加才能更改颜色 我使用以下代码: 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 =

我想将画布保存为图像。它可以工作,但背景色是黑色的。我必须如何添加才能更改颜色

我使用以下代码:

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

尝试
PixelFormats.Default
PixelFormats.Bgra32
PixelFormats.Rgb24
而不是
PixelFormats.Pbgra32

p代表预乘-假设每个通道预乘alpha


试试这个

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

不适合我。Render为没有P.@david.pfx的任何A格式抛出无效格式异常。请询问问题的详细信息。检查你拥有的对象的属性(格式、步幅),看看有什么不同。我没有问题。我完全按照给出的答案进行了尝试,Render()适用于Pbgra32,而不适用于任何建议的格式。在我看来,被接受的答案是错误的。@david.pfx您的输入是不同的,因此结果不同。@david.pfx此答案已有8.5年历史,当时解决了问题。技术在一年内变化很大,更不用说8.5年了。我在这里回答问题是没有报酬的,我这样做是为了帮助那些想自助的人。此外,我不再使用相关技术。我建议你提出一个新的问题,包括所有相关的细节。谢谢你的否决票,顺便说一句!