简体   繁体   English

将QImage(icon)转换为grayScale格式,同时保留背景

[英]Convert QImage(icon) to grayScale format while keeping background

I want to convert an icon to grayscale format (to give the disable action feedback to user) like this: 我想将图标转换为灰度格式(以向用户提供禁用操作反馈),如下所示:

在此处输入图片说明

inline QPixmap grayScaleImage(const QIcon &icon) {
        int w = icon.availableSizes().at(0).width();
        int h = icon.availableSizes().at(0).height();
        QImage image = icon.pixmap(w, h).toImage();
        image = image.convertToFormat(QImage::Format_Grayscale8);
        image.save("Sample.PNG");
        return QPixmap::fromImage(image);
    }

But the result is bad and background also converted to gray: 但是结果很糟糕,背景也转换为灰色:

在此处输入图片说明

So what can i do ? 那我该怎么办?

In order to keep the background transparent, you need to have the image in ARGB format (with alpha). 为了保持背景透明,您需要使图像具有ARGB格式(带有alpha)。 You can convert color image to gray by iterating through the image pixels, calculating the gray value, while keeping alpha channel. 您可以通过迭代图像像素,计算灰度值,同时保留Alpha通道,将彩色图像转换为灰色。 For example like this: 例如这样:

QImage im = some_pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
for (int y = 0; y < im.height(); ++y) {
    QRgb *scanLine = (QRgb*)im.scanLine(y);
    for (int x = 0; x < im.width(); ++x) {
        QRgb pixel = *scanLine;
        uint ci = uint(qGray(pixel));
        *scanLine = qRgba(ci, ci, ci, qAlpha(pixel)/3);
        ++scanLine;
    }
}
return QPixmap::fromImage(im);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM