简体   繁体   中英

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). You can convert color image to gray by iterating through the image pixels, calculating the gray value, while keeping alpha channel. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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