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);