QImage函数setAlphaChannel

最近使用QImage的函数setAlphaChannel时遇到了一个坑,花了不少时间才弄清楚:在使用这个函数后,图像格式都会变成QImage::Format_ARGB32_Premultiplied。

先看下setAlphaChannel在帮助文档的说明:

复制代码
void QImage::setAlphaChannel(const QImage &alphaChannel)
Sets the alpha channel of this image to the given alphaChannel.
If alphaChannel is an 8 bit alpha image, the alpha values are 
used directly. Otherwise, alphaChannel is converted to 
8 bit grayscale and the intensity of the pixel values is used.
If the image already has an alpha channel, 
the existing alpha channel is multiplied with the new one. 
If the image doesn't have an alpha channel 
it will be converted to a format that does.
The operation is similar to painting alphaChannel as 
an alpha image over this image using QPainter::CompositionMode_DestinationIn.

大概意思:

setAlphaChannel函数为图像指定透明通道,如果alphaChannel是单通道的8位图片,那么直接使用,如果不是就转换成8位的灰度图片在作为透明通道。

如果图像已经有透明通道,那么两个通道会相乘,如果图像没有透明通道则会将图像转换成有透明通道的格式。

帮助文档只说了如果图像没有透明通道,那么会将图像转化成有透明通道的图像,但在使用过程中会发现,只要使用了setAlphaChannel,图像都会将格式转化成

复制代码
QImage::Format_ARGB32_Premultiplied格式。

测试如下:

复制代码
void MainWindow::on_pushButton_clicked()
{
    QImage src1(100,100,QImage::Format_RGB32);
    QImage src2(100,100,QImage::Format_RGB16);
    QImage src3(100,100,QImage::Format_ARGB32);

    QImage alpha(100,100,QImage::Format_Grayscale8);
    alpha.fill(Qt::white);

    src1.setAlphaChannel(alpha);
    src2.setAlphaChannel(alpha);
    src3.setAlphaChannel(alpha);

    qDebug()<<(src1.format() == QImage::Format_ARGB32_Premultiplied);
    qDebug()<<(src2.format() == QImage::Format_ARGB32_Premultiplied);
    qDebug()<<(src3.format() == QImage::Format_ARGB32_Premultiplied);
}

打印出的结果都是true,也就是图像格式都转换成了QImage::Format_ARGB32_Premultiplied。

相关推荐
东哥很忙XH25 分钟前
python使用PyQt5开发桌面端串口通信
开发语言·驱动开发·python·qt
汪宁宇2 小时前
如何在QT5+MinGW环境中编译使用QGIS开发地图应用
c++·qt·qgis·mingw·地图库
刺客xs3 小时前
Qt-----QSS样式表
开发语言·javascript·qt
qq_401700413 小时前
QProgressBar+QSS 进度条
qt
小灰灰搞电子4 小时前
Qt PDF模块详解
数据库·qt·pdf
ibuki_fuko4 小时前
QT/C++ 程序启动时检查程序是否已经启动
开发语言·c++·qt
深蓝海拓5 小时前
PySide6从0开始学习的笔记(五) 信号与槽
笔记·qt·学习·pyqt
淼淼7635 小时前
Qt工具栏+图页,图元支持粘贴复制,撤销,剪切,移动,删除
开发语言·c++·windows·qt
Kelvin_Ngan5 小时前
Qt包含QtCharts/QValueAxis时编译报错
开发语言·qt
葱卤山猪5 小时前
【Qt】心跳检测与粘包处理:打造稳定可靠的TCP Socket通信
开发语言·数据库·qt