我有一张PNG图片,正在使用.NET中的System.Drawing API进行操作。它有很大的透明区域,我想用白色填充替换透明区域,以便在图像中没有透明区域。在图像编辑程序中很容易实现...但是到目前为止,我在C#中尝试了很多次都没有成功。
有人可以给我一些指导吗?
我有一张PNG图片,正在使用.NET中的System.Drawing API进行操作。它有很大的透明区域,我想用白色填充替换透明区域,以便在图像中没有透明区域。在图像编辑程序中很容易实现...但是到目前为止,我在C#中尝试了很多次都没有成功。
有人可以给我一些指导吗?
void Foo(Bitmap image)
{
for (int y = 0; y < image.Height; ++y)
{
for (int x = 0; x < image.Width; ++x)
{
// not very sure about the condition.
if (image.GetPixel(x, y).A != 255)
{
image.SetPixel(x,y,Color.White);
}
}
}
}
我的例子:
public void FillPngWhite(Bitmap bmp)
{
if (bmp.PixelFormat != PixelFormat.Format32bppArgb)
throw new ApplicationException("Not supported PNG image!");
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbaValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbaValues, 0, bytes);
// array consists of values RGBARGBARGBA
for (int counter = 0; counter < rgbaValues.Length; counter += 4)
{
double t = rgbaValues[counter + 3]/255.0; // transparency of pixel between 0 .. 1 , easier to do math with this
double rt = 1 - t; // inverted value of transparency
// C = C * t + W * (1-t) // alpha transparency for your case C-color, W-white (255)
// same for each color
rgbaValues[counter] = (byte) (rgbaValues[counter]*t + 255*rt); // R color
rgbaValues[counter + 1] = (byte)(rgbaValues[counter + 1] * t + 255 * rt); // G color
rgbaValues[counter + 2] = (byte)(rgbaValues[counter + 2] * t + 255 * rt); // B color
rgbaValues[counter + 3] = 255; // A = 255 => no transparency
}
// Copy the RGB values back to the bitmap
System.Runtime.InteropServices.Marshal.Copy(rgbaValues, 0, ptr, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
}
这个例子与众不同的地方在于:
我使用 LockBits
而不是 GetPixel
和 SetPixel
。它更快,但理解起来有点困难。这是从MSDN修改得到的一个例子。
我考虑了真实的透明度值,正如我在你的问题中所说的评论。这将使带有50%透明度(128)的黑色看起来像灰色而不是黑色。原因是当我想象在图形编辑器中“用白色替换透明度”时,我会创建一个在图像下方填充白色的新图层,然后将两个图层合并。这个例子将产生同样的效果。
一旦您获得了位图对象的句柄,只需执行以下操作:
Bitmap yourImage = HOWEVER YOU LOAD YOUR IMAGE;
int width = YOUR IMAGE WIDTH;
int height = YOUR IMAGE HEIGHT;
Color c;
Color white = new Color(255,255,255,255)
for(int w = 0; w < width; w++)
for(int h = 0; h < height; h++)
{
c = yourImage.GetPixel(w,h);
yourImage.SetPixel(w,h, ((((short)(c.A)) & 0x00FF) <= 0)? white:c); //replace 0 here with some higher tolerance if needed
}
abs(c.A)
? - Bala R