Loading

HBITMAP转QImage/cv::Mat

uchar *bits = nullptr;
void initBuff(size_t size)
{
    if (bits == nullptr)
    {
        bits = new uchar[size];
    }
}

void releaseBuff()
{
    if (bits != nullptr)
    {
        delete[] bits;
        bits = nullptr;
    }
}
template <typename T>
// 限定cv::Mat类型
concept MatType = std::is_same_v<T, cv::Mat>;

template <typename T>
// 限定QImage类型
concept QImageType = std::is_same_v<T, QImage>;

template <MatType T>
T bitmapTo(HBITMAP &hBitmap)
{
    return BitmapToMat(hBitmap);
}

template <QImageType T>
T bitmapTo(HBITMAP &hBitmap)
{
    return bitmapToQImage(hBitmap);
}
// return: W H
QPair<size_t, size_t> updateBitmapToBits(HBITMAP &hBitmap)
{
    BITMAP bitmap{};
    GetObject(hBitmap, sizeof(BITMAP), &bitmap);
    BITMAPINFOHEADER bih{};
    bih.biSize = sizeof(BITMAPINFOHEADER);
    bih.biWidth = bitmap.bmWidth;
    bih.biHeight = bitmap.bmHeight;
    bih.biPlanes = 1;
    bih.biBitCount = 32;
    bih.biCompression = BI_RGB;
    bih.biSizeImage = 0;
    bih.biXPelsPerMeter = 0;
    bih.biYPelsPerMeter = 0;
    bih.biClrUsed = 0;
    bih.biClrImportant = 0;
    if (bits == nullptr)
    {
        initBuff(static_cast<size_t>(bih.biWidth) * bih.biHeight * 4);
    }
    HDC hdc = GetDC((HWND)_wid);
    GetDIBits(hdc, hBitmap, 0, bih.biHeight, bits, (BITMAPINFO *)&bih, DIB_RGB_COLORS);
    ReleaseDC((HWND)_wid, hdc);
    return {bih.biWidth, bih.biHeight};
}

// 将HBITMAP转为QImage
QImage bitmapToQImage(HBITMAP &hBitmap)
{
    auto &&wh = updateBitmapToBits(hBitmap);
    return QImage(bits, wh.first, wh.second, QImage::Format_ARGB32);
}

// Bitmap To Mat
cv::Mat BitmapToMat(HBITMAP &hBitmap)
{
    auto &&wh = updateBitmapToBits(hBitmap);
    return cv::Mat(wh.second, wh.first, CV_8UC4, bits);
}

posted @ 2022-11-19 18:39  WindSnowLi  阅读(31)  评论(0编辑  收藏  举报