qtqimageqpixmapqbytearrayqicon

Convert jpeg image to thumbnail image in Qt


A QImage needs to be finally shown as a thumbnail image in a QLabel. In between it's serialized in QByteArray and sent over the network. So, can we convert the QImage to QByteArray for thumbnail? Basically I want to avoid the QImage::scale() method as it's quite CPU consuming. Like QImage converted to a QByteArray which will hold data for thumbnail images.


Solution

  • On this case you cannot avoid QImage::scale. Why do you want? This is the answer to your question how to save QImage to QByteArray.

            QFile file(imagePath);
            if (file.open(QIODevice::ReadOnly)) {
                QByteArray bytes;
                QImage img;
                img = img.fromData(file.readAll());
                img = img.scaled(200, 100, Qt::IgnoreAspectRatio, Qt::FastTransformation);
                SetLabelImage(img);
                QBuffer buffer(&bytes);
                img.save(&buffer, "PNG");
            }