24

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 ability to read this QByteArray back from the file and into a QPixmap). I want to use following code from the QPixmap documentation:

     QPixmap pixmap(<image path>);  
     QByteArray bytes;
     QBuffer buffer(&bytes);
     buffer.open(QIODevice::WriteOnly);
     pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format

After writing the buffer to a file, I want to be able to retrieve the QByteArray and load it back into a QPixmap using the QPixmap::loadFromData() function.

Please let me know if any further clarification is needed (I'm open to alternative approaches as well, I just need to be able to read and write the QPixmap to a file! :) );

W.K.S
  • 9,787
  • 15
  • 75
  • 122
Alex Wood
  • 821
  • 3
  • 12
  • 27

1 Answers1

52

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.

feedc0de
  • 3,646
  • 8
  • 30
  • 55
Kaleb Pederson
  • 45,767
  • 19
  • 102
  • 147
  • This solution is great but I need to be able to save multiple image data along with text to a single file. For example, my file would contain picture 1 title, picture 1 info... etc picture 2 title, picture 2 info... etc Any suggestions? – Alex Wood Mar 12 '10 at 06:56