Convert HBitmap to Byte Array in Delphi

I am trying to convert hBitmap to an array of bytes, but I do not want to use TBitmap from Unit Graphics. My input image is 128x64x32bit.

var TheBits: array of array of Cardinal; begin with info.bmiHeader do begin biWidth:=131; biHeight:=64; biSize:=SizeOf(TBITMAPINFOHEADER); biCompression:=BI_RGB; biBitCount:=32; biPlanes:=1; biSizeImage:=0; end; DC := CreateCompatibleDC(0); SetLength(TheBits, 128, 64); GetDIBits(DC, BmpHandle, 0, 64,@TheBits[0][0],Info,DIB_RGB_COLORS); 

This gives me a nice image (of course, the leg), but I had to insert 131 into biWidth, which makes no sense to me. Why can't it be 128?

+6
source share
1 answer

You are very lucky. There are actually 128 completely separate arrays in your array. When you set the dimensions, Delphi had to allocate each array very close to the previous one, with 12 bytes separating them, which takes into account the different accounting data in each dynamic array. False, telling the API that your bitmap was 131 pixels wide, it skipped these bytes when copying data for a narrower bitmap.

The API expects one continuous block of bytes, which is not a multidimensional dynamic array. A multidimensional dynamic array is actually a regular dynamic array whose element type is another dynamic array.

To fix your code, you need a one-dimensional array; set its length to the product of the height and width of the bitmap.

+7
source

All Articles