Determine if an image is opaque or transparent I wrote an extension method defined for the Image Class (System.Drawing) —
 which returns a Boolean value telling you if the image is opaque or transparent.

The color of each pixel in the image is represented as a 32-bit number: 8 bits each for alpha, red, green, and blue (ARGB). Each of the four components is a number from 0 through 255, with 0 representing no intensity and 255 representing full intensity.

The alpha component specifies the transparency of the color.

If any pixel in the image has a value not equal to 255 in its alpha channel, then the image is not opaque, and therefore transparent.

    public static bool IsOpaque(this Image image)
    {
        var bitmap = new Bitmap(image);
        var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly,
            PixelFormat.Format32bppArgb);
        unsafe
        {
            var p = (byte*)bitmapData.Scan0;
            for (var x = 0; x &lt; bitmap.Width; x++)
            {
                for (var y = 0; y &lt; bitmap.Height; y++)
                {
                    if (p[x * 4 + y * bitmapData.Stride + 3] == 255) continue;
                    bitmap.UnlockBits(bitmapData);
                    return false;
                }
            }
        }
        bitmap.UnlockBits(bitmapData);
        return true;
    }


Concerns:


Can performance be improved at all?
Is it possible to improve readability and reusability without affecting performance?
I don't know how good the C# compiler and runtime optimize this code out of the box, so here is what I would try:


Load bitmap.Width, bitmap.Height and bitmapData.Stride into local variables.
Swap the two for loops, making x the inner loop. Memory accesses are now linear instead of jumping around (to see this, print the array index in your current code).


Side node: You should check whether your code works correctly on big-endian platforms. The + 3 looks suspicious. You could use a uint * instead of the byte * and test the pixel value like this: (p[x + stride * y] &gt;= 0xFF000000.