Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!


We're also offering banner ads on our site from just $5! 1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.






Blitting with per-pixel alpha in Win32

  Posted by jwezorek, 04 February 2012 · 1,385 views

I don't know how long the Win32 API has included an AlphaBlend() function. I mean, it came in whenever Msimg32.lib did but I'm not sure when that was, probably Windows XP era, I guess.

It's always been a pain in the ass to use; easy to use global alpha but per-pixel is a chore. You see a lot of people asking how to use this call at StackOverflow and other sites but basically never see a comprehensive reply. Generally the replies are variants of "It's easy. you just need to pre-multiply the alpha", which is true but unhelpful for two reasons: (1) doing so is a pain in the ass i.e. show me some code, buddy, and more importantly (2) in order to burn the alpha values into the RGB you need to actually have image data that contains an alpha channel but Win32 only natively supports loading BMP's which generally don't.

So on (2), for completeness, I should say I think that it is possible to get Photoshop to spit out a BMP file with alpha information. I haven't tried it but the advanced options when saving a BMP have an option for the format "a8 r8 g8 b8". I always see it grayed out but am guessing that it's possible to do this somehow. Also I think that you can load PNG's using GDI+; I know next to nothing about GDI+ but if that's what you use I'm not sure the solution I propose below is worth it just to get out of having to write the pre-multiply function yourself.

However, the above aside, if you want alpha-blended images in your application, you want to use PNG files ,and if you are writing to Win32 you need to use a 3rd-party library. The two 3rd party graphics libraries that people commonly use in Windows applications for things like loading PNG's and JPEG's are DevIL and FreeImage. I have no experience with DevIL and, frankly, it looks orphaned to me. What I suggest for blitting with semi-transparency in Win32 is using FreeImage, which seems tailor-made for doing this.
So below is an implementation on top of FreeImage demonstrating
  • Loading PNG's (and other formats) as FreeImage data structures from Win32 resources.
  • Converting from FreeImage to HBITMAPs with alpha burned in.
  • Blitting the HBITMAPs with per-pixel alpha.
Here's the code I use for loading a PNG from a resource to FreeImage's data structures. FimgUtil::MemPtr and FimgUtil::Ptr are defined as
boost::shared_ptr<FIMEMORY>
boost::shared_ptr<FIBITMAP>
That is, I'm using smart pointers with custom deleters to call the appropiate FreeImage clean-up code on destruction. If this isn't your style the following code can easily be modified to use raw pointers.

[source lang="cpp"]namespace { bool GetResourceData(const char* name, BYTE*& ptr, unsigned long& size) { HRSRC hrsrc = FindResource(NULL, name, RT_RCDATA); if (hrsrc == NULL) { return false; } HGLOBAL handle = LoadResource(NULL, hrsrc); if (handle == NULL) { return false; } ptr = static_cast<BYTE*>(LockResource(handle)); size = SizeofResource(NULL, hrsrc); return true; }}FimgUtil::MemPtr FimgUtil::GetMemoryPtr(FIMEMORY* fimem) { return FimgUtil::MemPtr(fimem, FreeImage_CloseMemory);}FimgUtil::Ptr FimgUtil::GetBitmapPtr(FIBITMAP* fibmp) { return FimgUtil::Ptr(fibmp, FreeImage_Unload);}FimgUtil::Ptr FimgUtil::LoadFiBitmapFromResource(const char* rsrc_name, FREE_IMAGE_FORMAT format) { BYTE* data; unsigned long size = 0; if (! GetResourceData(rsrc_name, data, size)) { return FimgUtil::Ptr (); } FimgUtil::MemPtr buff = GetMemoryPtr(FreeImage_OpenMemory(data, size)); if (buff.get() == 0) { return FimgUtil::Ptr (); } if (format == FIF_UNKNOWN) { format = FreeImage_GetFileTypeFromMemory(buff.get(), 0); if (format == FIF_UNKNOWN) { return FimgUtil::Ptr (); } } return GetBitmapPtr( FreeImage_LoadFromMemory(format, buff.get(), 0) );}[/source]

To convert from an FIBITMAP* to a an HBITMAP and rolled together with the above:
[source lang="cpp"]HBITMAP FimgUtil::FiBitmapToWin32Bitmap(const FimgUtil::Ptr & src_ptr, bool premultiply_alpha) { if (premultiply_alpha) { FreeImage_PreMultiplyWithAlpha( src_ptr.get() ); } HDC hdc_scr = GetDC(NULL); FIBITMAP* src = src_ptr.get(); HBITMAP hbm = CreateDIBitmap( hdc_scr, FreeImage_GetInfoHeader(src), CBM_INIT, FreeImage_GetBits(src), FreeImage_GetInfo(src), DIB_RGB_COLORS); ReleaseDC(NULL, hdc_scr); return hbm;}HBITMAP FimgUtil::LoadPngResource( const char* rsrc_name, bool premultiply_alpha) { FimgUtil::Ptr fibmp = LoadFiBitmapFromResource( rsrc_name, FIF_PNG ); return FiBitmapToWin32Bitmap( fibmp, premultiply_alpha);}[/source]
and a wrapper for blitting:


void FimgUtil::BlitWithAlpha( HDC dst, int dst_x, int dst_y, int wd, int hgt, HDC src, int src_x, int src_y, float alpha ) {
	BLENDFUNCTION bf;

	ZeroMemory( &bf, sizeof(BLENDFUNCTION) );
	bf.BlendOp = AC_SRC_OVER;
	bf.BlendFlags = 0;
	bf.AlphaFormat = AC_SRC_ALPHA;
	bf.SourceConstantAlpha = static_cast<BYTE>( 255 * alpha );

	AlphaBlend( dst, dst_x, dst_y, wd, hgt, src, src_x, src_y, wd, hgt, bf);
}


Source for my FreeImage utility functions is here.
Source




Also I think that you can load PNG's using GDI+

Yeah it does. It's quite simple too. This is the error-checking-less bones of initialising, loading a BMP, TIFF, PNG, GIF, ICO or (W|E)MF from a resource, and natively drawing it on the screen.

namespace Gp = Gdiplus;
ULONG_PTR cookie = 0;
Gp::GdiplusStartupInput inp;
Gp::GdiplusStartup(&cookie, &inp, NULL);
HDC hdcDesk = GetDC(NULL);
{
   Gp::Bitmap image(hModule, resourceName);
   Gp::Graphics grap(hdcDesk);
   grap.DrawImage(&bm, 0, 0);
}
ReleaseDC(NULL, hdcDesk);
Gp::GdiplusShutdown(cookie);

After you remove the init and shutdown, it's about 5 lines for the important work. It can also provide you with a suitably formatted HBITMAP of the image data, which has per-pixel alpha values which can then be passed to AlphaBlend() as desired.

For C only development, there's currently the IShellImageData (http://msdn.microsoft.com/en-us/library/bb761207.aspx) COM object which is a wrapper around the basic GDI+ operations.

Oh and AlphaBlend's been around since the first version of Win98 :-)

Good old Alphablend()... brings back memories of screwing around with Win32 using Delphi 3.. haha. Good times!

PARTNERS