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。

相关推荐
沫璃染墨8 小时前
《Qt从零入门系列(十五):Qt线程安全与锁机制详解——从QMutex到RAII与读写锁实战》
开发语言·c++·qt·安全·交互·线程·qt6.3
小豆庄12 小时前
视频脱敏引擎的追踪难题:转场误判定、ID撞号和淡入窗口
qt·算法·目标检测·音视频·视频·敏捷流程
小灰灰搞电子15 小时前
Qt 中使用 QSettings 存储结构体数据详解
开发语言·qt
LaoWaiHang1 天前
关于Qt中鼠标左键事件被子控件截留的处理
qt
初阳7851 天前
【基于Qt5仿音乐播放器(一)】——项目准备
qt·1024程序员节
kaixin_learn_qt_ing2 天前
Qt开发工程师
qt
ShineWinsu2 天前
对于Qt:信号与槽的解析
c++·qt·gui·lambda·信号·信号与槽·槽函数
努力实干3 天前
Qt/C++ 模块化设计与工程组织
开发语言·c++·qt
Lhan.zzZ3 天前
Qt:动态库模块框架设计
开发语言·c++·qt
qq_401700414 天前
TCP 长连接、心跳包与断线自动重连设计:工业级通信的“不死鸟”架构
网络·qt·tcp/ip