Search code examples
qttransparency

QImage setting alpha in PNG with transparency


I'm trying to draw an image over another (and that part works) but before I draw the overlay image I want to reduce the opacity of it. This is where I'm having trouble. My overlay images are PNG and they themselves have transparent areas, otherwise the content of them is black. In Qt I'm looping through every pixel and I'm having trouble determining if the pixel is transparent or not -- it tells me every pixel is black with full alpha. I've tried checking both the pixel color and alpha but I must be doing it wrong. Searching hasn't lead to a solution. Here's my little loop I'm using:

// Set Alpha
for (int x = 0; x < overlay.width(); x++)
{
    for (int y = 0; y < overlay.height(); y++)
    {
        pixelColor = QColor(overlay.pixel(x,y));

        if (pixelColor.alpha() == 255)
        {
            overlay.setPixel(x, y, QColor(0,0,0,200).rgba());
            //qDebug() << "Not Skipped";
        }
        else
        {
            qDebug() << "Skipped";
        }
    }
}

QImage says my overlay image format is Format_ARGB32. Anyone know what I'm doing wrong? According to the Qt docs I should be able to use alpha(), but it gives me 255 for every single pixel. Maybe I'm getting the color wrong?


Solution

  • Your problem is with the QColor(QRgb) constructor:

    Constructs a color with the value color. The alpha component is ignored and set to solid.

    You have this problem because QImage::pixel(int,int) returns a QRgb. You should use QImage::pixelColor(int,int) instead (if available, was introduced in Qt 5.6), or use a QRgb directly, like this:

    QRgb col = image.pixel(x,y);
    if(qAlpha(col) == 255) {}
    

    Note that if you want to decrease the opacity of an image, you can always change the QPainter opacity.