imageloader.cpp Example File
imageloader/src/imageloader.cpp
#include "imageloader.hpp"
#include "imageprocessor.hpp"
#include <bb/ImageData>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QDebug>
ImageLoader::ImageLoader(const QString &imageUrl, QObject* parent)
: QObject(parent)
, m_loading(false)
, m_imageUrl(imageUrl)
{
}
ImageLoader::~ImageLoader() { }
void ImageLoader::load()
{
m_loading = true;
emit loadingChanged();
QNetworkAccessManager* netManager = new QNetworkAccessManager(this);
const QUrl url(m_imageUrl);
QNetworkRequest request(url);
QNetworkReply* reply = netManager->get(request);
bool ok = connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished()));
Q_ASSERT(ok);
Q_UNUSED(ok);
}
void ImageLoader::onReplyFinished()
{
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response;
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
const int available = reply->bytesAvailable();
if (available > 0) {
const QByteArray data(reply->readAll());
ImageProcessor *imageProcessor = new ImageProcessor(data);
QFuture<QImage> future = QtConcurrent::run(imageProcessor, &ImageProcessor::start);
bool ok = connect(&m_watcher, SIGNAL(finished()), this, SLOT(onImageProcessingFinished()));
Q_ASSERT(ok);
Q_UNUSED(ok);
m_watcher.setFuture(future);
}
} else {
m_label = tr("Error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString());
emit labelChanged();
m_loading = false;
emit loadingChanged();
}
reply->deleteLater();
} else {
m_label = tr("Download failed. Check internet connection");
emit labelChanged();
m_loading = false;
emit loadingChanged();
}
}
void ImageLoader::onImageProcessingFinished()
{
QImage swappedImage = m_watcher.future().result().rgbSwapped();
if(swappedImage.format() != QImage::Format_RGB32) {
swappedImage = swappedImage.convertToFormat(QImage::Format_RGB32);
}
const bb::ImageData imageData = bb::ImageData::fromPixels(swappedImage.bits(), bb::PixelFormat::RGBX, swappedImage.width(), swappedImage.height(), swappedImage.bytesPerLine());
m_image = bb::cascades::Image(imageData);
emit imageChanged();
m_label.clear();
emit labelChanged();
m_loading = false;
emit loadingChanged();
}
QVariant ImageLoader::image() const
{
return QVariant::fromValue(m_image);
}
QString ImageLoader::label() const
{
return m_label;
}
bool ImageLoader::loading() const
{
return m_loading;
}