Example #1
0
void  CvvImage::DrawMatToHDC(Mat mat, HDC hDC, RECT rect)
{
    ATL::CImage img; //ATL::CImage
    int w = mat.cols;  //宽
    int h = mat.rows;  //高
    int chinnels = mat.channels();
    img.Create(w, h, chinnels << 3);

    RGBQUAD* pColorTable = NULL;
    int nMaxColors = 256;
    pColorTable = new RGBQUAD[nMaxColors];
    img.GetColorTable(0, nMaxColors, pColorTable);

    for(int i = 0; i < nMaxColors; i++)
    {
        pColorTable->rgbBlue = (BYTE) i;
        pColorTable->rgbGreen = (BYTE) i;
        pColorTable->rgbRed = (BYTE) i;
    }

    img.SetColorTable(0, nMaxColors, pColorTable);
    delete[] pColorTable;

    int i, j, k;
    BYTE *pSource = NULL;
    BYTE *pImgData = (BYTE *) img.GetBits();
    int step = img.GetPitch();

    if(chinnels == 1)
    {
        for(i = 0; i < h; ++i)
        {
            pSource = mat.ptr<BYTE> (i);

            for(j = 0; j < w; ++j)
            {
                * (pImgData + i * step + j) = pSource[j];
            }
        }
    }
    else if(chinnels == 3)
    {
        for(i = 0; i < h; ++i)
        {
            pSource = mat.ptr<BYTE> (i);

            for(j = 0; j < w; ++j)
            {
                for(k = 0; k < 3; ++k)
                {
                    * (pImgData + i * step + j * 3 + k) = pSource[j * 3 + k];
                }
            }
        }
    }
    else
    {
        AfxMessageBox(TEXT("仅支持灰度图/3通道彩色图"));
        return;
    }

    SetStretchBltMode(hDC, COLORONCOLOR);
    img.StretchBlt(hDC, rect, SRCCOPY);
    img.Destroy();
}