2014-12-05 135 views
5

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

// 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。图像是灰度。

+0

你有尝试索引格式的原因吗?你有没有试过24种bpp格式的任何一种? – 2014-12-05 15:01:01

+0

你应该可以创建一个白色的位图并将图像绘制到它上面,然后保存为任何.. – TaW 2014-12-05 15:04:03

+0

@NicoSchertler嗯..我尝试了大多数,我不认为全部。 Format24bppRgb给出了相同的结果。 – 2014-12-05 15:05:25

回答

11

这将绘制到一个给定的颜色:

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

相关问题