GetDIBits 遍历位图 获取像素的颜色值(RGB)

本文介绍如何通过GetDIBits函数从位图资源中获取每个像素的RGB颜色值。虽然网上的例子不完整,但本文旨在提供一个清晰的教程,作为个人笔记和他人参考。
摘要由CSDN通过智能技术生成

加载位图,当然,这个可以有很多种方式,我这里用的是比较简单的,直接导入资源。

CBitmap m_bmp;
//根据位图资源导入之后的ID来获得位图
m_bmp.LoadBitmap(IDB_BITMAP_ORIGIN);</pre>

接下来就是通过GetDIBits函数来对位图的像素进行遍历,获取RGB

	BITMAP bm;
	m_bmp.GetBitmap(&bm);

	int nbyte = bm.bmBitsPixel / 8;

	BITMAPINFO bi;  
	bi.bmiHeader.biSize = sizeof(bi.bmiHeader);  
	bi.bmiHeader.biWidth = bm.bmWidth;  
	bi.bmiHeader.biHeight = -bm.bmHeight;  
	bi.bmiHeader.biPlanes = 1;  
	bi.bmiHeader.biBitCount = bm.bmBitsPixel;   
	bi.bmiHeader.biCompression = BI_RGB;   
	bi.bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * nbyte; 
	bi.bmiHeader.biClrUsed = 0;  
	bi.bmiHeader.biClrImportant = 0;  

	// 获取位图数据  
	HDC hdc = ::GetDC(NULL);  
	BYTE* pBits = (BYTE*)new BYTE[bm.bmWidth * bm.bmHeight * nbyte];  
	::ZeroMemory(pBits, bm.bmWidth * bm.bmHeight * nbyt
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
MFC,可以通过使用GetDIBits函数来遍历HBITMAP像素。下面是一个示例代码,演示如何遍历HBITMAP像素: ```c++ void TraverseBitmapPixels(HBITMAP hBitmap) { BITMAP bmp; ::GetObject(hBitmap, sizeof(BITMAP), &bmp); BITMAPINFOHEADER bmInfoHeader = {0}; bmInfoHeader.biSize = sizeof(BITMAPINFOHEADER); bmInfoHeader.biWidth = bmp.bmWidth; bmInfoHeader.biHeight = bmp.bmHeight; bmInfoHeader.biPlanes = 1; bmInfoHeader.biBitCount = 24; // 24位图像,每个像素占3字节 BYTE* pPixels = new BYTE[bmp.bmWidth * bmp.bmHeight * 3]; // 存储像素的缓冲区 HDC hDC = ::GetDC(NULL); // 获取屏幕设备上下文 // 获取HBITMAP的像素 if (::GetDIBits(hDC, hBitmap, 0, bmp.bmHeight, pPixels, (BITMAPINFO*)&bmInfoHeader, DIB_RGB_COLORS)) { int rowBytes = (bmp.bmWidth * 3 + 3) & ~3; // 每行的字节数,需要按4字节对齐 for (int y = 0; y < bmp.bmHeight; y++) { BYTE* pRow = pPixels + (bmp.bmHeight - y - 1) * rowBytes; // 像素行的指针 for (int x = 0; x < bmp.bmWidth; x++) { BYTE blue = pRow[x * 3]; BYTE green = pRow[x * 3 + 1]; BYTE red = pRow[x * 3 + 2]; // 在这里可以对每个像素RGB进行处理或分析 // ... // 示例:输出像素坐标和RGB TRACE("Pixel at (%d, %d): R=%d, G=%d, B=%d\n", x, y, red, green, blue); } } } ::ReleaseDC(NULL, hDC); delete[] pPixels; } ``` 此示例代码通过调用GetDIBits函数获取HBITMAP的像素,并遍历每个像素RGB。你可以根据实际需求,在遍历过程对每个像素RGB进行处理或分析。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值