Copying from a packed DIB void pointer - c++

I am working on an API to cache GDI objects, written in C++, in which I am implementing different Create methods that imitate the win32 API. One such method is CreateDIBPatternBrushPt(), which takes in a VOID* to a packed DIB. The VOID* contains a BITMAPINFO structure followed immediately by an array of bytes defining the pixels of the bitmap. I did some research on packed DIBs. According to the book, Programming Windows, as well as Wikipedia the length is equal to the product of the row length and biHeight (a member of BITMAPINFOHEADER), where:
RowLength = 4 * ((bmi.bcWidth * bmi.bcBitCount + 31) / 32) ;
So, currently my thought is to do something like this:
//copy BIMAPINFO to access width and height
//lpPackedDIB is the VOID* parameter of CreateDIBPatternBrushPt()
BITMAPINFO tmpBitmapInfo;
std::memcpy(&tmpBitmapInfo, lpPackedDIB, sizeof(BITMAPINFO));
//copy entire packed DIB
int rowLength = 4 * ((tmpBitmapInfo.bmiHeader.biWidth * tmpBitmapInfo.bmiHeader.biBitCount + 31) / 32);
std::memcpy(m_pPackedDIB, lpPackedDIB, sizeof(BITMAPINFO) + rowLength * std::abs(bitmapInfo.bmiHeader.biHeight));
Does this seem like a valid way to do this? I would also like to know where lpPackedDIB would come from for people who use CreateDIBPatternBrushPt(), so that I can properly test this logic.
EDIT:
References:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd183493(v=vs.85).aspx
https://en.wikipedia.org/wiki/BMP_file_format#File_structure
https://www-user.tu-chemnitz.de/~heha/petzold/ch15b.htm (particularly "The DIB Pixel Bits" section)

This answer was posted before, but taken down for some reason. It doesn't directly address the question, but it gives good insight to the problem I was facing. Credit to user: Barmak Shemirani.
You can simply use CreatePatternBrush to get HBRUSH from HBITAMP
Or use CreateDIBPatternBrushPt. However, note that packed dib is only 14 bytes smaller, since it doesn't need BITMAPFILEHEADER. This makes it useful for very small brushes. For example a 2x1 green/black brush:
typedef struct
{
BITMAPINFOHEADER header;
unsigned char bits[2 * 1 * 4];
} DIBSTRUCT;
const DIBSTRUCT dib =
{
{ sizeof(BITMAPINFOHEADER), 2, 1, 1, 32, BI_RGB, 0, 0, 0, 0, 0 },
{ 0,0xff,0,0, 0,0,0,0 }
};
HBRUSH hbrush = CreateDIBPatternBrushPt(&dib, DIB_RGB_COLORS);
You can make the brush from bitmap file as well. Allocate the dib, add room for BITMAPINFOHEADER and color table. Then copy BITMAPINFOHEADER, followed by color table (if any), followed by pixels. Example:
HBRUSH getbrush(HBITMAP hbitmap)
{
BITMAP bm;
GetObject(hbitmap, sizeof(bm), &bm);
int colorCount = 0;
if (bm.bmBitsPixel == 1) colorCount = 2;
if (bm.bmBitsPixel == 4) colorCount = 16;
if (bm.bmBitsPixel == 8) colorCount = 256;
RGBQUAD rgb[256];
if (colorCount)
{
HDC memdc = CreateCompatibleDC(NULL);
HGDIOBJ oldbitmap = SelectObject(memdc, hbitmap);
GetDIBColorTable(memdc, 0, colorCount, rgb);
SelectObject(memdc, oldbitmap);
DeleteDC(memdc);
}
BITMAPINFOHEADER bminfo = { sizeof(BITMAPINFOHEADER),
bm.bmWidth, bm.bmHeight, 1, bm.bmBitsPixel, BI_RGB, 0, 0, 0, 0, 0 };
DWORD size = ((bm.bmWidth * bm.bmBitsPixel + 31) / 32) * 4 * bm.bmHeight;
char *dib = new char[sizeof(BITMAPINFOHEADER) + colorCount * 4 + size];
memcpy(dib, &bminfo, sizeof(BITMAPINFOHEADER));
memcpy(dib + sizeof(BITMAPINFOHEADER), rgb, colorCount * 4);
memcpy(dib + sizeof(BITMAPINFOHEADER) + colorCount * 4, bm.bmBits, size);
HBRUSH hbrush = CreateDIBPatternBrushPt(dib, DIB_RGB_COLORS);
//clearnup
DeleteObject(hbitmap);
delete[]dib;
return hbrush;
}

