Alpha blend algorithm

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
andor andor is offline Offline Sep 14th, 2006, 9:51 am |
0
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).
Quick reply to this message  
C Syntax
  1. /* alpha blend routine */
  2. unsigned int AlphaBlend(const unsigned int bg, const unsigned int src)
  3. {
  4. unsigned int a = src >> 24; /* alpha */
  5.  
  6. /* If source pixel is transparent, just return the background */
  7. if (0 == a)
  8. return bg;
  9.  
  10. /* alpha blending the source and background colors */
  11. unsigned int rb = (((src & 0x00ff00ff) * a) +
  12. ((bg & 0x00ff00ff) * (0xff - a))) & 0xff00ff00;
  13. unsigned int g = (((src & 0x0000ff00) * a) +
  14. ((bg & 0x0000ff00) * (0xff - a))) & 0x00ff0000;
  15.  
  16. return (src & 0xff000000) | ((rb | g) >> 8);
  17. }
0
irishp irishp is offline Offline | Dec 4th, 2006
any explanation for the code? what are those magic numbers (0x00ff00ff, 0xff00ff00, etc.) and why red and blue rb?
 
0
andor andor is offline Offline | Dec 5th, 2006
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.
 
0
Jason Zhang Jason Zhang is offline Offline | Sep 27th, 2007
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.
 
 

Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC