c++ - 使用 QtConcurrent 使用 QImageReader 读取图像文件

标签 c++ multithreading qt 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;

}

所以这基本上是为每个图 block 实例化一个新的阅读器,并更新父类(super class)的“图像”变量,然后我可以绘制它。

这似乎给了我很多读者的错误,只是说“无法读取图像数据”

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

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

最佳答案

查看QImageReader的源代码.

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

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

The image data was invalid, and QImageReader was unable to read an image from it. The can happen if the image file is damaged.

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

关于c++ - 使用 QtConcurrent 使用 QImageReader 读取图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6459278/

相关文章:

c++ - 编译器是否对所有内联函数调用执行相同的操作?

java - java native 方法调用是原子调用吗?

c++ - 如何在 QT 语言翻译中使用 & 符号字符串

python - 在 PyQt 应用程序中嵌入 IPython Qt 控制台

c++将文件连接返回给成员,因此可以由同一类的其他方法使用

c++ - 不能在嵌套类中使用父类——即使嵌套类是在之后定义的

c++ - 在 C++ 中创建不可复制但可移动的对象

c - Python C API - 线程安全吗?

c# - C# 4.0 中的 Barrier 和 C# 3.0 中的 WaitHandle 之间的区别?

c++ - 如何自动链接到共享库的依赖项