Blitting with per-pixel alpha in Win32

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 the 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.

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

To convert from an FIBITMAP* to a an HBITMAP and rolled together with the above:

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

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.

Leave A Comment

Your email address will not be published.