简体   繁体   English

如何在不丢失透明度的情况下将PNG图像转换为灰度C#

[英]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. 我想将透明的png图像转换为灰度而不丢失其透明度。

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. 您需要传递原始颜色的Alpha值以获得透明度。 Note that if you have partially transparent pixels that will be passed as well. 请注意,如果您也将传递部分透明的像素。

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

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

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