Introduction
A simple function to load a bitmap in Win32 GDI to be used by the Sprite-class for SFML.
Using the code
The code is a simple function that you can copy and paste into your Win32 project:
bool SFMLLoadHBitmapAsImage(HBITMAP hBitmap, sf::Image *pPicture)
{
HDC hDC = GetDC( ::GetDesktopWindow() );
BITMAPINFO MyBMInfo = {0};
MyBMInfo.bmiHeader.biSize = sizeof( MyBMInfo.bmiHeader );
if( 0 == GetDIBits(hDC, hBitmap, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
{
return false;
}
BYTE* lpPixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];
MyBMInfo.bmiHeader.biCompression = BI_RGB;
if (0 == GetDIBits(hDC, hBitmap, 0, MyBMInfo.bmiHeader.biHeight, (LPVOID)lpPixels, &MyBMInfo, DIB_RGB_COLORS))
{
return false;
}
sf::Uint8 *lpPixelWithAlpha = new sf::Uint8[ MyBMInfo.bmiHeader.biSizeImage +
(MyBMInfo.bmiHeader.biSizeImage/3)/3 ];
for(int x=0;x<MyBMInfo.bmiHeader.biSizeImage;x+=4)
{
lpPixelWithAlpha[x] = lpPixels[x+2]; lpPixelWithAlpha[x+1] = lpPixels[x+1]; lpPixelWithAlpha[x+2] = lpPixels[x]; lpPixelWithAlpha[x+3] = 255; }
delete[] lpPixels;
if( false == pPicture->LoadFromPixels(MyBMInfo.bmiHeader.biWidth,
MyBMInfo.bmiHeader.biHeight, lpPixelWithAlpha))
{
return false;
}
delete[] lpPixelWithAlpha;
ReleaseDC(::GetDesktopWindow(), hDC);
return true;
}
To use the function in your load-procedure, use it like this. Note that the
Screenshot
function can be located here.
sf::Image m_mypicture;
HBITMAP hBitmap = ScreenShot( http:
if( false == SFMLLoadHBitmapAsImage(hBitmap, &my_picture) )
{
}
sf::Sprite m_mysprite.SetImage(m_mypicture);
m_mysprite.FlipY(true);
Got any other ways to do this? Please comment. If other formats are needed, an integration
with GDI+ could be made, it natively supports PNG, GIF, JPG, etc...
History
- v1.0 - First release (and probably the only release).