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。

相关推荐
初阳7855 小时前
【Qt】控件概述(4)—— 输出类控件
开发语言·qt·命令模式
只会掉头发的程序猿5 小时前
在QT中将Widget提升为自定义的Widget后,无法设置Widget的背景颜色问题解决方法
开发语言·qt
Geek之路5 小时前
QT-多线程、线程池的使用
qt·多线程
清风玉骨6 小时前
Qt-QHBoxLayout布局类控件(42)
开发语言·qt
感谢地心引力6 小时前
【Qt】Qt安装(2024-10,QT6.7.3,Windows,Qt Creator 、Visual Studio、Pycharm 示例)
c++·windows·python·qt·visual studio
T0uken7 小时前
【QT Quick】C++交互:调用QML函数
c++·qt·交互
T0uken9 小时前
【QT Quick】C++交互:QML对象操作
c++·qt·交互
barbyQAQ11 小时前
Qt源码阅读——事件循环
开发语言·数据库·qt
T0uken13 小时前
【QT Qucik】C++交互:接收QML信号
c++·qt·交互
martian66513 小时前
QT开发:基于Qt实现的交通信号灯模拟器:实现一个带有倒计时功能的图形界面应用
开发语言·qt