This algorithm proved to be effective when two images are combined. The picture beneath (background) is seen if alpha component of fronth picture is less then 0xFF. If alpha of front picture (src in snippet) is zero then all we see is background picture. The format of colour is ARGB which means 32 bit variables are used to represent the color of pixels (off course alpha, red, green, blue are one bytes).

/* alpha blend routine */
unsigned int AlphaBlend(const unsigned int bg, const unsigned int src)
   unsigned int a = src >> 24;    /* alpha */

   /* If source pixel is transparent, just return the background */
   if (0 == a) 
      return bg;

   /* alpha blending the source and background colors */
   unsigned int rb = (((src & 0x00ff00ff) * a) +  
      ((bg & 0x00ff00ff) * (0xff - a))) & 0xff00ff00;
   unsigned int    g  = (((src & 0x0000ff00) * a) + 
      ((bg & 0x0000ff00) * (0xff - a))) & 0x00ff0000;

    return (src & 0xff000000) | ((rb | g) >> 8);
10 Years
Discussion Span
Last Post by Jason Zhang

any explanation for the code? what are those magic numbers (0x00ff00ff, 0xff00ff00, etc.) and why red and blue rb?


rb stands for red and blue. To get this component we must mask with 0x00ff00ff. Why?
Becouse the first 8 MSB bits are the alpha transparent component, next byte (or 8 bits) is the red component then the green component follows and finaly the blue component.
Thats why for g (green) variable the 0x0000ff00 mask is used. So the resultant picture is formed from rb, g and from alpha component of source pictures.



What you're doing is basically pixel_out=(pixel_1*alpha+pixel_2*(255-alpha))/256. The denominator is changed from 255 to 256 because it's cheaper, but also it has a disadvantage. When alpha equals to 0xFF, pixel_out supposed to be equal to pixel_1 but what you get is pixel_1*255/256 which is a little small than pixel_1.

Actually I'm having the same problem and I need to implement alpha blending in hardware. Do you have a solution better than this?


Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.