转载出处: http://blog.csdn.net/zfdxx369/article/details/8138706
显示RGB图像:
void ShowRGBToWnd(HWND hWnd, BYTE* data, int width, int height)
{
if (data == NULL)
return;
static BITMAPINFO *bitMapinfo = NULL;
static bool First = TRUE;
if (First)
{
bitBuffer = new BYTE[40 + 4 * 256];//开辟一个内存区域
if (bitBuffer == NULL)
{
return;
}
First = FALSE;
memset(bitBuffer, 0, 40 + 4 * 256);
bitMapinfo = (BITMAPINFO *)bitBuffer;
bitMapinfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitMapinfo->bmiHeader.biPlanes = 1;
for (int i = 0; i < 256; i++)
{ //颜色的取值范围 (0-255)
bitMapinfo->bmiColors[i].rgbBlue = bitMapinfo->bmiColors[i].rgbGreen = bitMapinfo->bmiColors[i].rgbRed = (BYTE)i;
}
}
bitMapinfo->bmiHeader.biHeight = -height;
bitMapinfo->bmiHeader.biWidth = width;
bitMapinfo->bmiHeader.biBitCount = 3 * 8;
CRect drect;
GetClientRect(hWnd, drect); //pWnd指向CWnd类的一个指针
HDC hDC = GetDC(hWnd); //HDC是Windows的一种数据类型,是设备描述句柄;
SetStretchBltMode(hDC, COLORONCOLOR);
StretchDIBits(hDC,
0,
0,
drect.right, //显示窗口宽度
drect.bottom, //显示窗口高度
0,
0,
width, //图像宽度
height, //图像高度
data,
bitMapinfo,
DIB_RGB_COLORS,
SRCCOPY
);
ReleaseDC(hWnd, hDC);
}
显示Mat图像
void ShowMatImgToWnd(CWnd* pWnd, cv::Mat img)
{
if(img.empty())
return;
static BITMAPINFO *bitMapinfo = NULL;
static bool First=TRUE;
if(First)
{
BYTE *bitBuffer = new BYTE[40+4*256];
if(bitBuffer == NULL)
{
return;
}
First=FALSE;
memset(bitBuffer, 0, 40+4*256);
bitMapinfo = (BITMAPINFO *)bitBuffer;
bitMapinfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitMapinfo->bmiHeader.biPlanes = 1; // 目标设备的级别,必须为1
for(int i=0; i<256; i++)
{ //颜色的取值范围 (0-255)
bitMapinfo->bmiColors[i].rgbBlue =bitMapinfo->bmiColors[i].rgbGreen =bitMapinfo->bmiColors[i].rgbRed =(BYTE) i;
}
}
bitMapinfo->bmiHeader.biHeight = -img.rows; //如果高度为正的,位图的起始位置在左下角。如果高度为负,起始位置在左上角。
bitMapinfo->bmiHeader.biWidth = img.cols;
bitMapinfo->bmiHeader.biBitCount = img.channels() *8; // 每个像素所需的位数,必须是1(双色), 4(16色),8(256色)或24(真彩色)之一
CRect drect;
pWnd->GetClientRect(drect); //(drect); (&drect); 两种方式均可,竟然
CClientDC dc(pWnd);
HDC hDC =dc.GetSafeHdc();
SetStretchBltMode(hDC, COLORONCOLOR); //此句不能少哦
//内存中的图像数据拷贝到屏幕上
StretchDIBits(hDC,
0,
0,
drect.right, //显示窗口宽度
drect.bottom, //显示窗口高度
0,
0,
img.cols, //图像宽度
img.rows, //图像高度
img.data,
bitMapinfo,
DIB_RGB_COLORS,
SRCCOPY
);
}