简体   繁体   中英

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

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
        {

        }

    }

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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