MW

Qt: Tint alphatransparent PNG

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:

      QLabel* label = new QLabel;
      // load your image
      QImage img(QString("..."));
      // morph it into a grayscale image
      img = img.alphaChannel();
      // the new color we want the logo to have
      QColor foreground = label->palette().foreground().color();
      // now replace the colors in the image
      for(int i = 0; i < img.colorCount(); ++i) {
        foreground.setAlpha(qGray(img.color(i)));
        img.setColor(i, foreground.rgba());
      }
      // display the new logo
      label->setPixmap(QPixmap::fromImage(img));
      label->show();

This seems to work just fine for me. YMMV.

Comments

Want to comment? Send me an email!

Comment by NUNO PINHEIRO (not verified) (2011-09-21 21:00:00)

Milian you know what a designer would do to you if you start changing the color of his logos don’t you? ;)

Comment by Milian Wolff (2011-09-21 21:59:00)

Probably he’d rip my head of for changing the app’s palette to a dark scheme in the first place. Wait a minute, do I have a deja vu? :D

Na, seriously: Better a visible logo in a different color than no logo at all.

Comment by jstaniek (not verified) (2011-09-21 19:44:00)

Technically, good code, but in addition to what Ariya said, the example with logo can be only sometimes appropriate. By a rule of thumb, good logos should have defines limited number of backgrounds and foregrounds (2 to 3) and post- processing them is then forbidden. No cropping, and so on. There are a lot of rules noted down in the interweb, e.g. http://tannerchristensen.com/rules-for-logo-design/.

Greetings!

Comment by Milian Wolff (2011-09-21 22:03:00)

Sure, but that would mean the logo must come with a hard-coded background which would stick out of the rest of the application. Anyhow, the above worked for me for now :)

Comment by Ariya (not verified) (2011-09-21 19:26:00)

You can also use QPainter’s composition support, see e.g. <http://ariya.ofilabs.com/2008/11/tinting-through- composition.html> for the details.

Comment by Milian Wolff (2011-09-21 22:01:00)

I searched the hell of the interwebz and did not find anything and now this… Sigh, would have made my live a lot easier.

Thanks, noted for the future.

Published on September 21, 2011.