使用QtConcurrent使用QImageReader读取图像文件

Der*_*rek 14 c++ qt multithreading thread-safety

我试图使用QImageReader一次读取图像文件的部分(每个Tile),这样对于非常大的图像,它们不会从磁盘读入内存,直到需要显示它们为止.

看来谎言我遇到了一些线程安全问题.

这就是我目前拥有的:

#include "rastertile.h"

QMutex RasterTile::mutex;
RasterTile::RasterTile()
{
}

//RasterTile::RasterTile(QImageReader *reader, int nBlocksX, int nBlocksY, int xoffset, int yoffset, int nXBlockSize, int nYBlockSize)
RasterTile::RasterTile(QString filename, int nBlocksX, int nBlocksY, int xoffset, int yoffset, int nXBlockSize, int nYBlockSize)

    : Tile(nBlocksX, nBlocksY, xoffset, yoffset, nXBlockSize, nYBlockSize)
{
        this->reader = new QImageReader(filename);
        connect(&watcher,SIGNAL(finished()),this,SLOT(updateSceneSlot()));
}


void RasterTile::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget)
{
    if(image.isNull())
    {
        TilePainter=painter;
        TileOption=option;
        TileWidget=widget;
        future = QtConcurrent::run(this, &RasterTile::LoadTilePixmap);
        watcher.setFuture(future);

    }else
    {
        QRectF imageRect = image.rect();
        painter->drawImage(imageRect, image);
    }

}

QImage RasterTile::LoadTilePixmap()
{
    QMutexLocker locker(&mutex);

    QImage img(nBlockXSize, nBlockYSize, QImage::Format_RGB32);

    QRect rect(tilePosX*nBlockXSize, tilePosY*nBlockYSize, nBlockXSize, nBlockYSize);

    reader->setClipRect(rect);
    reader->read(&img);
    if(reader->error())
    {
        qDebug("Not null error");
        qDebug()<<"Error string is: "<<reader->errorString();
    }
    return img;

}
Run Code Online (Sandbox Code Playgroud)

所以这基本上是为每个磁贴实例化一个新的读取器,并更新超类的"图像"变量,然后我可以绘制它.

这似乎给了我很多读者的错误,简单地说"无法读取图像数据"

我认为这可能与访问同一文件的许多磁贴有关,但我不知道如何证明或修复它.

我认为Qt使用libjpeg和libpng以及其他任何东西来阅读各种图像格式.

O.C*_*.C. 2

查看QImageReader的源代码。

当阅读器返回InvalidDataError时,您将得到“无法读取图像数据”

如果您还阅读了InvalidDataError QT Doc的解释

图像数据无效,QImageReader 无法从中读取图像。如果图像文件损坏,则可能会发生这种情况。

所以你的文件可能已损坏。