Tuesday, September 8, 2015

QImageReader: how to use and what's new in Qt 5.5

QImageReader is a Qt class which is able to work with images of different formats located in files or devices (like sockets, ports, etc.).

List of supported formats can be received in such a way:
QList<QByteArray> imageFormats = QImageReader::supportedImageFormats();
Typically these image formats include jpg, png, tiff, bmp, svg and some others.
Let's take logo from our site and cut a piece from it using QImageReader:

Imagine we need only bottom part from this logo, here what we need to do:
QImageReader *imageReader = new QImageReader("logo.png");
int x = imageReader->size().width();
int y = imageReader->size().height()/3;
QImage image = imageReader->read();
QPixmap pixmap = QPixmap::fromImage(image);
Here is the output:

All the previous code worked in previous versions of Qt. What's new in Qt 5.5? Functions which are working with transformation metadata - usually they are extracted from EXIF.

void setAutoTransform(bool)
bool autoTransform() const
QImageIOHandler::Transformations transformation() const

These three functions are new in Qt 5.5.

Let's take a jpeg photo rotated for 90 degrees.

QImageReader *imageReader = new QImageReader("photo.jpg");
std::cout << imageReader->size().width() << " x ";
std::cout << imageReader->size().height();
QImageIOHandler::Transformations transformation = imageReader->transformation();
After executing this code transformation is equal to QImageIOHandler::TransformationRotate90.