0

I am creating an animated gif with Water and Land. The Land part has shores, so the water will in some cases be overlaying those shores. However, I wish the shores to still be slightly visible underneath the water. Basically, imagine 1 transparent png which represents water, over another that has sand. The 2 images combined can be viewed as a third image.

My question is - how would I calculate the RGB value of the new pixels, based on the top ones RGBA (with transparency) and the bottom ones RGB values, to mimic a natural look.

I will change the transparency level myself to see what suits me best, but I'm missing a formula.

EDIT: atm I do have 1 idea - take the percentage of the transparency level of the water, and based on that percentage calculate a new RGB. Do the same for the sand pixels, but with the "remaining" percentage (100-transparency%)

ie (A part is in %, for simplicity) (R1,G1,B1, 40) (R2,G2,B2) = 40% of first group + 60% of second

Dejan Biljecki
  • 595
  • 1
  • 5
  • 26
  • Average the values of the two colors in Lab: http://stackoverflow.com/questions/398224/how-to-mix-colors-naturally-with-c – Sean May 04 '17 at 15:20
  • See http://stackoverflow.com/questions/1944095/how-to-mix-two-argb-pixels. You're going to have some trouble doing this as an animated GIF, because GIFs are restricted in the number of colors they can contain and blending generates *lots* of new colors. – Mark Ransom May 04 '17 at 15:31

2 Answers2

2

Alpha blending is either dead simple (alpha is on 0-255, so the colour is destination * (255 - a) + overlay * a, all over 255) or quite subtle, when you allow the destination to also have alpha. Also it is necessary to implement efficiently for many applications, which is done by pre-multiplying, then hardcoding the division by 255 using

 ((x+1) * 257) >> 16;
Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18
2

Malcolm McLean gives the correct answer for the case where destination (aka background) is completely opaque, which happens to be the case we are discussing.

Just for completeness, I'd like you give the formula for the general case and the intuition behind it.

First of all, assume our colors are 4-component floating-point vectors, with each channel having values between 0 and 1. Also assume our colors are alpha-premultiplied, that is the r, g and b channels are pre-multiplied by the alpha channel. Then the alpha-blending formula is:

blended = front + back * (1.0 - front.a)

The intuition is: we are taking the front color and adding to it a bit of the back color, namely as much as we can see through the front color.

Note that the blended color is also alpha-premultiplied.

Joseph Artsimovich
  • 1,499
  • 10
  • 13