Related

GetDIBits() sets destination pointer to NULL with no error

I am trying to put an application icon into a char array. The code below converts a HICON into a BITMAP, then attempts to extract the bytes from the BITMAP into a char array. As I step through the code, I observed that the second GetDIBits() modifies the destination pointer to NULL despite claiming 16 bytes were written. This behavior is very puzzling. I suspect that casting BITMAPINFOHEADER* into BITMAPINFO* might be problematic, but using a BITMAPINFO directly causes stack corruption upon exiting the function. Does anyone know why GetDIBits() behaves in such a way?
std::unique_ptr<char> getRawImg(HICON& icon)
{
// step 1 : get a bitmap from an application icon
ICONINFO iconInfo;
ZeroMemory(&iconInfo, sizeof(iconInfo));
BITMAP bitMap;
ZeroMemory(&bitMap, sizeof(bitMap));
HRESULT bRes = GetIconInfo(icon, &iconInfo);
int width;
int height;
int bitsPerPixel;
if (iconInfo.hbmColor) // color icon
{
if (GetObject(iconInfo.hbmColor, sizeof(bitMap), &bitMap))
{
width = bitMap.bmWidth;
height = bitMap.bmHeight;
bitsPerPixel = bitMap.bmBitsPixel;
}
}
else if (iconInfo.hbmMask) // black and white icon
{
if (GetObject(iconInfo.hbmMask, sizeof(bitMap), &bitMap))
{
width = bitMap.bmWidth;
height = bitMap.bmHeight / 2;
bitsPerPixel = 1;
}
}
// step 2 : extract bytes from the bitmap into a byte array
HBITMAP hBitmap = CreateBitmapIndirect(&bitMap);
int stride = (width * bitsPerPixel + 31) / 32 * 4;
HDC hdc = GetDC(NULL);
BITMAPINFOHEADER bi;
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = width;
bi.biHeight = height;
bi.biPlanes = 1;
bi.biBitCount = bitsPerPixel;
bi.biCompression = BI_RGB;
bi.biSizeImage = stride * height;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
BITMAPINFO* pBitmapInfo = (BITMAPINFO*)&bi;
if (!GetDIBits(hdc, hBitmap, 0, 0, NULL, pBitmapInfo, DIB_RGB_COLORS)) {
// error
std::cout << "failed to get bitmap info" << std::endl;
}
std::unique_ptr<char> buffer(new char[bi.biWidth * bi.biHeight * bi.biBitCount / 8]);
// Buffer points to some address before calling GetDIBits(). After calling GetDIBits(), buffer points to NULL. bytesWritten is 16
int bytesWritten = GetDIBits(hdc, hBitmap, 0, height, (LPVOID)buffer.get(), pBitmapInfo, DIB_RGB_COLORS);
if (bytesWritten <= 0) {
// error
std::cout << "failed" << std::endl;
}
DeleteObject(hBitmap);
ReleaseDC(NULL, hdc);
if (iconInfo.hbmColor)
DeleteObject(iconInfo.hbmColor);
if (iconInfo.hbmMask)
DeleteObject(iconInfo.hbmMask);
return buffer;
}
You need to allocate a suitably-sized BITMAPINFO and cast it to BITMAPINFOHEADER* (or just use its bmiHeader member). Not allocate a BITMAPINFOHEADER and cast it to BITMAPINFO*. A BITMAPINFO consists of a BITMAPINFOHEADER followed by an array of 0 or more RGBQUAD elements for a color table. A BITMAPINFOHEADER itself does not contain the color table, but it does describe the color table that follows it.
Per the GetDIBits() documentation:
If the requested format for the DIB matches its internal format, the RGB values for the bitmap are copied. If the requested format doesn't match the internal format, a color table is synthesized...
If the lpvBits parameter is a valid pointer, the first six members of the BITMAPINFOHEADER structure must be initialized to specify the size and format of the DIB. The scan lines must be aligned on a DWORD except for RLE compressed bitmaps.
A bottom-up DIB is specified by setting the height to a positive number, while a top-down DIB is specified by setting the height to a negative number. The bitmap color table will be appended to the BITMAPINFO structure.
If lpvBits is NULL, GetDIBits examines the first member of the first structure pointed to by lpbi. This member must specify the size, in bytes, of a BITMAPCOREHEADER or a BITMAPINFOHEADER structure. The function uses the specified size to determine how the remaining members should be initialized.
If lpvBits is NULL and the bit count member of BITMAPINFO is initialized to zero, GetDIBits fills in a BITMAPINFOHEADER structure or BITMAPCOREHEADER without the color table. This technique can be used to query bitmap attributes.
So, in your case, you are setting lpvBits to NULL, but the BITMAPINFOHEADER::biBitCount field is not 0, so GetDIBits() will try to fill in the color table of the provided BITMAPINFO, but you are not allocating any memory to receive that color table. So GetDIBits() ends up corrupting the memory that follows the BITMAPINFOHEADER.
I think you did not guarantee that the hbm parameter of GetDIBits is compatible bitmap during the process of converting HICON to HBITMAP.
Try to use the following code and test :
#include <iostream>
#include <windows.h>
using namespace std;
HBITMAP getBmp(HICON hIcon)
{
HDC hDC = GetDC(NULL);
HDC hMemDC = CreateCompatibleDC(hDC);
HBITMAP hMemBmp = CreateCompatibleBitmap(hDC, 32, 32);
HBITMAP hResultBmp = NULL;
HGDIOBJ hOrgBMP = SelectObject(hMemDC, hMemBmp);
DrawIconEx(hMemDC, 0, 0, hIcon, 32, 32, 0, NULL, DI_NORMAL);
hResultBmp = hMemBmp;
hMemBmp = NULL;
SelectObject(hMemDC, hOrgBMP);
DeleteDC(hMemDC);
ReleaseDC(NULL, hDC);
DestroyIcon(hIcon);
return hResultBmp;
}
BYTE* getPixArray(HBITMAP hBitmap)
{
HDC hdc, hdcMem;
hdc = GetDC(NULL);
hdcMem = CreateCompatibleDC(hdc);
BITMAPINFO MyBMInfo = { 0 };
MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
if (0 == GetDIBits(hdcMem, hBitmap, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
{
cout << " fail " << endl;
}
BYTE* lpPixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];
MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
MyBMInfo.bmiHeader.biBitCount = 32;
MyBMInfo.bmiHeader.biCompression = BI_RGB;
MyBMInfo.bmiHeader.biHeight = (MyBMInfo.bmiHeader.biHeight < 0) ? (-MyBMInfo.bmiHeader.biHeight) : (MyBMInfo.bmiHeader.biHeight);
// get the actual bitmap buffer
if (0 == GetDIBits(hdc, hBitmap, 0, MyBMInfo.bmiHeader.biHeight, (LPVOID)lpPixels, &MyBMInfo, DIB_RGB_COLORS))
{
cout << " fail " << endl;
}
return lpPixels;
}
int main(int argc, const char* argv[])
{
HICON hIcon = (HICON)LoadImage(0, L"test.ico", IMAGE_ICON, 32, 32, LR_LOADFROMFILE);
HBITMAP hbmp = getBmp(hIcon);
getPixArray(hbmp);
return 0;
}

How do I get the byte representation of a BITMAPFILEHEADER and BITMAPINFOHEADER?

I'm trying to take a screenshot of my computer screen using code, and then store the BYTEs of that image into an array rather than save the image right away using the following function:
void WINAPI CaptureScreenIntoByteArray(
BYTE*& screen_bytes,
DWORD& screen_bytes_size)
{
BITMAPFILEHEADER bfHeader;
BITMAPINFOHEADER biHeader;
BITMAPINFO bInfo;
HGDIOBJ hTempBitmap;
HBITMAP hBitmap;
BITMAP bAllDesktops;
HDC hDC, hMemDC;
LONG lWidth, lHeight;
BYTE* sb = NULL;
ZeroMemory(&bfHeader, sizeof(BITMAPFILEHEADER));
ZeroMemory(&biHeader, sizeof(BITMAPFILEHEADER));
ZeroMemory(&bInfo, sizeof(BITMAPINFO));
ZeroMemory(&bAllDesktops, sizeof(BITMAP));
hDC = GetDC(NULL);
hTempBitmap = GetCurrentObject(hDC, OBJ_BITMAP);
GetObjectW(hTempBitmap, sizeof(BITMAP), &bAllDesktops);
lWidth = bAllDesktops.bmWidth;
lHeight = bAllDesktops.bmHeight;
DeleteObject(hTempBitmap);
bfHeader.bfType = (WORD)('B' | ('M' << 8));
bfHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
biHeader.biSize = sizeof(BITMAPINFOHEADER);
biHeader.biBitCount = 24;
biHeader.biCompression = BI_RGB;
biHeader.biPlanes = 1;
biHeader.biWidth = lWidth;
biHeader.biHeight = lHeight;
bInfo.bmiHeader = biHeader;
screen_bytes_size = (((24 * lWidth + 31) & ~31) / 8) * lHeight;
hMemDC = CreateCompatibleDC(hDC);
hBitmap = CreateDIBSection(hDC, &bInfo, DIB_RGB_COLORS, (VOID**)&sb, NULL, 0);
SelectObject(hMemDC, hBitmap);
int x = GetSystemMetrics(SM_XVIRTUALSCREEN);
int y = GetSystemMetrics(SM_YVIRTUALSCREEN);
BitBlt(hMemDC, 0, 0, lWidth, lHeight, hDC, x, y, SRCCOPY);
// Need to also copy bfHeader & biHeader bytes somehow...
screen_bytes = new BYTE[screen_bytes_size];
std::copy(sb, sb + screen_bytes_size, screen_bytes);
DeleteDC(hMemDC);
ReleaseDC(NULL, hDC);
DeleteObject(hBitmap);
}
My specific issue is that I need to have the bfHeader and biHeader saved into the byte array also (so that later on I can save the image as a file)... So this is the problem area...
// Need to also copy bfHeader & biHeader bytes somehow...
screen_bytes = new BYTE[screen_bytes_size];
std::copy(sb, sb + screen_bytes_size, screen_bytes);
How can I also copy the bfHeader and biHeader bytes into the array?
If needed, this is how you call the function...
BYTE* screen_bytes = NULL;
DWORD screen_bytes_size = 0;
CaptureScreenIntoByteArray(screen_bytes, screen_bytes_size);
You need to make the array big enough for the two structures as well.
screen_bytes = new BYTE[sizeof(BITMAPFILEHEADER) + sizeof (BITMAPINFOHEADER) + screen_bytes_size];
Then you can copy the two structures to the front of the array:
std::copy(&bfHeader, &bfHeader + 1, (BITMAPFILEHEADER*)screen_bytes);
std::copy(&biHeader, &biHeader + 1, (BITMAPINFOHEADER*)(screen_bytes + sizeof(BITMAPFILEHEADER)));
And copy the image data after the two structures.
std::copy(sb, sb + screen_bytes_size, screen_bytes + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER));

