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。

相关推荐
clever10111 小时前
在QtCreator 4.10.2中调试qt程序qDebug()输出中文为乱码问题的解决
开发语言·qt
吕司13 小时前
Qt的信号与槽
开发语言·qt
轩情吖15 小时前
Qt的窗口(三)
c++·qt
mengzhi啊16 小时前
qt加载了.qm却没有反应。因为加载时间太晚了
qt
C语言小火车18 小时前
Qt样式实现方式详解:六大方法全面解析
c语言·c++·qt·学习
ae_zr19 小时前
QT静态库如何使用
qt·压缩·静态exe
mengzhi啊19 小时前
针对no TS files specified。使用qt语言家,内网加密软件,不能生成.ts。当3种方法失效,还剩最后一种方法。
qt
木千19 小时前
Qt5.15.2安装MSVC2019编译器
开发语言·qt
专注于ai算法的踩坑小达人19 小时前
C++变量全面总结
c++·qt
去往火星20 小时前
Qt6 CMake 中引入 Qt Linguist 翻译功能
开发语言·qt