【问题标题】:Replacing transparent background with white color in PNG images在PNG图像中用白色替换透明背景
【发布时间】:2015-02-03 18:43:28
【问题描述】:

我有一个 PNG 图像从 Android 中的 DrawingView 发送到 WCF 服务。图像以 32 位格式发送,并且具有透明背景。我想用白色替换透明颜色(因为没有更好的词)背景。到目前为止,我的代码如下所示:

// Converting image to Bitmap object
Bitmap i = new Bitmap(new MemoryStream(Convert.FromBase64String(image)));
// The image that is send from the tablet is 1280x692
// So we need to crop it
Rectangle cropRect = new Rectangle(640, 0, 640, 692);
//HERE
Bitmap target = i.Clone(cropRect, i.PixelFormat);
target.Save(string.Format("c:\\images\\{0}.png", randomFileName()),
System.Drawing.Imaging.ImageFormat.Png);

上述工作正常,除了图像具有透明背景。我注意到在 Paint.NET 中,您可以简单地将 PNG 格式设置为 8 位,并将背景设置为白色。但是,当我尝试使用时:

System.Drawing.Imaging.PixelFormat.Format8bppIndexed

我得到的只是一张全黑的照片。

问:如何将 png 中的透明背景替换为白色?

PS。图像为灰度。

【问题讨论】:

  • 您尝试索引格式是否有原因?您尝试过 24 种 bpp 格式中的任何一种吗?
  • 您应该能够创建一个白色位图并将图像绘制到其上,然后另存为..
  • @NicoSchertler 嗯.. 我尝试了大多数,我不认为所有。 Format24bppRgb 给出相同的结果。
  • @TaW 这是一个正确的答案。取消删除,我可以标记它
  • 好的,但我仍然在与我拥有的一个 PNG 作斗争,但它并没有像我预期的那样工作.. 找到原因后我会更新

标签: c# .net colors bitmap


【解决方案1】:

这将绘制到给定的颜色:

Bitmap Transparent2Color(Bitmap bmp1, Color target)
{
    Bitmap bmp2 = new Bitmap(bmp1.Width, bmp1.Height);
    Rectangle rect = new Rectangle(Point.Empty, bmp1.Size);
    using (Graphics G = Graphics.FromImage(bmp2) )
    {
        G.Clear(target);
        G.DrawImageUnscaledAndClipped(bmp1, rect);
    }
    return bmp2;
}

这使用G.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;,这是默认值。它根据绘制图像的 alpha 通道将绘制的图像与背景混合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-28
    • 2012-09-07
    • 1970-01-01
    • 2015-06-22
    • 2021-03-28
    • 2019-01-03
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多