用白色替换PNG图像中的透明背景

10

我有一个来自Android中的 DrawingView 的PNG图像,正在发送到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文件中的透明背景替换为白色?

附注:该图片为灰度图像。


你尝试使用索引格式的原因是什么?你尝试过24 bpp格式中的任何一种吗? - Nico Schertler
你应该能够创建一个白色的位图并将图像绘制到上面,然后另存为任何格式。 - TaW
@NicoSchertler 嗯..我试过大部分,但不是全部。Format24bppRgb 的结果相同。 - Dawid O
@TaW 这是一个正确的答案。请恢复它,以便我可以标记它。 - Dawid O
好的,但我仍然在努力解决一个PNG图片的问题,它并不像我预期的那样工作。如果我找到了原因,我会更新。 - TaW
好的,我放弃了,我无法用其他任何图像复现,所以我认为答案毕竟没有问题。 - TaW
1个回答

26

这将绘制在给定的颜色上:

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 通道将绘制图像与背景混合。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接