code_junkie

How to Create a Gdiplus::Bitmap from an HBITMAP, retaining the alpha channel information?

Nov 12th, 2011
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. #include <GdiPlus.h>
  2. #include <memory>
  3.  
  4. Gdiplus::Status HBitmapToBitmap( HBITMAP source, Gdiplus::PixelFormat pixel_format, Gdiplus::Bitmap** result_out )
  5. {
  6. BITMAP source_info = { 0 };
  7. if( !::GetObject( source, sizeof( source_info ), &source_info ) )
  8. return Gdiplus::GenericError;
  9.  
  10. Gdiplus::Status s;
  11.  
  12. std::auto_ptr< Gdiplus::Bitmap > target( new Gdiplus::Bitmap( source_info.bmWidth, source_info.bmHeight, pixel_format ) );
  13. if( !target.get() )
  14. return Gdiplus::OutOfMemory;
  15. if( ( s = target->GetLastStatus() ) != Gdiplus::Ok )
  16. return s;
  17.  
  18. Gdiplus::BitmapData target_info;
  19. Gdiplus::Rect rect( 0, 0, source_info.bmWidth, source_info.bmHeight );
  20.  
  21. s = target->LockBits( &rect, Gdiplus::ImageLockModeWrite, pixel_format, &target_info );
  22. if( s != Gdiplus::Ok )
  23. return s;
  24.  
  25. if( target_info.Stride != source_info.bmWidthBytes )
  26. return Gdiplus::InvalidParameter; // pixel_format is wrong!
  27.  
  28. CopyMemory( target_info.Scan0, source_info.bmBits, source_info.bmWidthBytes * source_info.bmHeight );
  29.  
  30. s = target->UnlockBits( &target_info );
  31. if( s != Gdiplus::Ok )
  32. return s;
  33.  
  34. *result_out = target.release();
  35.  
  36. return Gdiplus::Ok;
  37. }
Add Comment
Please, Sign In to add comment