954,479 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Alpha blend algorithm

0
By andor on Sep 14th, 2006 6:51 pm

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);
}

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

irishp
Newbie Poster
1 post since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

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.

andor
Posting Whiz in Training
276 posts since Jun 2005
Reputation Points: 251
Solved Threads: 29
 

andor,

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?

Regards,
Jason.

Jason Zhang
Newbie Poster
2 posts since Jul 2006
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You