繁体   English   中英

将透明png颜色转换为单色

[英]Convert transparent png in color to single color

我正在使用Bitmap C#并想知道如何将颜色png图像转换为仅一种颜色。 我希望图像中的所有可见颜色都变白。 透明的部分应保持透明。 我将以灰色背景显示这些。

如果图像不使用alpha通道获得透明度,则以下内容将执行:

Bitmap image;

for (int x = 0; x < image.Width; x++)
{
    for (int y = 0; y < image.Height; y++)
    {
        if (image.GetPixel(x, y) != Color.Transparent)
        {
            image.SetPixel(x, y, Color.White);
        }
    }
}

其他答案很有帮助,让我走了,非常感谢。 我不能让他们工作,不知道为什么。 但我也发现我想保留像素的原始alpha值,使边缘平滑。 这就是我提出的。

for (int x = 0; x < bitmap.Width; x++)
{
    for (int y = 0; y < bitmap.Height; y++)
    {
        Color bitColor = bitmap.GetPixel(x, y);
        //Sets all the pixels to white but with the original alpha value
        bitmap.SetPixel(x, y, Color.FromArgb(bitColor.A, 255, 255, 255));
    }
}

这是一个放大了几次的结果的屏幕转储(原始在上面): 替代文字
(来源: codeodyssey.se

SetPixel是最慢的方式。 您可以使用ColorMatrix

var newImage = new Bitmap(original.Width, original.Height,
                          original.PixelFormat);

using (var g = Graphics.FromImage(newImage)) {
    var matrix = new ColorMatrix(new[] {
        new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
        new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
        new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
        new float[] { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f },
        new float[] { 1.0f, 1.0f, 1.0f, 0.0f, 1.0f }
    });

    var attributes = new ImageAttributes();

    attributes.SetColorMatrix(matrix);

    g.DrawImage(original,
                new Rectangle(0, 0, original.Width, original.Height),
                0, 0, original.Width, original.Height,
                GraphicsUnit.Pixel, attributes);
}

尝试以下代码:

    void Test()
    {
        Bitmap bmp = new Bitmap(50, 50);//you will load it from file or resource

        Color c = Color.Green;//transparent color

        //loop height and width. 
        // YOU MAY HAVE TO CONVERT IT TO Height X VerticalResolution and
        // Width X HorizontalResolution
        for (int i = 0; i < bmp.Height; i++)
        {
            for (int j = 0; j < bmp.Width; j++)
            {
                var p = bmp.GetPixel(j, i);//get pixle at point

                //if pixle color not equals transparent
                if(!c.Equals(Color.FromArgb(p.ToArgb())))
                {
                    //set it to white
                    bmp.SetPixel(j,i,Color.White);
                }
            }
        }
    }

PS:这没有经过测试,也没有进行优化

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM