How to Load Bitmap and Access the Bitmap Data?

28 12 2008

While doing image processing, you will be loading the bitmap, access each pixel, process it and set it back. You can get/set each pixel by calling functions which is time consuming. Well, It will be nice if its possible to access the entire bitmap buffer and process it. Since access the data by pointers is so fast compared to get/set each pixel by function calls. But how to load the bitmap, cut it and access the bitmap data? 😉


You can load the bitmap by using LoadImage() and can call GetBitmapBits() to access the pixel data of bitmap. After processing, you can call SetBitmapBits() to set the processed data back to bitmap. Check the code snippet below.

// Load and process the bitmap data.
void LoadAndProcessBitmap( TCHAR* pBitmapPath )
    // Load the image bitmapt.
    HBITMAP hBitmap = 0;
    hBitmap = (HBITMAP)LoadImage( NULL,
                                  LR_LOADFROMFILE | LR_DEFAULTSIZE);

    // Access bitmap data.
    CBitmap Bitmap;
    Bitmap.Attach( hBitmap );

    // Calculate buffer for bitmap bits.
    BITMAP BitmapInfo = { 0 };
    Bitmap.GetBitmap( &BitmapInfo );

    // Calculate the size of required buffer.
    DWORD BitmapImageSize = BitmapInfo.bmHeight *
        BitmapInfo.bmWidth *
        ( BitmapInfo.bmBitsPixel / 8 );

    // Allocate memory.
    BYTE* pBitmapData = new BYTE[ BitmapImageSize ];
    ZeroMemory( pBitmapData, BitmapImageSize );

    // Get bitmap data.
    Bitmap.GetBitmapBits( BitmapImageSize, pBitmapData );

    // Now access and process bitmap data
    // as you wish!

    // Now after processing, set the bitmap data back.
    Bitmap.SetBitmapBits( BitmapImageSize, pBitmapData );

    // Now you can use the processed bitmap for your purpose.
    // For instance, save to disk, display in your dialog etc.

    // Delete bitmap data after use.
    delete pBitmapData;
    pBitmapData = 0;

Here I’ve used CBitmap for ease. But this one can be done with pure windows apis as well.

Targeted Audience – Intermediate.




2 responses

23 04 2009

Very nice indeed….I was looking for something that simple. All the internet is full of chunky examples hard to follow.

27 04 2009

Thanks Gabriel! Thanks for those kind words. Well, keep watching. 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: