当我们有raw数据,想存成QImage图像数据时,往往使用下列函数进行生成:
QImage(uchar *data, int width, int height, int bytesPerLine, Format format, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr);
或者这样:
uchar* imgBuf = ...//假设imgBuf的位深度已经与下面设置QImage::Format_Grayscale8一致
int width = 300, height = 300;
QImage img = QImage(width, height, QImage::Format_Grayscale8);
uchar* pLine = img.scanLine(0); //获取图像数据指针基地址
memcpy(pLine, imgBuf, width * height);
但能看到有的新手是这样写的:
uchar* buf = ... //已有的raw数据缓存
QImage img = QImage(300, 300, QImage::Format_Grayscale8);
for(int y = 0; y < 300; y++)
for(int x = 0; x < 300; x++)
img.setPixel(x, y, buf[y*300 + x]);
这样写确实也能实现功能,但这样效率会很低,而且可能低的吓人。
//(Qt5.12.1 源码摘录)
void QImage::setPixel(int x, int y, uint index_or_rgb)
{
if (!