Home > OS >  Quickest way to get dimensions of BITMAP file
Quickest way to get dimensions of BITMAP file

Time:08-17

What's the quickest way to get the height and width of a bitmap file in C? I either need to get it from the HBITMAP or the file itself, either way will work. Here's a section of my code:

    printf("Initializing textures...");
    HDC bp, memdc;
    HBITMAP bmp, hold;
    bp = GetDC(hwnd);
    memdc = CreateCompatibleDC(bp);
    bmp = (HBITMAP)LoadImage(NULL, tex_name, IMAGE_BITMAP, 0,0, LR_LOADFROMFILE);
    hold = (HBITMAP) SelectObject(memdc, bmp);
    for(int i = 0; i < 150; i  ){
        for(int j = 0; j < 150; j  ){
            COLORREF co = GetPixel(memdc, j, i);
            texturemap[i][j] = (COLORREF) (GetRValue(co)<<16)|(GetGValue(co)<<8)|GetBValue(co);
        }
    }
    SelectObject(memdc, hold);
    DeleteObject(bmp);
    DeleteDC(bp);
    system("cls");

It loads the pixel data from a file and then stores it into a 2d array. I would like to replace the 150 in each loop with the height followed by the width, but I have no clue how to get them.

(Also, yes I have already looked for existing answers.)

CodePudding user response:

You could use GetObject to fetch the information, which is written to a BITMAP structure:

bmp = (HBITMAP)LoadImage(NULL, tex_name, IMAGE_BITMAP, 0,0, LR_LOADFROMFILE);

BITMAP bm;
GetObject(bmp, (int) sizeof bm, &bm);

for(LONG i = 0; i < bm.bmHeight; i  ){
    for(LONG j = 0; j < bm.bmWidth; j  ){
        // ...

CodePudding user response:

A newer way is using WIC which would also work for any sort of supported image.

static CComPtr<IWICImagingFactory> wbfact;
if (!wbfact)
    CoCreateInstance(CLSID_WICImagingFactory, 0, CLSCTX_INPROC_SERVER,__uuidof(IWICImagingFactory), (void**)&wbfact);
CComPtr<IWICBitmapDecoder> pDecoder = NULL;
CComPtr<IWICBitmapFrameDecode> pSource = NULL;
wbfact->CreateDecoderFromFilename(file,NULL, GENERIC_READ,WICDecodeMetadataCacheOnLoad,&pDecoder);
pDecoder->GetFrame(0, &pSource);
UINT w,h;
pSource->GetSize(&w,&h);

(Error handling omitted).

Yes, more lines of code but greater support of compression types and color formats, support for reading from memory and compatibility with Direct2D.

  • Related