Frage

I am using this to load an image:

QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("."));

if (fileName == "")
{
    QMessageBox::critical(this, tr("Error"), tr("Could not open File"));
    return;
}
QImage img;
img.load(fileName);

And this to save it back after processing it:

this->img.save(this->fileName);

But the issue is that the size of image is increasing even if I don't process the image at all i.e. simply load and save the image?
Even though this is by ~5kb for a png image of ~500kb it is way too high for my algorithm(~150kb for the same image, after just one iteration). The only operations I do in my algorithm are swapping of two pixels and XORing. My algorithm involves multiple iterations.
How to resolve this issue of size.
I am actually doing an image encryption/decryption algorithm and this increase of size is creating serious problems for me.
I am using Qt 5.2 on linux mint 16.

War es hilfreich?

Lösung

A QImage is storing the contents of an image, not its representation in a file. Thus, even if you "don't process" the image, you're still decompressing it on loading, and recompressing it into whatever format the filename implies.

If the image format uses lossy compression, you'll be likely degrading the image each time it gets loaded and re-saved - thus it should be avoided.

If the image format uses lossless compression, the compression factor is highly contents-dependent - your processing of the image will have impact on the image size.

If you wish to preserve file representation of an image, you should load the file into a buffer, and only operate on QImage when you intend to change it. Thus:

QFile file(fileName);
if (! file.open(QIODevice::ReadOnly)) return false;
QByteArray imageData = file.readAll();
if (imageData.isEmpty()) return false;
file.close();    

// process the image
QImage img;
QBuffer imageBuffer(&imageData);
imageBuffer.open(QIODevice::ReadOnly);
img.load(&imageBuffer, "JPG");
imageBuffer.close();
//
// process the image here
//
imageData.clear();
imageBuffer.open(QIODevice::WriteOnly);
img.save(&imageBuffer);
imageBuffer.close();    

// save the image
QSaveFile file(fileName);
if (! file.open(QIODevice::WriteOnly)) return false;
file.write(imageData);

Andere Tipps

If you mean size of the file, I believe it has to do with quality parameter of function QImage::save. The last one:

bool QImage::save ( const QString & fileName, const char * format = 0, int quality = -1 ) const

After QImage is already loaded it has no memory of quality which it has initially, then on save Qt makes quality default so if quality of image initially was lower than default it may result in raising of file size a bit. (Also in case of loseless formats like .png quality seems to mean just how strongly compressed file is)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top