I want to know if a QImage
I loaded contains an alpha channel. I already know that QImage::hasAlphaChannel()
can tell me if the image format I'm using supports alpha channels, but is there a way to know if it's actually being used in the loaded image?
-
2What do you mean by "used"? Having at least one pixel with alpha different from opaque?– vinesMay 27, 2011 at 20:34
-
@vines Yes, that's what I meant.– PieterMay 28, 2011 at 10:48
2 Answers
Here you have my snippet for checking if alpha is really used. It's useful when image is in ARGB32.
bool useAlpha = false;
const uchar* pixelData = image.bits();
int bytes = image.byteCount();
for (const QRgb* pixel = reinterpret_cast<const QRgb*>(pixelData); bytes > 0; pixel++, bytes -= sizeof(QRgb)) {
if (qAlpha(*pixel) != UCHAR_MAX) {
useAlpha = true;
break;
}
}
Remember also that there is format() method.
-
I've read that you should use
static_cast
instead ofreinterpret_cast
whenever possible. My compiler won't let me usestatic_cast
in this context. Could you explain whatreinterpret_cast
is used for in this case and whystatic_cast
doesn't work?– PieterMay 28, 2011 at 9:23 -
@Pieter QRgb (
unsigned int
) is different type than uchar (unsigned char
), thus pointers are incompatible.static_cast
is useful only for related types (like class and its subclass). Check: cplusplus.com/doc/tutorial/typecasting. bits() returns pointer to the first pixel data, and as I said before I assume that image is in 32bpp format, so casting to QRgb* is safe and actually required, as scanline() description explains.– przemocMay 28, 2011 at 9:40
If the format you load the QImage
as has an alpha channel, your QImage
has an alpha channel.
If you're checking to see if any pixel in an image with an alpha channel actually sets any pixel to something other than opaque, you could try something like generating an alpha mask using QImage::createAlphaMask()
and inspecting its pixel values.
-
1createAlphaMask() adds not justified here overhead. IOW: There is no reason to create another QImage just to check its content, because you can do it in original image. What's important, such image from this method is 1bpp, so there is loss of information.– przemocMay 27, 2011 at 22:00