views:

82

answers:

1

Hey everyone,

I want to be able to save an image as text in a xml file and I can't manage to find a efficient way to do it !

So far I tried :

QByteArray ImageAsByteArray;
QBuffer ImageBuffer(&ImageAsByteArray);
ImageBuffer.open(QIODevice::WriteOnly);
rImage.save(&ImageBuffer, "PNG"); 

return QString(ImageAsByteArray.toBase64());

Despite the fact it's working, the result is a file that is huge ! I tried adding some QCompress in there but without much success... Actually the QCompress doesn't seem to compress anything...

I think I'm doing it the wrong way, but could someone enlight my path please ?

+3  A: 

Are you loading the image file to QImage and then getting the bytes from that QImage? If yes, then you are base64 encoding the raw image. In that case it really doesn't matter at all how much the original image file is compressed.

You should read the original image file (png or jpg) as a binary stream and base64 encode that stream. Example:

QFile* file = new QFile("Image001.jpg");
file->open(QIODevice::ReadOnly);
QByteArray image = file->readAll();
int originalSize = image.length();

QString encoded = QString(image.toBase64());
int encodedSize = encoded.size();

My test image's originalSize is 1028558 bytes, and encodedSize is 1371412 bytes, which is 33% more than the originalSize (see Jérôme's comment to your question).

Roku
It works this way but, at some point I'll need a QPixmap to display this image... And when I save it after using it, its size is increased by a 10 factor... It's annoying because for some reasons (resize purpose for example) I want to have a QImage or a QPixmap, but each time, the size of the image is dramatically increased as soon as it's been one of those objects... Any ideas ?
Andy M
If you have a QPixmap, save it first to a QByteArray (see http://doc.qt.nokia.com/4.7/qpixmap.html#save-2 ), for example in JPG format. Now you can save that byte array (containing the image data in compressed format) to the disk.
Roku
That's what I did, but if I need to resize the image, I have to first make it a QPixmal (or QImage), resize it, then get it as a QByteArray, but the weight is much bigger ! As soon as I pass the image into a QPixmap, I can't get it back to QByteArray with a correct weight...
Andy M
Andy M