How to check if QImage is valid?
Asked Answered
A

2

13

I wanted to know if there was a way to determine if a QImage is valid. I am displaying that image as a pixmap in QLabel and sometimes when the image is not valid. It is not displayed in the QLabel, then.

The reason for not being valid sometimes is that the image is loaded from external data and that data can be corrupted at times.

Thereby, I wished to know if it is possible to actually determine whether a QImage is valid.

Altis answered 1/1, 2014 at 18:49 Comment(2)
Have you tried QImage::isNull?Leola
I havent wll give that a tryAltis
L
14

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.

Lowbred answered 1/1, 2014 at 19:2 Comment(0)
G
3

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

image.isNull()
Geri answered 1/1, 2014 at 19:5 Comment(1)
The image could have been loaded by a third party library, so even if it was returned by a function(ie, no exception occurred or error flags have been set), it still could be invalid.Geri

© 2022 - 2024 — McMap. All rights reserved.