QImage在PNG中设置alpha,具有透明度

QImage在PNG中设置alpha,具有透明度

问题描述:

我正在尝试在另一个图像上绘制图像(并且该部分有效),但在绘制叠加图像之前,我想降低它的不透明度.这就是我遇到麻烦的地方.我的叠加图像是 PNG,它们本身有透明区域,否则它们的内容是黑色的.在 Qt 中,我遍历每个像素,但无法确定像素是否透明——它告诉我每个像素都是黑色的,带有完整的 alpha.我试过检查像素颜色和 alpha,但我一定是做错了.搜索并没有导致解决方案.这是我正在使用的小循环:

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 说我的叠加图像格式是 Format_ARGB32.有谁知道我做错了什么?根据 Qt 文档,我应该能够使用 alpha(),但它为每个像素提供 255.也许我弄错了颜色?

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?

您的问题在于 QColor(QRgb) 构造函数:

Your problem is with the QColor(QRgb) constructor:

用值 color 构造一个颜色.alpha 分量被忽略并设置为solid.

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

你有这个问题是因为 QImage::pixel(int,int) 返回一个 QRgb.您应该使用 QImage::pixelColor(int,int) 代替(如果可用,在 Qt 5.6 中引入),或者直接使用 QRgb,如下所示:

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) {}

请注意,如果您想降低图像的不透明度,您可以随时更改 QPainter 不透明度.

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