当我们有一个图像数据,宽度、高度、格式都已经明确的情况下,我们通过保存Raw数据查看也确认图像数据没有问题,但通过QImage构造函数得到的图像却呈现错位扭曲的现象。
这是调用的函数原型为:
QImage(uchar *data, int width, int height, Format format, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr);
而要解决这个问题,应该要调用函数为:
QImage(uchar *data, int width, int height, int bytesPerLine, Format format, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr);
根据常识判断,上面的函数传入信息已经能够完整确认图像的基本特质,那为啥还需要下面的重载函数传入bytesPerLine呢?
查看Qt的这部分源码,发现QImage中实际调用的是如下函数,上面第一个重载调用该函数传入的bpl实际为0,此时的问题就出在calculateImageParameters这个函数里面:
//(Qt5.12.1 源码摘录)
QImageData *QImageData::create(uchar *data, int width, int height, int bpl, QImage::Format format, bool readOnly, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
{
if (width <= 0 || height <= 0 || !data || format == QImage::Form