flydev
flydev

Reputation: 5714

Compare two bitmap (device context - file)

I need to compare two bitmaps. One bitmap is loaded from a file, the second is a bitmap from a device context. The file bitmap is generated by the same program for test-purpose.

I am programming on vc10 / win7

I deliberately not handle error to keep clear the code on this post.

First step, I make a rgb24 bitmap file and save it as "test.bmp" :

void GetBitmap24FromDcToFile(HDC winDC, int x, int y, int w, int h)
{
int imgsize;

if((3 * w) % 4 > 0)
    imgsize = ((3 * w) / 4 + 1) * 4 * h;
else if((3 * w) % 4 == 0)
    imgsize = 3 * w * h;

BITMAPINFO bi;
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = h;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 24;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biSizeImage = imgsize;
bi.bmiHeader.biXPelsPerMeter = 0;
bi.bmiHeader.biYPelsPerMeter = 0;
bi.bmiHeader.biClrUsed = 0;
bi.bmiHeader.biClrImportant = 0;

void *pvBits = NULL;
HBITMAP hbmp = ::CreateDIBSection(winDC, &bi, DIB_RGB_COLORS, &pvBits, NULL, 0);
HDC hdc = ::CreateCompatibleDC(winDC);
HBITMAP holdbmp = (HBITMAP)::SelectObject(hdc, hbmp);
::BitBlt(hdc, 0, 0, w, h, winDC, x, y, SRCCOPY);

HANDLE hFile = ::CreateFile(_T("test.bmp"), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

DWORD dwCnt;
BITMAPFILEHEADER bmfh;

ZeroMemory(&bmfh, sizeof(BITMAPFILEHEADER));
bmfh.bfType = 0x4d42;
bmfh.bfSize = imgsize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

WriteFile(hFile, (char*)&bmfh, sizeof(BITMAPFILEHEADER), &dwCnt, NULL);
WriteFile(hFile, (char*)&bi.bmiHeader, sizeof(BITMAPINFOHEADER), &dwCnt, NULL);
WriteFile(hFile, (char*)pvBits, imgsize, &dwCnt, NULL);
CloseHandle(hFile);

::SelectObject(hdc, holdbmp);
::DeleteDC(hdc);
::DeleteObject(hbmp);
}

Second step, i make a bitmap from a device context :

HBITMAP GetBitmap24FromDC(HDC winDC, int x, int y, int w, int h)
{
HDC  hMemDC = ::CreateCompatibleDC( winDC );
HBITMAP hbmp; // = ::CreateCompatibleBitmap( winDC, w, h);

BITMAPINFOHEADER infoHeader; 
infoHeader.biSize          = sizeof(infoHeader); 
infoHeader.biWidth         = (LONG)w; 
infoHeader.biHeight        = (LONG)h; 
infoHeader.biPlanes        = 1; 
infoHeader.biBitCount      = 24; 
infoHeader.biCompression   = BI_RGB; 
infoHeader.biSizeImage     = 0; 
infoHeader.biXPelsPerMeter = 0; 
infoHeader.biYPelsPerMeter = 0; 
infoHeader.biClrUsed       = 0; 
infoHeader.biClrImportant  = 0; 

BITMAPINFO info; 
info.bmiHeader = infoHeader; 

unsigned char *mem;
hbmp = CreateDIBSection(winDC, &info, DIB_RGB_COLORS, (void**)&mem, 0, 0);
HBITMAP holdbmp = (HBITMAP) ::SelectObject(hMemDC, hbmp); 
::BitBlt(hMemDC, 0, 0, w, h, winDC, x, y, SRCCOPY);
    ::SelectObject(hMemDC, holdbmp);
::DeleteDC(hMemDC);

return hbmp;
}

And i use this method for comparaison :

// Author: PJ Arends - codeproject
bool CompareBitmaps(HBITMAP HBitmapLeft, HBITMAP HBitmapRight)
{
if (HBitmapLeft == HBitmapRight)
{
    return true;
}

if (NULL == HBitmapLeft || NULL == HBitmapRight)
{
    return false;
}

bool bSame = false;

HDC hdc = GetDC(NULL);
BITMAPINFO BitmapInfoLeft = {0};
BITMAPINFO BitmapInfoRight = {0};

BitmapInfoLeft.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
BitmapInfoRight.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);

if (0 != GetDIBits(hdc, HBitmapLeft, 0, 0, NULL, &BitmapInfoLeft, DIB_RGB_COLORS) &&
    0 != GetDIBits(hdc, HBitmapRight, 0, 0, NULL, &BitmapInfoRight, DIB_RGB_COLORS))
{
    // Compare the BITMAPINFOHEADERs of the two bitmaps

    if (0 == memcmp(&BitmapInfoLeft.bmiHeader, &BitmapInfoRight.bmiHeader, 
        sizeof(BITMAPINFOHEADER)))
    {
        // The BITMAPINFOHEADERs are the same so now compare the actual bitmap bits

        BYTE *pLeftBits = (BYTE*)malloc(sizeof(BYTE) * BitmapInfoLeft.bmiHeader.biSizeImage);
        BYTE *pRightBits = (BYTE*)malloc(sizeof(BYTE) * BitmapInfoRight.bmiHeader.biSizeImage);
        BYTE *pByteLeft = NULL;
        BYTE *pByteRight = NULL;

        PBITMAPINFO pBitmapInfoLeft = &BitmapInfoLeft;
        PBITMAPINFO pBitmapInfoRight = &BitmapInfoRight;

        // calculate the size in BYTEs of the additional

        // memory needed for the bmiColor table

        int AdditionalMemory = 0;
        switch (BitmapInfoLeft.bmiHeader.biBitCount)
        {
        case 1:
            AdditionalMemory = 1 * sizeof(RGBQUAD);
            break;
        case 4:
            AdditionalMemory = 15 * sizeof(RGBQUAD);
            break;
        case 8:
            AdditionalMemory = 255 * sizeof(RGBQUAD);
            break;
        case 16:
        case 32:
            AdditionalMemory = 2 * sizeof(RGBQUAD);
        }

        if (AdditionalMemory)
        {
            // we have to allocate room for the bmiColor table that will be

            // attached to our BITMAPINFO variables

            pByteLeft = new BYTE[sizeof(BITMAPINFO) + AdditionalMemory];
            if (pByteLeft)
            {
                memset(pByteLeft, 0, sizeof(BITMAPINFO) + AdditionalMemory);
                memcpy(pByteLeft, pBitmapInfoLeft, sizeof(BITMAPINFO));
                pBitmapInfoLeft = (PBITMAPINFO)pByteLeft;
            }

            pByteRight = new BYTE[sizeof(BITMAPINFO) + AdditionalMemory];
            if (pByteRight)
            {
                memset(pByteRight, 0, sizeof(BITMAPINFO) + AdditionalMemory);
                memcpy(pByteRight, pBitmapInfoRight, sizeof(BITMAPINFO));
                pBitmapInfoRight = (PBITMAPINFO)pByteRight;
            }
        }

        if (pLeftBits && pRightBits && pBitmapInfoLeft && pBitmapInfoRight)
        {
            // zero out the bitmap bit buffers

            memset(pLeftBits, 0, BitmapInfoLeft.bmiHeader.biSizeImage);
            memset(pRightBits, 0, BitmapInfoRight.bmiHeader.biSizeImage);

            // fill the bit buffers with the actual bitmap bits

            if (0 != GetDIBits(hdc, HBitmapLeft, 0, 
                pBitmapInfoLeft->bmiHeader.biHeight, pLeftBits, pBitmapInfoLeft, 
                DIB_RGB_COLORS) && 0 != GetDIBits(hdc, HBitmapRight, 0, 
                pBitmapInfoRight->bmiHeader.biHeight, pRightBits, pBitmapInfoRight, 
                DIB_RGB_COLORS))
            {
                // compare the actual bitmap bits of the two bitmaps

                bSame = 0 == memcmp(pLeftBits, pRightBits, 
                    pBitmapInfoLeft->bmiHeader.biSizeImage);
            }
        }

        // clean up
        free(pLeftBits);
        free(pRightBits);
        free(pByteLeft);
        free(pByteRight);
    }
}

ReleaseDC(NULL, hdc);

return bSame;
}

