虽然我特殊处理了一下256位的图,但我仍然无法画灰度图,挺奇怪的。目前只支持24位的图片。
main:
IplImage *img = cvLoadImage("****");
BITMAPINFO bmi;
FillBitmapInfo(&bmi, img->width, img->height, img->
depth*img->nChannels);
ShowImage(img, wnd, bmi); // 这里的wnd是目标窗口,必须是CWnd类型的。
void FillBitmapInfo( BITMAPINFO *bmi, int width, int height, int bpp )
{
ASSERT( bmi && width > 0 && height > 0 &&
(bpp == 8 || bpp == 24 || bpp == 32) );
{
ASSERT( bmi && width > 0 && height > 0 &&
(bpp == 8 || bpp == 24 || bpp == 32) );
BITMAPINFOHEADER* bmih = &(bmi->bmiHeader);
memset( bmih, 0, sizeof(*bmih));
bmih->biSize = sizeof(BITMAPINFOHEADER);
bmih->biWidth = width;
bmih->biHeight = -abs(height);
bmih->biPlanes = 1;
bmih->biBitCount = bpp;
bmih->biCompression = BI_RGB;
bmih->biSize = sizeof(BITMAPINFOHEADER);
bmih->biWidth = width;
bmih->biHeight = -abs(height);
bmih->biPlanes = 1;
bmih->biBitCount = bpp;
bmih->biCompression = BI_RGB;
if( bpp == 8 )
{
RGBQUAD* palette = bmi->bmiColors;
int i;
for( i = 0; i < 256; i++ )
{
palette[i].rgbBlue = palette[i].rgbGreen = palette[i].rgbRed = (BYTE)i;
palette[i].rgbReserved = 0;
}
}
}
{
RGBQUAD* palette = bmi->bmiColors;
int i;
for( i = 0; i < 256; i++ )
{
palette[i].rgbBlue = palette[i].rgbGreen = palette[i].rgbRed = (BYTE)i;
palette[i].rgbReserved = 0;
}
}
}
void ShowImage(IplImage *pImg, CWnd *wnd, BITMAPINFO &bmi)
{
CDC *pDC = wnd->GetDC();
HDC hDC = pDC->GetSafeHdc();
CRect rect;
wnd->GetClientRect(&rect);
if(bmi.bmiHeader.biBitCount== 8)
{
CPalette pal;
HPALETTE hpal=NULL;
HPALETTE hOldPal=NULL;
::SetPaletteEntries(hpal,0,256,(LPPALETTEENTRY)bmi.bmiColors);
hOldPal = ::SelectPalette(pDC->GetSafeHdc(), hpal, TRUE);
{
CDC *pDC = wnd->GetDC();
HDC hDC = pDC->GetSafeHdc();
CRect rect;
wnd->GetClientRect(&rect);
if(bmi.bmiHeader.biBitCount== 8)
{
CPalette pal;
HPALETTE hpal=NULL;
HPALETTE hOldPal=NULL;
::SetPaletteEntries(hpal,0,256,(LPPALETTEENTRY)bmi.bmiColors);
hOldPal = ::SelectPalette(pDC->GetSafeHdc(), hpal, TRUE);
}
::SetStretchBltMode(pDC->m_hDC, COLORONCOLOR);
::StretchDIBits(pDC->GetSafeHdc(),rect.left,rect.top,pImg->width,pImg->height,0,0,
pImg->width,pImg->height,pImg->imageData,&bmi,DIB_RGB_COLORS,SRCCOPY);
::SetStretchBltMode(pDC->m_hDC, COLORONCOLOR);
::StretchDIBits(pDC->GetSafeHdc(),rect.left,rect.top,pImg->width,pImg->height,0,0,
pImg->width,pImg->height,pImg->imageData,&bmi,DIB_RGB_COLORS,SRCCOPY);
}