Daw*_*d O 6 .net c# colors bitmap
我有一个从DrawingViewAndroid中发送到WCF服务的PNG图像.图像以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);
Run Code Online (Sandbox Code Playgroud)
以上工作正常,但图像具有透明背景.我注意到在Paint.NET中你可以简单地将PNG格式设置为8位,并将背景设置为白色.但是,当我尝试使用时:
System.Drawing.Imaging.PixelFormat.Format8bppIndexed
Run Code Online (Sandbox Code Playgroud)
我得到的只是一张完全黑色的照片.
问:如何在png中用白色替换透明背景?
PS.图像为灰度.
TaW*_*TaW 18
这将绘制到给定的颜色:
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;
}
Run Code Online (Sandbox Code Playgroud)
这使用了G.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;,这是默认值.它根据绘制图像的alpha通道将绘制的图像与背景混合.