How to convert a PNG image to grayscale and without losing the transparency C#

╄→гoц情女王★ 提交于 2021-01-28 07:12:28

问题


I want to convert a transparent png image to greyscale without losing its transparency.

The problem is the algorithm that I am using in is converting the transparent part into Black, which some picture with black character wouldn't be shown. To give you an idea.

Heres the original picture :

Look what happens when I pass it through the algorithm.

The algorithm :

       public static void ToWhiteBlack(Bitmap original)
    {
        try
        {

            for (var i = 0; i < original.Width; i++)
            {
                for (var j = 0; j < original.Height; j++)
                {
                    var originalColor = original.GetPixel(i, j);
                    var grayScale = (int) ((originalColor.R*0.3) + (originalColor.G*0.59) + (originalColor.B*0.11));
                    var corEmEscalaDeCinza = Color.FromArgb(grayScale, grayScale, grayScale);
                    original.SetPixel(i, j, corEmEscalaDeCinza);
                }
            }
        }
        catch
        {

        }

    }

回答1:


You need to pass the alpha value of the original color to get the transparency. Note that if you have partially transparent pixels that will be passed as well.

var corEmEscalaDeCinza = Color.FromArgb(originalColor.A, grayScale, grayScale, grayScale);


来源:https://stackoverflow.com/questions/45242964/how-to-convert-a-png-image-to-grayscale-and-without-losing-the-transparency-c-sh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!