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.
The QPixmap class is an off-screen image representation that can be used as a paint device. The QImage class provides a hardware-independent image representation that allows direct access to the pixel data, and can be used as a paint device.
A QPixmap object can be converted into a QImage using the toImage() function. Likewise, a QImage can be converted into a QPixmap using the fromImage(). If this is too expensive an operation, you can use QBitmap::fromImage() instead.
Simply call the save() function to save a QImage object.
To resize an image one would use QImage::scaled(). If you want to crop an image, you can use QImage::copy() and assign it to the same object you copied from. Other ways to change the size of an image wouldn't make sense.
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.
If there was a failure while loading image, it will not contain any data, so you can check it using:
image.isNull()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With