简体   繁体   中英

Problems with “normal” blending of two images with alpha

I'm trying to do some blending of images in Java. After succcesfully doing multiply and screen blending, "normal" blending is causing me headaches.

I found on Wikipedia that the formula for blending two pixels with alpha is: Co being resulting color, Ca color of top image, Cb color of bottom image and Aa -> alpha of top, Ab -> alpha of bottom.

I've tried to translate this to Java, and now have:

(t_X == Components from top image, b_X == Components from bottom image)

float t_a = (topPixels[i] >> 24) & 0xff, t_r = (topPixels[i] >> 16) & 0xff, t_g = (topPixels[i] >> 8) & 0xff, t_b = topPixels[i] & 0xff;
float b_a = (bottomPixels[i] >> 24) & 0xff, b_r = (bottomPixels[i] >> 16) & 0xff, b_g = (bottomPixels[i] >> 8) & 0xff, b_b = bottomPixels[i] & 0xff;

destPixels[i] = 
    (255 << 24 |
    (int)((t_r * t_a) + ((b_r * b_a) * (((255 - t_a) / 255)))) << 16 |  
    (int)((t_g * t_a) + ((b_g * b_a) * (((255 - t_a) / 255)))) << 8 |   
    (int)((t_b * t_a) + ((b_b * b_a) * (((255 - t_a) / 255)))) << 0                     
);

But this seems to be wrong as the resulting image comes out wrong.

Any ideas what I'm missing, or is my lack of mathematical skill getting the best of me again when translating the formula to code?

You need to change a lot of this.

t_r, t_a etc must all be floats from 0 to 1. Do all your calculations in floating point, then multiply by 255 and then cast to int.

If t_a is not a floating point value, then calculations such as (255 - t_a) / 255 are done as integers too. You need to cast one of your inputs to a float beforehand, eg ((255 - t_a) / 255f).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM