Mega Code Archive

 
Categories / Delphi / Graphic
 

Blend two images using API

Title: Blend two images using API Question: How can I use the AlphaBlend function? Answer: If you use Win98 of Win2000 you are already used to the effects of the AlphaBlend function: when a menu pops up or a tooltip appears Windows uses this function to smoothly fade the background image to the appearing control one. The process is simple: Windows computes size and position of appearing control, captures the screen portion relative to those coordinate and repeatedly blends the image of appearing control over the captured one drawing the resulting images on the screen. Only at the end of these steps, Windows shows the real control deceiving us with a cute visual effect. This is the theory. But in practice? The use of the AlphaBlend function is quite simple. Suppose you have a form with three TImages called imgFirst, imgSecond and imgDestination and a TTrackBar called trkBlender with the minimum and maximum set to 0 and 255. Now set the Picture property of imgFirst and imgSecond to two bitmaps. Note that you must use .BMP file or the AlphaBlend will not work. Place on the OnChange event of the TTrackBar this code: procedure TfrmAlphaBlend.trkBlenderChange(Sender: TObject); var udtBlender: TBlendFunction; begin //Specifies the action to take with udtBlender do begin BlendOp := AC_SRC_OVER; BlendFlags := 0; SourceConstantAlpha := trkBlender.Position; AlphaFormat := 0; end; //Draw the first image on destination canvas imgDestination.Canvas.Draw(0,0, imgFirst.Picture.Graphic); //Blend the second image over the previous one AlphaBlend(imgDestination.Canvas.Handle, 0, 0, imgDestination.Width, imgDestination.Height, imgSecond.Canvas.Handle, 0, 0, imgSecond.Width, imgSecond.Height, udtBlender); end; Once your program is compiled you can see AlphaBlend in action by moving the TrackBar cursor. The parameter accepted by the API are the destination HDC, the coordinates of destination rectangle, the source HDC, the coordinates of destination rectangle and a TBlendFunction structure whose fields contains informations about the action to take. Oddly enough the only field of interest is the SourceConstantAlpa that contains the blend value to use for source bitmap: the only admitted value for BlendOp field is AC_SRC_OVER, the BlendFlags must be zero and the AlphaFormat needs to be filled only if the source bitmap has an alpha channel information. Once the destination image has been draw, you can save the resulting image just by saving the destination Picture to the disk: ... imgDestination.Picture.SaveToFile('foo.bmp'); ... Despite the pretty results you can obtain with this function, I believe that the AlphaBlend function is not very useful but for multimedia writers who needs a blending effect without writing too much code or component writers who wants to imitate the UI graphical effects. Enjoy!