首页 > 解决方案 > QImage:加载图像时自动检测格式

问题描述

我有一个带有.jpg扩展名的图像,但它以png格式存储。当我QImage用来加载该图像时,它返回一个无效的QImage

QImage image (path);
if (image.isNull())
{
    //it enters here
}

在加载图像之前,我必须一一检查格式:

auto readImage = [](const QString & path)
{
    std::string formats[] = {
        "PNG",
        "JPG",
        "GIF",
        "JPEG",
    };

    for (auto && format : formats)
    {
        QImageReader img(path, format.c_str());
        if (img.canRead())
        {
            return QImage(path, format.c_str());
        }
    }
    return QImage(path);
};

QImage image = readImage(path);
if (image.isNull())
{
    //it does not enter here this time
}

有没有更好的方法来加载未知格式的图像?

load使用的方法更新QImage,仍然得到相同的结果:

QImage image;
image.load(path);
if (image.isNull())
{
    //it enters herer
 }

标签: c++qtqt5qimage

解决方案


我认为这是您需要的(来自QImage 文档):

bool QImage::load(const QString &fileName, const char *format = nullptr) 从给定文件名的文件中加载图像。如果图像加载成功,则返回 true;否则使图像无效并返回 false。加载程序尝试使用指定的格式(例如 PNG 或 JPG)读取图像。如果未指定格式(这是默认设置),则会根据文件的后缀和标题自动检测。有关详细信息,请参阅 {QImageReader::setAutoDetectImageFormat()}{QImageReader}。

如果没有,请尝试查看这个答案,其中提到了 jpeg 插件丢失的选项?也许尝试使用 *.png 文件进行完全相同的实验?


推荐阅读