Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Save/Load Image between buffer

0.00/5 (No votes)
4 Mar 2014 1  
Save/Load Image between buffer

Given below is a small piece of code to save/load image between buffer:

typedef std::vector<BYTE> vecByte;

bool save_img(const CImage &image, vecByte &buf) 
{
    IStream *stream = NULL;
    HRESULT hr = CreateStreamOnHGlobal(0, TRUE, &stream);
    if( !SUCCEEDED(hr) )
        return false;
    image.Save(stream, Gdiplus::ImageFormatBMP);
    ULARGE_INTEGER liSize;
    IStream_Size(stream, &liSize);
    DWORD len = liSize.LowPart;
    IStream_Reset(stream);
    buf.resize(len);
    IStream_Read(stream, &buf[0], len);
    stream->Release();
    return true;
}

bool load_img(const vecByte &buf, CImage &image)
{
    UINT len = buf.size();
    HGLOBAL hMem = GlobalAlloc(GMEM_FIXED, len);
    BYTE *pmem = (BYTE*)GlobalLock(hMem);
    memcpy(pmem, &buf[0], len);
    IStream    *stream = NULL;
    CreateStreamOnHGlobal(hMem, FALSE, &stream);
    image.Load(stream);
    stream->Release();
    GlobalUnlock(hMem);
    GlobalFree(hMem);
    return true;
}  

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here