Determine if Alpha Channel is Used in an Image

前端 未结 7 1935
北恋
北恋 2020-12-06 05:29

As I\'m bringing in images into my program, I want to determine if:

  1. they have an alpha-channel
  2. if that alpha-channel is used

#1

7条回答
  •  广开言路
    2020-12-06 06:14

    I get a more advanced solution, based on ChrisF answer:

    public bool IsImageTransparent(Bitmap image,string optionalBgColorGhost)
        {
            for (int i = 0; i < image.Width; i++)
            {
                for (int j = 0; j < image.Height; j++)
                {
                    var pixel = image.GetPixel(i, j);
                    if (pixel.A != 255)
                        return true;
                }
            }
    
            //Check 4 corners to check if all of them are with the same color!
            if (!string.IsNullOrEmpty(optionalBgColorGhost))
            {
                if (image.GetPixel(0, 0).ToArgb() == GetColorFromString(optionalBgColorGhost).ToArgb())
                {
                    if (image.GetPixel(image.Width - 1, 0).ToArgb() == GetColorFromString(optionalBgColorGhost).ToArgb())
                    {
                        if (image.GetPixel(0, image.Height - 1).ToArgb() ==
                            GetColorFromString(optionalBgColorGhost).ToArgb())
                        {
                            if (image.GetPixel(image.Width - 1, image.Height - 1).ToArgb() ==
                                GetColorFromString(optionalBgColorGhost).ToArgb())
                            {
                                return true;
                            }
                        }
                    }
                }
            }
    
            return false;
        }
    
        public static Color GetColorFromString(string colorHex)
        {
            return ColorTranslator.FromHtml(colorHex);
        }
    

    It has a optional bg color string to non transparent images:

    Example of usage:

    IsImageTransparent(new Bitmap(myImg),"#FFFFFF");
    

提交回复
热议问题