views:

50

answers:

1

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 is simple enough with using Image.IsAlphaPixelFormat. For #2 though, other than looping through every single pixel, is there a simple way I can determine if at least one of the pixels has an alpha channel that is used (i.e. set to some other value than 255)? All I need back is a boolean and then I'll make determination as to whether to save it out to 32-bit or 24-bit.

UPDATE: I have discovered that ImageFlags.HasTranslucent should provide me with what I'm looking for - unfortunately, it doesn't work at all. For example, PNGs with pixel formats that have at least alpha channel of 66 (semi-transparent) continue to report False (Usage: if((img.Flags & ImageFlags.HasTranslucent) == 4) ...;). I've tested on all types of images, including .bmp that have an alpha value >0 and <255 and it still reports False. Anyone ever use this and know if it even works in GDI+?

+3  A: 

You don't have to loop through every pixel (well you might, but it depends on the image). Set up to loop over all the pixels, but just break out of the loop when you find an alpha value other than 255 use the following pseudo code:

bool hasAlpha = false;
foreach (var pixel in image)
{
    hasAlpha = pixel.Alpha != 255;
    if (hasAlpha)
    {
        break;
    }
}

You'll only have to check all the pixels for images that don't have any alpha. For images that do have alpha this will break out quite quickly.

ChrisF
Thanks ChrisF. It's appearing to be the only way to do this. I'll let the question stand a bit longer to see if another solution comes in.
Otaku
@Otaku - I'd be interested in seeing if there is another way too.
ChrisF
@ChrisF: Check out the update above.
Otaku
Oh man, this looks like the only way. I was hoping for something a bit simplier, but...
Otaku