How do I save base64 string as png image in Qt?

I want to write function which saves input base64 string as a png image to local. How can I do it in Qt?

Upvotes: 6

Views: 9916

Answers (3)

vg34
vg34

Reputation: 91

If the string is base64 encoded image, it contains header information. You should remove the header information from the image data first, then convert the QString to QByteArray, construct the QImage using the static method QString::fromData() and finally save the QImage.

QString inputData;
QStringList stringList = inputData.split(',');
QString imageExtension = stringList.at(0).split(';').at(0).split('/').at(1);
QByteArray imageData = stringList.at(1).toUtf8();

imageData = QByteArray::fromBase64(imageData);

QImage img = QImage::fromData(imageData);

if(!img.isNull())
    img.save(confFilesPath + "images/ticketLogo", imageExtension.toUtf8());

Upvotes: 1

Alessandro Pezzato
Alessandro Pezzato

Reputation: 8802

This is a simple program I wrote sometime ago for testing png and base64. It accepts a png encoded in base64 from standard input, show it and than save it to specified path (output.png if nothing has been specified). This wont work if base64 string is not a png.

#include <QtCore>
#include <QApplication>

#include <QImage>
#include <QByteArray>
#include <QTextStream>
#include <QDebug>
#include <QLabel>

int main(int argc, char *argv[]) {
    QString filename = "output.png";
    if (argc > 1) {
        filename = argv[1];
    }
    QApplication a(argc, argv);
    QTextStream stream(stdin);
    qDebug() << "reading";
    //stream.readAll();
    qDebug() << "read complete";
    QByteArray base64Data = stream.readAll().toAscii();
    QImage image;
    qDebug() << base64Data;
    image.loadFromData(QByteArray::fromBase64(base64Data), "PNG");
    QLabel label(0);
    label.setPixmap(QPixmap::fromImage(image));
    label.show();
    qDebug() << "writing";
    image.save(filename, "PNG");
    qDebug() << "write complete";
    return a.exec();
}

Upvotes: 5

Bruce
Bruce

Reputation: 7132

You can read the FAQ and ask for specific problem...

Process is something like : Base64 (QString) -> QByteArray -> QImage -> save to file

Of course, you need to take into account plugins and export capacity to write png, and know how your base64 file represent an image... And be able to do the reverse process most probably.

Upvotes: 1

Related Questions