Convertion between CImage and BYTE
We can get the BYTEs of the CImage object by Image2Bytes API, and get the CImage object from the BYTEs by Bytes2Image API.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
bool Image2Bytes(const CImage& img, BYTE** bytes, size_t& byteSize){
if(img.isNull()) return false;
IStream* pStrImg = NULL;
if(CreateStreamOnHGlobal(NULL, TRUE, &pStrImg) != S_OK) return false;
img.Save(pStrImg, Gdiplus::ImageFormatBMP);
HGLOBAL hGlobalImg = NULL;
GetHGlobalFromStream(pStrImg, &hGlobalImg);
BYTE* pBits = (BYTE*)GlobalLock(hGlobalImg);
byteSize = GlobalSize(pBits);
*bytes = new BYTE[byteSize];
memcpy(*bytes, pBits, byteSize);
GlobalUnlock(hGlobalImg);
PstrImg->Release();
GlobalFree(hGloabalImg);
return true;
}
bool Bytes2Image(const BYTE* bytes, const size_t byteSize, CImage& img){
if(bytes == NULL) return false;
HGLOBAL hGlobalImg = GlobalAlloc(GMEM_MOVEABLE, byteSize);
BYTE* pBits = (BYTE*)GlobalLock(hGlobalImg);
memcpy(pBits, bytes, byteSize);
GlobalUnlock(hGlobalImg);
IStream* pStrImg = NULL;
if(CreateStreamOnHGlobal(hGlobalImg, TRUE, &pStrImg) != S_OK){
GlobalFree(hGloabalImg);
return false;
}
if(!img.isNull()) img.Destroy();
img.Load(pStrImg);
pStrImg->Release();
GlobalFree(hGloabalImg);
return true;
}