How to check if QImage is valid?

If there was a failure while loading image, it will not contain any data, so you can check it using:

image.isNull()

You can check the return value of the image loading from the data since it is a boolean return value, and it will be false when the loading was unsuccessful.

Here is the relevant part of the documentation inline for your convenience:

bool QImage::load(const QString & fileName, const char * format = 0)

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.

You could even use QImageReader if you happen to load from file or other devices. That has a dedicated error enumeration for fine tuning. You could also query the errorString() as is.

That being said, if for some reason you wanna proceed with the QImage despite that the loading was unsuccessful, you can check the image validity later by the following method:

bool QImage::isNull() const

Returns true if it is a null image, otherwise returns false.

A null image has all parameters set to zero and no allocated data.

Tags:

C++

Qt

Qimage

Qtgui