【问题标题】:how to use GDI to read pixels from bitmap?如何使用 GDI 从位图中读取像素?
【发布时间】:2011-08-29 14:11:39
【问题描述】:

我已经使用了许多其他技术来从文件中读取像素数据,但尝试使用 GDI 似乎是个好主意。 文档在非屏幕 DC 上有点含糊,所以我有点抓住了稻草。

这是我现在得到的,它说所有像素都超出了范围(打印出“x”)。

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

using namespace std;

#define filename "test.bmp"


int 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;
}

【问题讨论】:

    标签: windows bitmap gdi pixels


    【解决方案1】:

    您必须为您的 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);
       ....
    

    创建内存dc时,默认选择1x1位图。

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2013-07-13
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 2012-01-23
      • 2015-10-10
      相关资源
      最近更新 更多