tags:

views:

313

answers:

2

I am looking for a way to quickly determine if a PNG image has transparent features. Does anyone one know a simple way to detect this?

UPDATE: OK, is there a less complicated way then to pull out the PNG specification and hacking code?

+3  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;
    }
APShredder
Keep in mind that using GetPixel is atrociously slow. You should use the Bitmap.LockBits method to get a pointer to the image data, and use unsafe code to process the image. The GetPixel method will lock the image bits, get the pixel data, build a Color struct, then unlock the image bits every time it is called, requiring orders of magnitude more processing time.
jrista
I was hoping for something a little quicker than checking every pixel. But it is certainly easier than RTM. I'll have to decide if I have the time for that brute force check. Thanks.
kenny
It would be more efficient to return true from within the loop, therefore exiting immediately if the first pixel is transparent.
apathetic
Good idea, I've edited my post accordingly.
APShredder
+1  A: 

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.

n535
Thanks, but this isn't helpful for me, since I need to know if the image contained is actually translucent not if it could be. The other answer above works, but I was hoping for something quicker, which this clearly is....
kenny
This is quite useful. I have used it in combination with the code above so I only inspect the pixels of images that support transparency.
apathetic