mrz
mrz

Reputation: 1872

Qt - Download Images from web

I am trying to write an application using Qt/C++ to download images from web. The program will be provided a list of URLs as a text file, and should open each URL and download all images in each website.

In order to do so, I subclass QNetworkAccessManager and override createRequest method/function like below:

QNetworkReply* clsNAM::createRequest(Operation op,const QNetworkRequest & req,
                                                    QIODevice * outgoingData )
{
    return new clsNR(QNetworkAccessManager::createRequest(_op,_req,_outgoingData));
}

My subclass of QNetworkReply class, clsNR, identifies the type of the reply from its raw header, something like:

bool clsNR::isImage()
{
    if(this->rawHeader("Content-Type").toLower().startsWith("image"))
       return true;
    else
       return false;
}

As I get readyRead signal (which means there is data available to read) ,I store the coming in a QbyteArray. I have connected a slot in clsNR to save the image when the QNetworkReply is finished. It looks like:

void clsNR::slotCloseConnection()
{
    if(isImage())
    {
      QImage image;
      bool bool1 = image.loadFromData(ContentData);
      QString name(QDir::homePath());
      name.append(this->url().path());
      bool bool2 = image.save(name,0,-1);
    }
}

There is something wrong with my saving. bool1 is true, but bool2 is false. The reason I'm using the url path for the name is to generate unique name for images. When I print out the name, it's something like:

"/home/guest/images/splash/3.jpg"

So My questions would be:

  1. What I'm doing wrong with QImage?
  2. Can I use QFile and QStream to write down the images instead?

Upvotes: 1

Views: 1133

Answers (1)

Blastcore
Blastcore

Reputation: 370

I'll add something else, like Mat said in your comment. If you need to check if the directory exists use Qdir::exists() and if you need to create it use QDir::mkdir()

Upvotes: 0

Related Questions