Colorize an image via painter composition

Playing with the hue/saturation/value of the pixels in an image can be useful in some contexts. For example, if the image is used as an icon (e.g. in the tool bar), changing the hue during the mouse hover will give a subtle but nicevisual feedback to the user. In many desktop environments, the whole screen is grayscaled when the user is about to logout. For an application where there are pop-ups or other user-interface elements that need to get the user's attention, the other part of the window can be dimmed or tinted
to a pale color.

One technically correct way to colorize an image is by iterating through the pixels, get the pixel color in HSV color space and changing its hue and saturation (potentially also the value) with the intended color. Since an image is often stored in RGB32 format, this involves a conversion to HSV, some H/V manipulation, and back conversion to RGB. An alternative, though less precise, is shown in this dojo example. Basically it is just a conversion of the pixel to grayscale through qGray function and then overdrawing it with a solid color rectangle with the Screen, Overlay or Multiply composition mode. The code, as well as the sample program, is:

svn checkout svn://

The picture shown in the program can be drawn in grayscale or tinted with whatever color you like (use the sliders to change the RGB components) and the composition mode that you like. Each composition mode gives a different result, just play with it to find something that suits your need. Of course, like the previous dojo example shows, you can replace the picture by dragging an image from your file manager or web browser and drop it in the window so that you can experiment the tinting with your own favorite photos.

Blog Topics: