qt - 如何通过http下载和保存图像?

时间:2011-06-08 18:30:39

标签: c++ qt

我想下载1张图片并保存。以下是我到目前为止的情况:

    QCoreApplication a(argc, argv);

    QNetworkAccessManager *manager = new QNetworkAccessManager();

    QNetworkReply *img = manager->get(QNetworkRequest(QUrl("http://placekitten.com/200/300")));

    QImage* img2 = new QImage();
    img2->save(img->readAll(), "omg2.png");

但是ID不起作用,请帮忙!

编辑: 那也不行,我在控制台得到“oops”:

 QNetworkAccessManager *manager = new QNetworkAccessManager();
   //connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));

    QNetworkReply *img = manager->get(QNetworkRequest(QUrl("http://placekitten.com/200/300")));

    QImage* img2 = new QImage();
    img2->loadFromData(img->readAll());

    if(img2->isNull())
        std::cout << "oops";

    img2->save("omg2.png");

编辑: 在vtable错误仍然存​​在后,qmake出现奇怪的错误:

#include <QtCore/QCoreApplication>
#include <QNetworkAccessManager>
#include <QtNetwork>
#include <QImage>
#include <QPixmap>
#include <iostream>


class omg  : public QObject{

     Q_OBJECT

    public:
        void start(){


            QNetworkAccessManager *manager = new QNetworkAccessManager();
            connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

            manager->get(QNetworkRequest(QUrl("http://placekitten.com/200/300")));
        }


    public slots:
        void replyFinished(QNetworkReply* reply)
        {
           //Check for errors first
           QImage* img2 = new QImage();
           img2->loadFromData(reply->readAll());

           if(img2->isNull())
               std::cout << "oops";

           img2->save("omg2.png");
        }


};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    omg *o = new omg();
    o->start();

    return a.exec();
}

1 个答案:

答案 0 :(得分:5)

即使在发出Http请求之前,您也试图从QNetworkReply读取数据,更不用说完成了。

NetworkAccessManager *manager = new QNetworkAccessManager();
connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));

manager->get(QNetworkRequest(QUrl("http://placekitten.com/200/300")));

...
/*Define  slot and read data from QNetworkreply*/
void finished(QNetworkReply* reply)
{
   //Check for errors first
   QImage* img2 = new QImage();
   img2->loadFromData(reply->readAll());

   if(img2->isNull())
       std::cout << "oops";

   img2->save("omg2.png");
}