Question

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 ?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top