将base64转换为QImage

将base64转换为QImage

我有问题。我必须将base64转换为QImage,但是之后该图像始终为null。这是代码:

void convertAll(QString path)
{
    QDir *dir = new QDir(path);
    QDirIterator *iter = new QDirIterator(*dir);
    QVector<QFile*> files;

    QTextStream cout(stdout);

    cout << "Finding files...\n";
    cout.flush();

    while (iter->hasNext())
    {
        iter->next();
        if (iter->fileInfo().completeSuffix() == "txt")
            files.push_back(new QFile(iter->filePath()));
    }

    delete iter;

    cout << "Converting files to images...\n";
    cout.flush();

    foreach (QFile *file, files)
    {
        QString filename = QFileInfo(*file).fileName();
        filename.remove(".txt");

        file->open(QIODevice::ReadOnly);
        QTextStream stream(file);

        cout << "Reading file...\n";
        cout.flush();

        QByteArray base64Data = stream.readAll().toUtf8();
        cout << "Reading is completed!\n";
        cout.flush();
        file->close();


        QImage *image = new QImage();
        cout << "Converting...\n";
        cout.flush();


        image->loadFromData(QByteArray::fromBase64(base64Data), "GIF");
        if (!image->isNull())
        {
            cout << "Converting is completed! Saving...\n";
            cout.flush();
        }
        else
        {
            cout << "Error converting to image!\n\n";
            cout.flush();
            delete image;
            delete file;
            continue;
        }

        if (image->save("/home/prosperis/ProgramFiles/Content/" + filename + ".bmp", "BMP"))
        {
            cout << "Saved successful!\nFile " << filename << ".bmp has been made!\n\n";
            cout.flush();
        }
        else
        {
            cout << "Error saving the file!\n\n";
            cout.flush();
        }


        delete image;
        delete file;
    }

    delete dir;
}

屏幕截图,显示结果:

Result

Base64示例:



如果我删除

最佳答案

我通过这个简单的示例进行了尝试,并且可以在我的机器上运行。

QByteArray txt = "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADxSURBVFhH7ZSxDYMwEEW9RdqU9MhFOho6WrwAE0SsESGlyABpvEU2yB5ZItLFnG1kkJEgipUjuSdZWG78+HdnwTAMAR73J7gtXTYjOSd61Wc6PxCTJCXYM5X8muDldJi9OJQkKdjj+5KsoGcTgrHhSc5PJei2iVA1qNvRrBoyIYbLiAjmUBi5Sjc0BbPOJKdL2LVG0HzdMbJEMG16WNoGpBQUBW1pC2VLikl2OR3BqRAtQSzteCBigkv4vKAsoQpK65HaTHK7JyA4vHnxtVYy4ZCEjAdmDSyIYF/a99CdLCaxoE0u7MF3UmQYhmGYv0SIF0Zn9rmd3QoAAAAAAElFTkSuQmCC";

QPixmap image;
image.loadFromData(QByteArray::fromBase64(txt));
ui->label->setPixmap(image);

07-28 01:45