Skip to main content
GameDev.net gamedev.net
🔒 Locked

Image Merge With Transparency Math?

Started by user0 Jun 17, 2013 at 3:15 PM 3 replies 1k views
Original Post
user0
user0

I am merging two images and it works fine without transparency but now im adding in transparency and dont know what to do.

I get a unsigned char for each r,g,b,a of the source and the dest so I have

r,g,b,a and destr, destg, destb, desta

then I would do some math

then I have a function dest->SetPixel(x, y, r, g, b, a);

I dont know the math to merge the two and having a hard time finding actual source thats not a library to look at can someone point me in the right direction please?

MrCodeSushi
MrCodeSushi

I think this is the formula that you're looking for.


finalColor = (source.rgb * source.alpha) + (dest.rgb * ( 1.0 - source.alpha));

The alpha blending depends on the source alpha value and by source alpha value i mean the alpha value stored in the second image you're about to render on top of the first image.

user0
user0

Thanks! That looks good but how would this work if say both the source and the dest had an alpha to them? This looks like it would only handle the source alpha to me I could be wrong?

MrCodeSushi
MrCodeSushi

I'm assuming that when you were combining your two images you were just adding image1 and image2's rgb value. The problem is that you're saturating the final color value. It is very possible for the final value to go over 1.0. Or in your case more than 255. That won't cause the problem logically but visually your image will probably look too bright.

So the main reason why we're only taking into account the source alpha value is we want to make sure that whatever the percentage amount we want in the source, the remaining alpha value will be taken from the destination color.

To put it simply, if you want to combine two images, let's say you want to comibe image2 to image1. We're asking how much of image2 you want to be combined in image1 by using the alpha value of image2. It only goes one or the other. Either you combine image2 to image1 or combine image1 to image2. -> Think like a painter. You paint the image one at a time. You don't draw two images in parallel.

If you want to factor in both image's alpha values then formula would look simply like this:


finalColor = (source.rgb * source.alpha) + (dest.rgb * dest.alpha);

But then again this wouldn't really make much sense logically and i'm not really aware of any blending algorithms that uses this.

user0
user0

Thanks for the explanation I think I got it now. I will have to mess around with it to see the results but basically the dest would already have the alpha set so I just paint the source onto it and only set the rgb and the dest would still have its set transparency. Thanks

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.