2011-05-20 78 views
0

我用了很多其他技術從文件中讀取像素數據,但它似乎是一個好主意,使用GDI嘗試。 該文檔是有點含糊非屏幕的DC,所以我在吸管樣的把握。如何使用GDI來讀取位圖像素?

這裏是我已經有了,現在,它說的所有像素爲出界(打印的「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; 
} 

回答

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的位圖默認情況下選中了進去。

+0

感謝,這給了我我需要的東西 – user722132 2011-05-20 13:09:36