Bruno
Bruno

Reputation: 181

Win32 C/C++ Load Image from memory buffer

I want to load an image (.bmp) file on a Win32 application, but I do not want to use the standard LoadBitmap/LoadImage from Windows API: I want it to load from a buffer that is already in memory. I can easily load a bitmap directly from a file and print it on the screen, but this issue is making me stuck.

What I'm looking for is a function that works like this:

HBITMAP LoadBitmapFromBuffer(char* buffer, int width, int height);

Upvotes: 10

Views: 23865

Answers (4)

JustJeff
JustJeff

Reputation: 12980

CreateDIBSection can be a little complicated to use, but one of the things it can do is create a device-independent bitmap and give you a pointer to the buffer for the bitmap bits. Granted, you already have a buffer full of bitmap bits, but at least you could copy the data.

Speculating a bit: CreateDIBSection can also create bitmaps from file objects, and there's probably a way to get Windows to give you a file object representing a chunk of memory, which might trick CreateDIBSection into giving you a bitmap built directly from your buffer.

Upvotes: 3

Bruno
Bruno

Reputation: 181

Nevermind, I found my solution! Here's the initializing code:

std::ifstream is;
is.open("Image.bmp", std::ios::binary);
is.seekg (0, std::ios::end);
length = is.tellg();
is.seekg (0, std::ios::beg);
pBuffer = new char [length];
is.read (pBuffer,length);
is.close();

tagBITMAPFILEHEADER bfh = *(tagBITMAPFILEHEADER*)pBuffer;
tagBITMAPINFOHEADER bih = *(tagBITMAPINFOHEADER*)(pBuffer+sizeof(tagBITMAPFILEHEADER));
RGBQUAD             rgb = *(RGBQUAD*)(pBuffer+sizeof(tagBITMAPFILEHEADER)+sizeof(tagBITMAPINFOHEADER));

BITMAPINFO bi;
bi.bmiColors[0] = rgb;
bi.bmiHeader = bih;

char* pPixels = (pBuffer+bfh.bfOffBits);

char* ppvBits;

hBitmap = CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (void**) &ppvBits, NULL, 0);
SetDIBits(NULL, hBitmap, 0, bih.biHeight, pPixels, &bi, DIB_RGB_COLORS);

GetObject(hBitmap, sizeof(BITMAP), &cBitmap);

Upvotes: 8

Adam Rosenfield
Adam Rosenfield

Reputation: 400146

Try CreateBitmap():

HBITMAP LoadBitmapFromBuffer(char *buffer, int width, int height)
{
    return CreateBitmap(width, height, 1, 24, buffer);
}

Upvotes: 10

Billy ONeal
Billy ONeal

Reputation: 106530

No, but you can create a new bitmap the size of the current one in memory, and write your memory structure onto it.

You're looking for the CreateBitmap function. Set lpvBits to your data.

Upvotes: 1

Related Questions