Detecting if a PNG image file is a Transparent image?

后端 未结 3 1723
闹比i
闹比i 2020-12-06 05:10

I am looking for a way to quickly determine if a PNG image has transparent features. That is, whether any portion of the image is translucent or displays the background in a

相关标签:
3条回答
  • 2020-12-06 05:18

    Why not just loop through all of the pixels in the image and check their alpha values?

        bool ContainsTransparent(Bitmap image)
        {
            for (int y = 0; y < image.Height; ++y)
            {
                for (int x = 0; x < image.Width; ++x)
                {
                    if (image.GetPixel(x, y).A != 255)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    
    0 讨论(0)
  • 2020-12-06 05:35

    Well, i still don't understand the question completely, but if you just want to check, whether a given image may use transparency features, you can use this code:

    Image img = Image.FromFile ( "...", true );
    if ( (img.Flags & 0x2) != 0)
    {
    }
    

    Though it won't help you to determine whether a given png file actually uses transparent features, it will indicate, that it has color type 4 or 6 (both support transparency) according to png file specification.

    0 讨论(0)
  • 2020-12-06 05:35

    Here is an effective approach: Open the PNG in binary. Seek to byte 26 (25 if counting from zero). Evaluate the byte value of the char: 2 or lower => definitely opaque, 3 or higher => supports transparency. According to my findings, files generated by Photoshop only use 3 or higher when needed making this a reliable way to tell when using these. It appears that almost all of the files have 2 for opaque and 6 for alpha-blended. You may also consider checking the PNG and IHDR strings found in that general area to fool-proof your code.

    0 讨论(0)
提交回复
热议问题