【问题标题】:Set background color in Bitmap Image在位图图像中设置背景颜色
【发布时间】:2012-06-04 16:56:16
【问题描述】:

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

我使用这个代码:

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

【问题讨论】:

    标签: c# wpf image bitmap


    【解决方案1】:

    尝试使用PixelFormats.DefaultPixelFormats.Bgra32PixelFormats.Rgb24 而不是PixelFormats.Pbgra32

    P 代表预乘 - 假设每个通道都预先乘以 alpha。

    MSDN reference

    【讨论】:

    • 对我不起作用。对于任何没有 P 的 A 格式,Render 都会抛出一个无效的格式异常。
    • @david.pfx 提出问题的详细信息。检查您拥有的对象的属性(格式、步幅),看看有什么不同。
    • 我没有问题。我完全按照给定的方式尝试了答案,并且 Render() 适用于 Pbgra32,而不适用于任何建议的格式。接受的答案在我看来是错误的。
    • @david.pfx 您的输入不同,因此结果也不同。
    • @david.pfx 这个答案有 8.5 年历史,解决了当时的问题。技术在一年内发生了很大变化,更不用说 8.5 年了。我在这里回答问题没有报酬,我这样做是为了帮助那些想自助的人。此外,我不再使用相关技术。我建议你问一个包含所有相关细节的新问题。感谢您投票反对!
    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2017-09-11
      • 2011-11-07
      • 2012-02-17
      相关资源
      最近更新 更多