【Qt】根据png的alpha通道生成mask

自己获取

遍历整张图的alpaca通道,重新绘制一张图出来,代码如下:

QImage image;
image.load("image.png");

QImage imgMask;
imgMask.fill(Qt::black);

for (int y = 0; y < image.height(); y++) {
    for (int x = 0; x < image.width(); x++) {
        QColor c = QColor::fromRgba(image.pixel(x, y));
        if(c.alpha() == 255)){
           imgMask.setPixel(x, y, 255);
        }        
    }
}

但是实测上述代码会生成一张纯白的图片,这一点就很奇怪。

Qt的解决方法

QImage imgSrc(strFilePath);
//可以直接生成一张8bit的mask图
QImage img=imgSrc.alphaChannel();

Qt提供的方法可以正常生成出alpha通道的mask图,但是要注意。

注意点

alphaChannel函数是Qt废弃的函数,原因是这个方法耗时太严重,甚至Qt文档中也给出了提示:

QImage QImage::alphaChannel() const

This function is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.

Returns the alpha channel of the image as a new grayscale QImage in which each pixel's red, green, and blue values are given the alpha value of the original image. The color depth of the returned image is 8-bit.

You can see an example of use of this function in QPixmap's alphaChannel(), which works in the same way as this function on QPixmaps.

Most usecases for this function can be replaced with QPainter and using composition modes.

Note this returns a color-indexed image if you want the alpha channel in the alpha8 format instead use convertToFormat(Format_Alpha8) on the source image.

Warning: This is an expensive function.

1、这个函数会照成比较大性能开销

2、Qt建议使用QPainter自己去绘制这么一张图

3、目前还没找到替代alphaChannel更好的方法

你可能感兴趣的:(Qt,qt,开发语言)