QImage: auto detect format when loading image

I have an image with .jpg extension but it is stored as png format. When I use QImage to load that image, it returns an invalid QImage:

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

I have to check format one by one before loading image:

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
}

Is there any better way to load image with unknown format?

Update using load method of QImage, still get the same result:

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

1 answer

  • answered 2018-07-11 03:48 OrenIshShalom

    I think this is what you need (from QImage documentation):

    bool QImage::load(const QString &fileName, const char *format = nullptr) Loads an image from the file with the given fileName. Returns true if the image was successfully loaded; otherwise invalidates the image and returns false. The loader attempts to read the image using the specified format, e.g., PNG or JPG. If format is not specified (which is the default), it is auto-detected based on the file's suffix and header. For details, see {QImageReader::setAutoDetectImageFormat()}{QImageReader}.

    If not, try looking at this answer which mentions the option that the jpeg plugin is missing? maybe try the exact same experiment with a *.png file?