So, in my main code i have something like that :

   (...)
   HWND capture = ::FindWindow(_T("the_window_class"), NULL);
   HDC winDC = ::GetDC(capture);
   GetBitmap24FromDcToFile(winDC, 0, 0, 200, 200); // generate bitmap file "test.bmp"
   HBITMAP bmpFile = (HBITMAP)LoadImage( NULL, _T("test.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION ); 
   HBITMAP bmpMem  = GetBitmap24FromDC(winDC, 0, 0, 200, 200); // get bitmap from DC

   bool isEqual = CompareBitmaps(bmpFile, bmpMem); // test both bitmaps
   if(isEqual)
      AfxMessageBox(_T("Success"));
   (...)

Comparaison between two files return true; two bitmaps from dc return true; Comparaison between a bitmap file and a dc bitmap always return false.

After debugging, it passe the first test-condition (in the Compare method) where we check the BITMAPINFOHEADERs. It fail on the last memcmp() where we compare the bits of the two bitmaps.

In the debugger, the structure are the same for both bitmaps, I have only a small difference between the two pBitmapInfoLeft\pBitmapInfoRight->bmiColors field.

Checking the bits from the two bitmaps headers are the same (pLeftBits\pRightBits).

An idea, an alternative, an example? let me know! thank you!

Upvotes: 0

Views: 2509

Answers (2)

valdo
valdo

Reputation: 12951

There's a sort of a bug though.

You use the BITMAPINFO structure, which is actually a fake, not designed to be used as-is.

The actual bitmap header consists of a fixed BITMAPINFOHEADER structure, and a variable-sized array of RGBQUAD structures, whereas the size of this array depends on the data in the BITMAPINFOHEADER. Depending on the bitmap bitness, this array should have the following length:

  • 1/4/8: the array size should be 2^bitness. I.e. 2/16/256 respectively. The bitmap is considered indexed, and the values in this array define the actual colors.
  • 16: The pixel values translate into colors using so-called bitfields. The array size depends on biCompression member:
    • BI_RGB: the array should be empty. Default bitfields 5-5-5 are used.
    • BI_BITFIELDS: The array should have 3 entries. The define the appropriate bitmasks for R/G/B channels.
  • 32: The pixel values either directly correspond to the colors, or translate using bitfields if biCompression is set to BI_BITFIELDS. As with 16-bit case, the array should be either empty or have 3 entries.

The BITMAPINFO structure consists of the BITMAPINFO structure (bmiHeader), and bmiColors, which always has one entry. Which is never the case.

That's why BITMAPINFO is actually a fake structure. In order to create the bitmap header one should first allocate the needed amount of memory for the BITMAPINFOHEADER and the needed array, and then cast it to the BITMAPINFO.

In simple words: comparing BITMAPINFO structures (i.e. using sizeof(BITMAPINFO)) doesn't make sense. The bmiColors will either contain uninitialized data, or be inaccessible, or will actually have larger size.

P.S. BTW, the whole bitmap comparison is somewhat dirty IMHO. Saving the bitmap to the file, just to compare - looks insane. Also you don't actually need to allocate the memory for the whole bitmap, it may be compared line-by-line.

Also, if one of the bitmaps is a DIB, you may directly get pointer to its bits, hence allocating extra memory and copying is not needed.

Upvotes: 4

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39400

I believe you could use SoIL Library (or any other than WinApi, actually) for loading and operating on bitmap files. It's free and lightweight, and will shorten your code by about 90%.

Upvotes: 1

Related Questions