how to merge two images into one using QImage and QPainter in qt?

user2100249 picture user2100249 · Sep 25, 2013 · Viewed 12.2k times · Source

Hi I am developing a blackberry10 app. Inside the app I have two images and I just need to merge these two images into a single image. There is no function in Cascades to combine them. When I posted this in the blackberry developer forum I was advised to use QImage and QPainter functions in qt to combine two images into one. I don't know how to use these functions. Can someone help me with this code?

Answer

lpapp picture lpapp · Sep 25, 2013

You could do somthing like this with QPainter for a simple alpha blending. This code can be easily adjusted to something else as well:

QImage surface(...);
QPainter p(&surface);
p.setCompositionMode(QPainter::CompositionMode_Source);
// p.setBrush(LinearGradient from solid to transparent right to left)
p.drawRect(surface.size());
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
p.drawImage(image1);
p.end();
p.begin(image2);
p.drawImage(surface);
p.end();

This is a very useful part of the documentation with illustration visually.

If you used OpenGL shaders, this would be much simpler though as opengl has some support for this off-hand. I would recommend to consider switching to that in the future unless you are on a limited platform.

Note, there is also some alpha channel support for QImages, but this is probably not the best to use in here, so take it as "out-of-curiosity":

QImage::Format_ARGB32_Premultiplied