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? 😉

accessbitmapdata2


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,
                                  pBitmapPath,
                                  IMAGE_BITMAP,
                                  0,
                                  0,
                                  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.

Advertisements