Question

i'm trying to write a local resource (.BMP) imported in Visual Studio C++ to a file. I've added a new resource type BITMAP to resources. Its ID is 101 (shown in resource.h). I can successfully find it and save it to a file, but the file saved is not a BMP anymore, it has the same size of the original. I've seen in hex editor that the "header" of the written file is different from the original BMP that i've imported into project. Here's the code, pls help thank you !

`

   WORD wResId = 101;
    LPSTR lpszOutputPath = "c:\\test.bmp";
    HRSRC hrsrc = FindResource(NULL, MAKEINTRESOURCE(wResId) , RT_BITMAP);
    HGLOBAL hLoaded = LoadResource(NULL,hrsrc);
    LPVOID lpLock =  LockResource(hLoaded);
    DWORD dwSize = SizeofResource(NULL, hrsrc);
    HANDLE hFile = CreateFile (lpszOutputPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
    DWORD dwByteWritten;
    WriteFile(hFile, lpLock , dwSize , &dwByteWritten , NULL);
    CloseHandle(hFile);
    FreeResource(hLoaded);`
Was it helpful?

Solution

A RT_BITMAP resource doesn't have the BITMAPFILEHEADER in it, so you need to add that if you want to save it to disk. You could store the resource as RT_RCDATA to embed the file exactly as it was on disk, but then you lose the ability to use functions like LoadImage to read it.

This should do what you need:

#include <Windows.h>

int main()
{
    WORD wResId = 101;
    LPSTR lpszOutputPath = "test.bmp";
    HRSRC hrsrc = FindResource(NULL, MAKEINTRESOURCE(wResId) , RT_BITMAP);
    HGLOBAL hLoaded = LoadResource(NULL,hrsrc);
    LPVOID lpLock =  LockResource(hLoaded);
    DWORD dwSize = SizeofResource(NULL, hrsrc);
    HANDLE hFile = CreateFile (lpszOutputPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
    DWORD dwByteWritten;

    //Write BITMAPFILEHEADER
    BITMAPFILEHEADER bfh;
    bfh.bfType = 0x4d42;
    bfh.bfSize = dwSize + sizeof(BITMAPFILEHEADER);
    bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
    bfh.bfReserved1 = bfh.bfReserved2 = 0;
    WriteFile(hFile, &bfh, sizeof(bfh), &dwByteWritten , NULL);

    WriteFile(hFile, lpLock , dwSize , &dwByteWritten , NULL);
    CloseHandle(hFile);
    FreeResource(hLoaded);
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top