Win32 C/C++ Load Image from memory buffer

后端 未结 4 535
日久生厌
日久生厌 2020-12-03 03:47

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

相关标签:
4条回答
  • 2020-12-03 04:25

    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);
    
    0 讨论(0)
  • 2020-12-03 04:32

    Try CreateBitmap():

    HBITMAP LoadBitmapFromBuffer(char *buffer, int width, int height)
    {
        return CreateBitmap(width, height, 1, 24, buffer);
    }
    
    0 讨论(0)
  • 2020-12-03 04:34

    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.

    0 讨论(0)
  • 2020-12-03 04:34

    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.

    0 讨论(0)
提交回复
热议问题