I need to create a CImage from a byte array (actually, its an array of unsigned char, but I can cast to whatever form is necessary). The byte array is in the form “RGBRGBRGB…”. The new image needs to contain a copy of the image bytes, rather than using the memory of the byte array itself.
I have tried many different ways of achieving this — including going through various HBITMAP creation functions, trying to use BitBlt — and nothing so far has worked.
To test whether the function works, it should pass this test:
BYTE* imgBits;
int width;
int height;
int Bpp; // BYTES per pixel (e.g. 3)
getImage(&imgBits, &width, &height, &Bpp); // get the image bits
// This is the magic function I need!!!
CImage img = createCImage(imgBits, width, height, Bpp);
// Test the image
BYTE* data = img.GetBits(); // data should now have the same data as imgBits
All implementations of createCImage() so far have ended up with data pointing to an empty (zero filled) array.
Thanks everyone, I managed to solve it in the end with your help. It mainly involved @tinman and @Roel’s suggestion to use
SetDIBitsToDevice(), but it involved a bit of extra bit-twiddling and memory management, so I thought I’d share my end-point here.In the code below, I assume that
width,heightandBpp(Bytes per pixel) are set, and thatdatais a pointer to the array of RGB pixel values.