如何在Qt中将base64字符串保存为png图像?

Gür*_*kçı 6 c++ base64 qt png

我想编写将输入base64字符串作为png图像保存到本地的函数.我怎么能在Qt中做到这一点?

Ale*_*ato 5

这是我之前写的一个简单的程序,用于测试png和base64.它接受来自标准输入的base64编码的png,显示它并将其保存到指定的路径(如果没有指定任何内容,则输出.png).如果base64字符串不是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();
}
Run Code Online (Sandbox Code Playgroud)