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开发者_JAVA百科 do it in Qt?
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();
}
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());
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.
精彩评论