How to save a QPixmap Object to a file?

后端 未结 1 1270
深忆病人
深忆病人 2021-01-03 21:05

I\'m having trouble reading and writing QByteArray data to a file.

My goal is to save QPixmap data into a QByteArray and save that QByteArray to a file (with the ab

相关标签:
1条回答
  • 2021-01-03 22:11

    That seemed like a really long way to go about doing it (but your comment better explains):

    For writing:

    QFile file("yourFile.png");
    file.open(QIODevice::WriteOnly);
    pixmap.save(&file, "PNG");
    

    For reading:

    QPixmap pixmap;
    pixmap.load("yourFile.png");
    

    QBuffer is great when you need a QIODevice and want to keep it in memory, but if you're actually going out to disk, then it's an unnecessary middle step.

    EDIT:

    To write pixmaps, and other things, to a single file I'd recommend that you use QDataStream.

    For writing:

    QFile file("outfile.dat");
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);
    out << QString("almost any qt value object")
        << yourQPixMap << yourQList /* << etc. */;
    

    Then, you can do similarly for reading:

    QFile file("infile.dat");
    file.open(QIODevice::ReadOnly);
    QDataStream in(&file);
    in >> firstQString >> yourQPixmap >> yourList /* >> etc. */;
    

    You'll need to make sure that you read in the same objects as you wrote them out. In order to save yourself future compatibility headaches, set the QDataStream version explicitly.

    0 讨论(0)
提交回复
热议问题