4K screen capturing in Windows and directly save into a buffer

I know there are many posts across the web to do screen capturing in Windows either using GDI or DirectX approaches. However, all I found save the captured image to a bitmap, whereas I want to save it into a buffer instead. Here is my code to do so in GDi way:
HWND hwind = GetDesktopWindow();
HDC hdc = GetDC(hwind);
uint32_t resx = GetSystemMetrics(SM_CXSCREEN);
uint32_t resy = GetSystemMetrics(SM_CYSCREEN);
uint32_t BitsPerPixel = GetDeviceCaps(hdc, BITSPIXEL);
HDC hdc2 = CreateCompatibleDC(hdc);
BITMAPINFO info;
info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth = resx;
info.bmiHeader.biHeight = resy;
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = BitsPerPixel;
info.bmiHeader.biCompression = BI_RGB;
void *data;
static HBITMAP hbitmap = CreateDIBSection(hdc2, &info, DIB_RGB_COLORS,
(void**)&data, 0, 0);
SelectObject(hdc2, hbitmap);
BitBlt(hdc2, 0, 0, resx, resy, hdc, 0, 0, SRCCOPY);
uint8_t *ptr = new uint8_t[4 * resx * resy];
uint32_t lineSizeSrc = 4 * resx; // not always correct
uint32_t linesizeDst = 4 * resx;
for (uint32_t y = 0; y < resy; y++)
memcpy(ptr + y * lineSizeDst,
(uint8_t*) data + y * lineSizeSrc,
lineSizeDst);
DeleteObject(hbitmap);
ReleaseDC(hwind, hdc);
if (hdc2) {
DeleteDC(hdc2);
}
First, as far as I know, the value of lineSizeSrc in this code is not always correct since depending on the screen resolution, some zeros may be added to each line of data. Can anyone please explain when the zeros are added and how to get the correct value for lineSizeSrc?
Second, is it possible to get the captured image in 4K resolution regardless of the resolution of the monitor, for instance by forcing the graphics card to output in 4K resolution?
First, as far as I know, the value of lineSizeSrc in this code is not always correct since depending on the screen resolution, some zeros may be added to each line of data. Can anyone please explain when the zeros are added and how to get the correct value for lineSizeSrc?
The bitmap format requires that each line begin at an address that's a multiple of 4 bytes. Often, this just works out because common image widths are multiples of 4 or because the size of an individual pixel is 32-bits (which is 4 bytes).
But if you're representing an image with an unusual width (e.g., 31 pixels wide) and using something like 24 bits (3 bytes) per pixel then you'll need to pad the end of each line so that the next line starts on a multiple of 4.
A common way to do this is to round up the "stride":
lineSizeSrc = (resx * BitsPerPixel + 31) / 8;
resx * BitsPerPixel tells us the number of bits needed to represent the line. Dividing by 8 converts bits to bytes--sort of. Integer division truncates any remainder. By adding 31 first we ensures that the truncation gives us the smallest multiple of 32 bits (4 bytes) that's equal to or larger than the number of bits we need. So lineSizeSrc is the number of bytes needed for each row.
You should use lineSizeSrc instead of resx in the calculation of how many bytes you need.
Second, is it possible to get the captured image in 4K resolution regardless of the resolution of the monitor, for instance by forcing the graphics card to output in 4K resolution?
There's not a simple, works-in-all-cases method. Your best bet is probably to ask the program to render to a window that's 4K, even if the graphics card isn't in that mode. Some programs will support this, but others might now. Look at the documentation for the WM_PRINT and WM_PRINTCLIENT messages.
Most modern monitors support 32bit color which is relatively simple as it doesn't require palettes. Example in C++:
void capture(char* &buffer)
{
HWND hwnd = GetDesktopWindow();
HDC hdc = GetDC(hwnd);
int w = GetSystemMetrics(SM_CXSCREEN);
int h = GetSystemMetrics(SM_CYSCREEN);
int BitsPerPixel = GetDeviceCaps(hdc, BITSPIXEL);
if (BitsPerPixel = 32)
{
HDC memdc = CreateCompatibleDC(hdc);
HBITMAP bmp = CreateCompatibleBitmap(hdc, w, h);
HGDIOBJ oldbitmap = SelectObject(memdc, bmp);
BitBlt(memdc, 0, 0, w, h, hdc, 0, 0, CAPTUREBLT | SRCCOPY);
SelectObject(memdc, oldbitmap);
DWORD bitsize = w * h * 4;
char *bits = new char[bitsize];
DWORD szInfoHdr = sizeof(BITMAPINFOHEADER);
BITMAPINFOHEADER bmpInfoHeader =
{ szInfoHdr, w, h, 1, (WORD)BitsPerPixel, BI_RGB, 0, 0, 0, 0, 0 };
GetDIBits(hdc, bmp, 0, h, bits, (BITMAPINFO*)&bmpInfoHeader, DIB_RGB_COLORS);
buffer = new char[bitsize + szInfoHdr];
memcpy(buffer, &bmpInfoHeader, szInfoHdr);
memcpy(buffer + szInfoHdr, bits, bitsize);
delete[]bits;
DeleteObject(bmp);
DeleteObject(memdc);
}
ReleaseDC(hwnd, hdc);
}
You can pass buffer through a function. The following code can be used for testing:
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
char *buffer = 0;
//capture the screen and save to buffer
capture(buffer);
if (buffer)
{
//paint the buffer for testing:
BITMAPINFO* bmpinfo = (BITMAPINFO*)buffer;
if (bmpinfo->bmiHeader.biBitCount == 32)
{
int w = bmpinfo->bmiHeader.biWidth;
int h = bmpinfo->bmiHeader.biHeight;
char *bits = buffer + sizeof(BITMAPINFOHEADER);
HBITMAP hbitmap = CreateDIBitmap(hdc,
&bmpinfo->bmiHeader, CBM_INIT, bits, bmpinfo, DIB_RGB_COLORS);
HDC memdc = CreateCompatibleDC(hdc);
SelectObject(memdc, hbitmap);
BitBlt(hdc, 0, 0, w, h, memdc, 0, 0, SRCCOPY);
}
delete[]buffer;
}
EndPaint(hWnd, &ps);
}
Note however, GetSystemMetrics(SM_CXSCREEN) returns the width of the primary monitor only.
You may want SM_CXVIRTUALSCREEN and SM_CYVIRTUALSCREEN to get the width/height of multi-monitor. Use SM_(X/Y)VIRTUALSCREEN to get top-left corner.

