how to merge two images into one using QImage and QPainter in qt? [closed]
Asked Answered
D

2

6

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?

Dignitary answered 25/9, 2013 at 7:32 Comment(2)
In which way do you want to merge your images? Make them tiled, overlapped, vertically, horizontally?Romanfleuve
Are you fine with simple alpha blending?Pall
M
4

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 
Maye answered 25/9, 2013 at 7:46 Comment(0)
S
4

You have been directed to the right place and indeed, QPainter will probably do what you want, but your question is ambiguous when you state that you want to "merge these two images". That could imply you want half of one and half of another, or you want to blend them in some way, which is probably more likely.

Qt provides multiple composition modes which provide different effects. Here's the source code to the composition example that Qt provides, which shows you what it can do and you can see, from the source code, exactly how to go about combining the images.

Specifically, you'll see that the first image is rendered (drawBase()) then a composition mode is set on the QPainter and the second image is rendered (drawSource()).

Put simply, draw the first image and then combine the second like this: -

QPainter p(&destImage);
p.setCompositionMode(mode);
p.drawImage(0, 0, sourceImage);

As you can see from the Qt documentation, there are quite a few different composition modes, which will "merge" your images with different effects.

Steeple answered 25/9, 2013 at 8:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.