开发者

how to use GDI to read pixels from bitmap?

I've used a lot of other techniques for reading pixel data from files but it seemed like a good idea to try using the GDI. The documentation is a bit vague on non-screen DCs so I'm kind of grasping at straws.

Here's what I've got right now, and it says all the pixels are out of bounds (prints the 'x').

#include <windows.h>
#include <iostream>

using namespace std;

#define filename "test.bmp"


i开发者_C百科nt main()
{
    HBITMAP hBmp;
    hBmp = (HBITMAP)LoadImage(NULL,(LPCTSTR)filename,IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_SHARED);
    if( hBmp==NULL )
    {
        cout<< "could not load\n";
        system("pause");
        return 0;
    }

    BITMAP bmp;
    HDC hdc = CreateCompatibleDC(NULL);
    GetObject(hBmp,sizeof(bmp),&bmp);
    BitBlt(hdc,0,0,bmp.bmWidth,bmp.bmHeight,hdc,0,0,SRCCOPY);

    for(int y=0;y<bmp.bmHeight;y++)
    {
        for(int x=0;x<bmp.bmWidth;x++)
        {
            if(x==0) 
                cout<< endl;

            COLORREF clr;
            clr = GetPixel(hdc,x,y);

            if( clr != CLR_INVALID )
                cout<< 0+(int)(clr==0);
            else 
                cout<< 'x';
        }
    }
    system("pause");

    DeleteDC(hdc);
    DeleteObject(hBmp);

    return 0;
}


You have to select bitmap to your dc:

HBITMAP hOldBmp = SelectObject(hdc, hBmp);

// I haven't understood what you're trying to achieve with this line of code
BitBlt(hdc,0,0,bmp.bmWidth,bmp.bmHeight,hdc,0,0,SRCCOPY);

   ....

SelectObject(hDc, hOldBmp);
DeleteDC(hdc);
   ....

When you create memory dc, 1x1 bitmap selected into it by default.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