c/c++ assign RGBQUAD array to a bitmap

i am doing a program where you take a screenshot of a window and then scan every pixel of that picture. But I have a problem assigning RGBQUAD array to the taken screen. Every pixel has the same RGB which is 205. Here is a piece of my code:
RGBQUAD *pixel = malloc((ssWidth * ssHeight)* sizeof(RGBQUAD));
hdcScreen = GetDC(gameHandle);
hdc = CreateCompatibleDC(hdcScreen);
hBmp = CreateCompatibleBitmap(hdcScreen, ssWidth, ssHeight);
SelectObject(hdc, hBmp);
BitBlt(hdc, 0, 0, ssWidth, ssHeight, hdcScreen, xCenter, yCenter, SRCCOPY);
GetDIBits(hdc, hBmp, 0, ssHeight, pixel, &bmpInfo, DIB_RGB_COLORS);
int p = -1;
for(y_var = 0; y_var < ssWidth; y_var++)
{
for(x_var = 0; x_var < ssHeight; x_var++)
{
if(ComparePixel(&pixel[++p]))
{
SetCursorPos(xCenter + x_var + 3, yCenter + y_var + 3);
}
}
}
bool ComparePixel(RGBQUAD *pixel)
{
printf("%d, %d, %d\n"; pixel -> rgbRed, pixel -> rgbGreen, pixel -> rgbBlue);
return false;
}
ComparePixel(RGBQUAD *pixel) function just checks the RGB values. How do i assign the RGBQUAD to the bitmap of the screenshot?
Multiple issues.
The RGBQUAD **pixel = malloc(... and free(*pixel) appear to be the problem. I think you want RGBQUAD *pixel = malloc((ssWidth * ssHeight)* sizeof(RGBQUAD)); (only 1 *)
Suspect the pixels in GetDIBits() s/b pixel.
I think you want y_var = 0; (x_var = 0; also)
ComparePixel() is not defined, but I think you want something closer to if(ComparePixel(pixel[x_var+(y_var*ssWidth)], the_pixel_to_compare_against))
The free(*pixel); s/b _after the 2 for loops and should be free(pixel);

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!
JE
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.
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%.