qimage Syndicate content

warning: Creating default object from empty value in /www/htdocs/w0065fc9/milianw/modules/taxonomy/taxonomy.pages.inc on line 33.

» Qt: Tint alphatransparent PNG

Wed, 09/21/2011 - 18:07

Let’s assume you want to display the logo of your company in your Qt app. Most probably that logo has just single color with an alpha channel.But: Having the color hard coded in the image is not nice, there are users (like me!) out there, who use a custom (dark!) color scheme. Meaning: If your logo is black/dark and assumes a bright background and you just embed it blindly in your app, I probably won’t see it since the background will be dark in my case.

Here is a solution for the simple case of a mono-colored PNG with an alpha channel which I came up with:

  1. QLabel* label = new QLabel;
  2. // load your image
  3. QImage img(QString("..."));
  4. // morph it into a grayscale image
  5. img = img.alphaChannel();
  6. // the new color we want the logo to have
  7. QColor foreground = label->palette().foreground().color();
  8. // now replace the colors in the image
  9. for(int i = 0; i < img.colorCount(); ++i) {
  10. foreground.setAlpha(qGray(img.color(i)));
  11. img.setColor(i, foreground.rgba());
  12. }
  13. // display the new logo
  14. label->setPixmap(QPixmap::fromImage(img));
  15. label->show();

This seems to work just fine for me. YMMV.