结合网上和Ds的结果修改而成,特此记录:
说明:这里的彩色图像必须是byte类型,否则会出错。
2025/05/23修复RGB转换出来的灰度值部分差异,无法配对转换前的数据
HImage转QImage:
- bool convertHImage2QImage(HImage &from, QImage &to)
- {
- HTuple hv_Width, hv_Height, hv_Channels, hv_Type;
- GetImageSize(from, &hv_Width, &hv_Height);
- hv_Channels = from.CountChannels();
- hv_Type = from.GetImageType();
- if(strcmp(hv_Type.S(), "byte"))
- return false;
- QImage::Format format;
- switch(hv_Channels.I())
- {
- case 1:
- format = QImage::Format_Grayscale8;
- break;
- case 3:
- format = QImage::Format_RGB32;
- break;
- default:
- return false;
- }
- int nWidth = hv_Width.I();
- int nHeight = hv_Height.I();
- if(to.width() != nWidth || to.height() != nHeight || to.format() != format)
- to = QImage(nWidth, nHeight, format);
- if (1 == hv_Channels.I())
- {
- HTuple pointer = from.GetImagePointer1(&hv_Type, &hv_Width, &hv_Height);
- uchar* pData = reinterpret_cast<uchar*>(pointer.L());
- memcpy(to.bits(), pData, nWidth * nHeight);
- return true;
- }
- else if (3 == hv_Channels.I())
- {
- HTuple ptrR, ptrG, ptrB;
- GetImagePointer3(from, &ptrR, &ptrG, &ptrB, &hv_Type, &hv_Width, &hv_Height);
- uchar* pDataR = reinterpret_cast<uchar*>(ptrR.L());
- uchar* pDataG = reinterpret_cast<uchar*>(ptrG.L());
- uchar* pDataB = reinterpret_cast<uchar*>(ptrB.L());
- for (int i = 0; i < nHeight; i++)
- {
- for (int j = 0; j < nWidth; j++)
- {
- int src_idx = i * nWidth + j;
- int dst_idx = src_idx * 4;
- to.bits()[dst_idx] = pDataB[src_idx]; // B
- to.bits()[dst_idx + 1] = pDataG[src_idx]; // G
- to.bits()[dst_idx + 2] = pDataR[src_idx]; // R
- to.bits()[dst_idx + 3] = 0xFF; // Alpha
- }
- }
- ptrR.Clear();
- ptrG.Clear();
- ptrB.Clear();
- pDataR = nullptr;
- pDataG = nullptr;
- pDataB = nullptr;
- return true;
- }
- return false;
- }
复制代码 转换QImage的图像类型必须是RGB32显示,如果用RGB888会出现错位,所在生成阶段直接生成RGB32即可。
QImage转HImage:
- bool convertQImage2HImage(QImage &from, HImage &to)
- {
- if(from.isNull()) return false;
- int width = from.width(), height = from.height();
- QImage::Format format = from.format();
- if(format == QImage::Format_RGB32 ||
- format == QImage::Format_ARGB32 ||
- format == QImage::Format_ARGB32_Premultiplied)
- {
- to.GenImageInterleaved(from.bits(), "rgbx", width, height, 0, "byte", width, height, 0, 0, 8, 0);
- return true;
- }
- else if(format == QImage::Format_RGB888)
- {
- to.GenImageInterleaved(from.bits(), "rgb", width, height, 0, "byte", width, height, 0, 0, 8, 0);
- return true;
- }else if(format == QImage::Format_Grayscale8)
- {
- to.GenImage1("byte", width, height, from.bits());
- return true;
- }
- return false;
- }
复制代码
|