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>
concept MatType = std::is_same_v<T, cv::Mat>;
template <typename T>
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);
}
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};
}
QImage bitmapToQImage(HBITMAP &hBitmap)
{
auto &&wh = updateBitmapToBits(hBitmap);
return QImage(bits, wh.first, wh.second, QImage::Format_ARGB32);
}
cv::Mat BitmapToMat(HBITMAP &hBitmap)
{
auto &&wh = updateBitmapToBits(hBitmap);
return cv::Mat(wh.second, wh.first, CV_8UC4, bits);
}