Skip to content

Instantly share code, notes, and snippets.

@c-smile
Created November 24, 2016 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c-smile/7f2ae24da7ab638548ce7a1ecda49da0 to your computer and use it in GitHub Desktop.
Save c-smile/7f2ae24da7ab638548ce7a1ecda49da0 to your computer and use it in GitHub Desktop.
DIB (device independent bitmap) combined with HDC (device context)
#include <windows.h>
class dib32
{
const unsigned _width;
const unsigned _height;
void* _bits;
mutable HBITMAP _old_bitmap;
mutable HDC _dc;
HBITMAP _bitmap;
BITMAPINFO _bitmap_info;
public:
dib32(unsigned w, unsigned h) :
_width(w),
_height(h),
_bits(0),
_old_bitmap(0),
_dc(0) {
memset(&_bitmap_info,0,sizeof(_bitmap_info));
_bitmap_info.bmiHeader.biSize = sizeof(_bitmap_info.bmiHeader);
_bitmap_info.bmiHeader.biWidth = _width;
_bitmap_info.bmiHeader.biHeight = 0 - int(_height);
_bitmap_info.bmiHeader.biPlanes = 1;
_bitmap_info.bmiHeader.biBitCount = 32;
_bitmap_info.bmiHeader.biCompression = BI_RGB;
_bitmap = ::CreateDIBSection(
NULL, // device context
&_bitmap_info,
DIB_RGB_COLORS,
&_bits,
0, // file mapping object
0); // file offset
if (0 == _bits) {
return;
//throw std::bad_alloc();
}
memset(_bits,0, _width * _height * 4);
}
~dib32() {
if( _dc )
{
::SelectObject(_dc,_old_bitmap);
::DeleteDC(_dc);
}
if( _bitmap )
::DeleteObject(_bitmap);
}
void set_white()
{
memset(_bits,0xff, _width * _height * 4);
}
unsigned width() const { return _width; }
unsigned height() const { return _height; }
void* bits() const { return _bits; }
BYTE* bytes() const { return (BYTE*)_bits; }
HDC DC() const
{
if(!_dc) {
_dc = ::CreateCompatibleDC(NULL);
if (_dc)
_old_bitmap = (HBITMAP)::SelectObject(_dc,_bitmap);
}
return _dc;
}
HBITMAP detach() { auto r = _bitmap; _bitmap = 0; return r; }
const BITMAPINFO& get_info() const { return _bitmap_info; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment