Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if QImage is valid?

Tags:

c++

qt

qimage

qtgui

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.

like image 914
MistyD Avatar asked Jan 01 '14 18:01

MistyD


People also ask

What is the difference between QImage and QPixmap?

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.

How do you convert QImage to QPixmap?

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.

How do you save in QImage?

Simply call the save() function to save a QImage object.

How do you scale a QImage?

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.


2 Answers

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.

like image 109
lpapp Avatar answered Oct 17 '22 05:10

lpapp


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

image.isNull()
like image 3
MasterID Avatar answered Oct 17 '22 04:10

MasterID