如何使用GDI从位图中读取像素?
我使用了很多其他技术从文件中读取像素数据,但尝试使用 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;
}
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"
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须为您的 dc 选择位图:
当您创建内存 dc 时,默认情况下会选择 1x1 位图。
You have to select bitmap to your dc:
When you create memory dc, 1x1 bitmap selected into it by default.