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
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;
}
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.
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.