如何创建逆png图像?

时间:2012-07-11 08:41:46

标签: c# .net wpf onpaint

我正在创建在我的基础上绘制的png图像,从基础我可以保存png图像,供您参考

Graphics g = e.Graphics;
 ....
g.DrawLine(pen, new Point(x, y), new Point(x1, y1));
 .....
base.OnPaint(e);

using (var bmp = new Bitmap(500, 50))
{
    base.DrawToBitmap(bmp, new Rectangle(0, 0, 500, 50));
    bmp.Save(outPath);
}

这是单色透明图像,现在我怎么能像png一样填充任何颜色来反转这个图像,真实图像部分应该是透明的,有可能吗?

比特细节:透明会变得不透明,填充的地方会变成透明

4 个答案:

答案 0 :(得分:7)

如果您愿意使用unsafe代码,可以采用更快捷的方式:

private unsafe void Invert(Bitmap bmp)
{
    int w = bmp.Width, h = bmp.Height;
    BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

    int* bytes = (int*)data.Scan0;
    for ( int i = w*h-1; i >= 0; i-- )
        bytes[i] = ~bytes[i];
    bmp.UnlockBits(data);
}

请注意,这并不关心颜色,也会将其反转。如果您希望使用特定颜色,则必须稍微修改代码。

答案 1 :(得分:6)

编辑 (感谢Thomas表示法)

public void ApplyInvert()  
{  
    byte A, R, G, B;  
    Color pixelColor;  

    for (int y = 0; y < bitmapImage.Height; y++)  
    {  
        for (int x = 0; x < bitmapImage.Width; x++)  
        {  
            pixelColor = bitmapImage.GetPixel(x, y);  
            A = (byte)(255 - pixelColor.A); 
            R = pixelColor.R;  
            G = pixelColor.G;  
            B = pixelColor.B;  
            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));  
        }  
    }  
}

从这里开始:Image Processing in C#: Inverting an image

答案 2 :(得分:6)

对于想要一种快速方法来反转Bitmap颜色而不使用unsafe的人:

public static void BitmapInvertColors(Bitmap bitmapImage)
{
    var bitmapRead   = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
    var bitmapLength = bitmapRead.Stride * bitmapRead.Height;
    var bitmapBGRA   = new byte[bitmapLength];
    Marshal.Copy(bitmapRead.Scan0, bitmapBGRA, 0, bitmapLength);
    bitmapImage.UnlockBits(bitmapRead);

    for (int i = 0; i < bitmapLength; i += 4)
    {
        bitmapBGRA[i]     = (byte)(255 - bitmapBGRA[i]);
        bitmapBGRA[i + 1] = (byte)(255 - bitmapBGRA[i + 1]);
        bitmapBGRA[i + 2] = (byte)(255 - bitmapBGRA[i + 2]);
        //        [i + 3] = ALPHA.
    }

    var bitmapWrite = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
    Marshal.Copy(bitmapBGRA, 0, bitmapWrite.Scan0, bitmapLength);
    bitmapImage.UnlockBits(bitmapWrite);
}

Bitmap GetPixel和SetPixel极其缓慢,此方法的工作原理是将Bitmap像素复制到一个字节数组中,然后在最终复制像素之前,可以循环并更改它。

答案 3 :(得分:0)

当您说将透明部分反转为颜色时,您是否将实际颜色存储在刚刚设置为完全透明的PNG图像中?很多程序都会通过从透明度中删除颜色数据来优化png,这样你就无法逆转它。

颜色可以转换为透明度 但透明度(没有底层颜色)无法转换为颜色。

如果幸运的话,你的PNG将不经过优化并仍然保持原始颜色数据的完整性,但是如果你从用户输入这样做,那么它将不适用于大部分情况。