Question

I'm writing a program which will have a list of users and each one will have their own picture from an online source. I am downloading the data successfully and I'm struggling with formatting the picture format. It saves the file successfully but it doesn't save it in a readable format.

void FriendsListProcess::picRequesFinished(QNetworkReply *reply)
{
    QByteArray data = reply->readAll();
    if(reply->error())
    {
        qDebug() << reply->errorString();
        return;
    }
    emit savePic(pic_name_path,data);
    reply->deleteLater();
}

void FriendsListProcess::savePicToFile(QString file, QByteArray &pic_data)
{
qDebug() << "File name from write pic: " << file;
QFile f(file);
if(f.open(QIODevice::WriteOnly))
{
    QDataStream out(&f);
    out << pic_data;
        f.close();
}
}

when i try to open the saved file windows says

"Windows Photo Viewer can't open this picture because either Photo Viewer doesn't support this file format. or you don't have the lates updates to Photo Viewer"

have you guys got any suggestions?

Was it helpful?

Solution

You have the following issues in your code:

  • You write the image data as if it was a text stream, whereas it is a binary stream.

  • You reading everything in without reading by chunks. This potentially wastes more memory than necessary.

  • You lack the error checking in your code.

  • You needlessly have the signal/slot indirection in here.

  • It is superfluous to check the QNetworkReply error in the finished handler slot because such things would be better caught in the error signal handler slot.

  • You open the file as ReadOnly, whereas you would like to write it.

  • You open the file with text open mode flag, whereas an image is binary data.

I would be writing something like this:

void FriendsListProcess::picRequesFinished(QNetworkReply *reply)
{
    QFile file(pic_name_path);
    if (!file.open(QIODevice::WriteOnly)) {
        qDebug() << "Failed to open the file for reading:" << file.fileName();
        return;
    }

    // You would need to make sure you do not get irrelevant data in the meantime
    while (reply->bytesAvailable()) {
        if (file.write(reply->read(512)) == -1)
            qDebug() << "Error while reading data:" << file.errorString();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top