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 < bitmap.Width; x++)
{
for (var y = 0; y < 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?
try { ... } finally { bitmap.UnlockBits(bitmapData); }
you avoid to repeat that code twice. \$\endgroup\$