Ejemplo n.º 1
0
bool PictureLoader::cardImageExistsOnDisk(QString & setName, QString & correctedCardname)
{
    QImage image;
    QImageReader imgReader;
    imgReader.setDecideFormatFromContent(true);

    //The list of paths to the folders in which to search for images
    QList<QString> picsPaths = QList<QString>() << picsPath + "/CUSTOM/" + correctedCardname;

    if(!setName.isEmpty())
    {
        picsPaths   << picsPath + "/" + setName + "/" + correctedCardname
                    << picsPath + "/downloadedPics/" + setName + "/" + correctedCardname;
    }

    //Iterates through the list of paths, searching for images with the desired name with any QImageReader-supported extension
    for (int i = 0; i < picsPaths.length(); i ++) {
        imgReader.setFileName(picsPaths.at(i));
        if (imgReader.read(&image)) {
            qDebug() << "Picture found on disk (set: " << setName << " card: " << correctedCardname << ")";
            imageLoaded(cardBeingLoaded.getCard(), image);
            return true;
        }
        imgReader.setFileName(picsPaths.at(i) + ".full");
        if (imgReader.read(&image)) {
            qDebug() << "Picture.full found on disk (set: " << setName << " card: " << correctedCardname << ")";
            imageLoaded(cardBeingLoaded.getCard(), image);
            return true;
        }
    }

    return false;
}
Ejemplo n.º 2
0
void KisImageLoader::run()
{
    typedef QHash<KisImageItem*,Data>::iterator Iterator;
    
    QImageReader reader;
    
    for(Iterator data=m_data.begin(); data!=m_data.end() && m_run; ++data) {
        reader.setFileName(data->path);
        qreal w = m_size;
        qreal h = m_size;
        
        if(reader.supportsOption(QImageIOHandler::Size)) {
            QSizeF imgSize = reader.size();
            
            if(imgSize.width() > imgSize.height()) {
                qreal div = m_size / imgSize.width();
                h = imgSize.height() * div;
            }
            else {
                qreal div = m_size / imgSize.height();
                w = imgSize.width() * div;
            }
        }
        
        reader.setScaledSize(QSize(w,h));
        data->image    = reader.read();
        data->isLoaded = true;
        emit sigItemContentChanged(data.key());
    }
}
Ejemplo n.º 3
0
void syImgReaderCodec::LoadCurrentFrame(syBitmap* dest) {
    if(!dest) {
        return;
    }
    sySafeMutexLocker lock(m_Mutex);
    if(lock.IsLocked()) {
        // 1. Check if m_Image is null. If not, abort (can't create the image, we could be in a worker thread)
        if(!m_Image) {
            return;
        }

        // 2. Read the image into m_Image.
        if(!m_ImageLoaded && m_Reader->read(m_Image)) {
            m_ImageLoaded = true;
        }

        // 3. Copy the image to dest.
        if(m_ImageLoaded) {
            const unsigned char* bits = m_Image->bits();
            dest->CopyFrom(bits,GetWidth(),GetHeight(),vcfRGB32,m_Image->numBytes());
        } else {
            dest->Clear();
        }
    }
}
Ejemplo n.º 4
0
void MainWindow::loadImage() {

    QImageReader reader;
    reader.setFileName(QFileDialog::getOpenFileName(this,tr("Open image"),"C:\\Users\\GiBSoN\\Desktop",tr("Image files (*.jpg *.png)")));
    QImage image = reader.read();
    imageSize = image.size();

    QVector<double> params;
    QVector<KPoint> points;

    for(int i=0;i<image.width();i++) {
        for(int j=0;j<image.height();j++) {
            params.push_back(qRed(image.pixel(i,j)));
            params.push_back(qGreen(image.pixel(i,j)));
            params.push_back(qBlue(image.pixel(i,j)));
            points.push_back(params);
            params.clear();
        }
    }

    nGas.setInputData(points);

    ui->actionNeural_Gas_Image->setEnabled(true);

    ui->graphicsView->setVisible(true);
    ui->graphicsView_2->setVisible(true);

    QGraphicsScene* scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);
    scene->addPixmap(QPixmap::fromImage(image.scaled(ui->graphicsView->width()*0.95,ui->graphicsView->height()*0.95)));
    ui->graphicsView->show();

    qDebug() << "Pixels: " << points.size() << " Dimensions: " << points[0].getDimensions();
}
void imgwidgetThumbThread::setimg(int i){

    float multiple = 0;//倍数
    QImage img;
    Image imgFlag72;
    imgFlag72.load("../bkbig.png");
    double tim = static_cast<double>(getTickCount());
    QImageReader * imgread = new QImageReader(allImgs.at(i).absoluteFilePath());
    tim = ((double)getTickCount()- tim)/getTickFrequency();
    //qDebug()<<"tim----------------"<<tim;
    if(!imgread->canRead()){
       imgread->setFileName("../picture_error.png");
    }
    QSize size = imgread->size();
    multiple = (imgread->size().width()/72.0>imgread->size().height()/48.0
                ?imgread->size().width()/72.0:imgread->size().height()/48.0);
    if(multiple>0)
        imgread->setScaledSize(imgread->size()/multiple);
     int x = (72-imgread->scaledSize().width())/2.0;
     int y = (48-imgread->scaledSize().height())/2.0;

    if(imgread->read(&img))
    {
        imgFlag72.painter(img,x,y,72,48);
        double tim = static_cast<double>(getTickCount());
        //imgFlag36 = imgFlag72.copy(18,0,36,48);
//        tim = ((double)getTickCount()- tim)/getTickFrequency();
//        qDebug()<<"tim----------------"<<tim<<i<<selectedNum;
        emit sendThumb(imgFlag72,img,size,i);
    }
}
Ejemplo n.º 6
0
VideoReviewDialog::VideoReviewDialog(QWidget* parent, const QString& imgdir)
 : QDialog(parent)
{
	setWindowTitle("Video review for Hotbuild2");

	QImageReader *reader = new QImageReader(imgdir + "img_start_bground_sample.jpg");
	QImage bground = reader->read();
	delete reader;

	QPalette* palette = new QPalette();
	palette->setBrush(QPalette::Background, *(new QBrush(bground)));
	setPalette(*palette);

	QVBoxLayout *layout = new QVBoxLayout(this);

	QWebView *webview = new QWebView(this);
	webview->setGeometry(0, 0, 640, 480);
	webview->resize(640, 480);
	QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
	webview->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
	webview->load(QUrl("http://www.youtube.com/embed/NNXV01cttMY?html5=1"));
	webview->show();

	QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, this);
//	connect(buttonBox, SIGNAL(accepted()), SLOT(accept()));
	
	layout->addWidget(webview);
	layout->addWidget(buttonBox);
}
Ejemplo n.º 7
0
void PictureLoader::picDownloadFinished(QNetworkReply *reply)
{
    if (reply->error()) {
        qDebug() << "Download failed:" << reply->errorString();
    }

    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (statusCode == 301 || statusCode == 302) {
        QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
        QNetworkRequest req(redirectUrl);
        qDebug() << "following redirect:" << cardBeingDownloaded.getCard()->getName() << "Url:" << req.url();
        networkManager->get(req);
        return;
    }

    const QByteArray &picData = reply->peek(reply->size()); //peek is used to keep the data in the buffer for use by QImageReader

    if(imageIsBlackListed(picData))
    {
        qDebug() << "Picture downloaded, but blacklisted, will consider it as not found";
        picDownloadFailed();
        reply->deleteLater();
        startNextPicDownload();
        return;
    }

    QImage testImage;
    
    QImageReader imgReader;
    imgReader.setDecideFormatFromContent(true);
    imgReader.setDevice(reply);
    QString extension = "." + imgReader.format(); //the format is determined prior to reading the QImageReader data into a QImage object, as that wipes the QImageReader buffer
    if (extension == ".jpeg")
        extension = ".jpg";
    
    if (imgReader.read(&testImage)) {
        QString setName = cardBeingDownloaded.getSetName();
        if(!setName.isEmpty())
        {
            if (!QDir().mkpath(picsPath + "/downloadedPics/" + setName)) {
                qDebug() << picsPath + "/downloadedPics/" + setName + " could not be created.";
                return;
            }

            QFile newPic(picsPath + "/downloadedPics/" + setName + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + extension);
            if (!newPic.open(QIODevice::WriteOnly))
                return;
            newPic.write(picData);
            newPic.close();
        }

        imageLoaded(cardBeingDownloaded.getCard(), testImage);
    } else {
        picDownloadFailed();
    } 

    reply->deleteLater();
    startNextPicDownload();
}
Ejemplo n.º 8
0
void PictureLoader::picDownloadFinished(QNetworkReply *reply)
{
    QString picsPath = _picsPath;
    if (reply->error()) {
        qDebug() << "Download failed:" << reply->errorString();
    }

    const QByteArray &picData = reply->peek(reply->size()); //peek is used to keep the data in the buffer for use by QImageReader
    QImage testImage;

    QImageReader imgReader;
    imgReader.setDecideFormatFromContent(true);
    imgReader.setDevice(reply);
    QString extension = "." + imgReader.format(); //the format is determined prior to reading the QImageReader data into a QImage object, as that wipes the QImageReader buffer
    if (extension == ".jpeg")
        extension = ".jpg";

    if (imgReader.read(&testImage)) {
        QString setName = cardBeingDownloaded.getSetName();
        if(!setName.isEmpty())
        {
            if (!QDir().mkpath(picsPath + "/downloadedPics/" + setName)) {
                qDebug() << picsPath + "/downloadedPics/" + setName + " could not be created.";
                return;
            }

            QFile newPic(picsPath + "/downloadedPics/" + setName + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + extension);
            if (!newPic.open(QIODevice::WriteOnly))
                return;
            newPic.write(picData);
            newPic.close();
        }

        emit imageLoaded(cardBeingDownloaded.getCard(), testImage);
    } else if (cardBeingDownloaded.getHq()) {
        qDebug() << "HQ: received invalid picture. URL:" << reply->request().url();
        cardBeingDownloaded.setHq(false);
        cardsToDownload.prepend(cardBeingDownloaded);
    } else {
        qDebug() << "LQ: received invalid picture. URL:" << reply->request().url();
        if (cardBeingDownloaded.nextSet()) {
            cardBeingDownloaded.setHq(true);
            mutex.lock();
            loadQueue.prepend(cardBeingDownloaded);
            mutex.unlock();
            emit startLoadQueue();
        } else
            emit imageLoaded(cardBeingDownloaded.getCard(), QImage());
    }

    reply->deleteLater();
    startNextPicDownload();
}
Ejemplo n.º 9
0
Frame::Frame ( const Epyx::byte_str& data, const Frame::ptime& timestamp,
	       const ptime& rt):
    timestamp(timestamp),
    realTime(rt)
{
    QByteArray message = QByteArray(
                             reinterpret_cast<const char * > ( data.data() ),
                             data.size());
    QBuffer buffer ( &message );
    QImageReader in ( &buffer, "JPG" );
    image = in.read().copy();
}
Ejemplo n.º 10
0
PhotoItem * PhotoItem::fromUrl(const KUrl & imageUrl, Scene * scene)
{
    QImage img;
    if (PhotoLayoutsEditor::instance()->hasInterface())
    {
        KIPI::ImageInfo info = PhotoLayoutsEditor::instance()->interface()->info(imageUrl);
        QImageReader ir (info.path().toLocalFile());
        if (!ir.read(&img))
            return 0;
    }
    else if (imageUrl.isValid())
    {
        QImageReader ir (imageUrl.toLocalFile());
        if (!ir.read(&img))
            return 0;
    }

    if (img.isNull())
        return 0;

    PhotoItem * result = new PhotoItem(img, imageUrl.fileName(), scene);
    result->d->setFileUrl(imageUrl);
    return result;
}
Ejemplo n.º 11
0
gboolean
media_art_file_to_jpeg (const gchar  *filename,
                        const gchar  *target,
                        GError      **error)
{
	if (max_width_in_bytes < 0) {
		g_debug ("Not saving album art from file, disabled in config");
		return TRUE;
	}

	/* TODO: Add resizing support */
	/* TODO: Add error reporting */

	QFile file (filename);

	if (!file.open (QIODevice::ReadOnly)) {
		g_message ("Could not get QFile from file: '%s'", filename);
		return FALSE;
	}

	QByteArray array = file.readAll ();
	QBuffer buffer (&array);

	buffer.open (QIODevice::ReadOnly);

	QImageReader reader (&buffer);

	if (!reader.canRead ()) {
		g_message ("Could not get QImageReader from file: '%s', reader.canRead was FALSE",
		           filename);
		return FALSE;
	}

	QImage image1;
	image1 = reader.read ();

	if (image1.hasAlphaChannel ()) {
		QImage image2 (image1.size(), QImage::Format_RGB32);
		image2.fill (QColor(Qt::black).rgb());
		QPainter painter (&image2);
		painter.drawImage (0, 0, image1);
		image2.save (QString (target), "jpeg");
	} else {
		image1.save (QString (target), "jpeg");
	}

	return TRUE;
}
Ejemplo n.º 12
0
void MainWindow_M::openFile()
{
	QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"./",tr("Images (*.png)"));
	if(fileName.isEmpty())
		return;
	QFile file(fileName);
	file.read(QIODevice::ReadOnly);
	QImageReader imageReader;
	imageReader.setDevice(&file);
	renderarea->setCurrentCanvas(imageReader.read());
	renderarea->setContentChanged(false);

	statusBar()->showMessage(fileName.section('/', -1));
	clearTempFiles();

	strCurrentFileName = fileName;
}
Ejemplo n.º 13
0
QPixmap Utils::renderSVG(const QString &path, const QSize &size)
{
    QImageReader reader;
    QPixmap pixmap;
    reader.setFileName(path);

    if (reader.canRead()) {
        const qreal ratio = qApp->devicePixelRatio();
        reader.setScaledSize(size * ratio);
        pixmap = QPixmap::fromImage(reader.read());
        pixmap.setDevicePixelRatio(ratio);
    } else {
        pixmap.load(path);
    }

    return pixmap;
}
Ejemplo n.º 14
0
void Xmpp::vCardReceived (const QXmppVCardIq& vCard)
{
    QByteArray photo = vCard.photo();
    QBuffer buffer;
    buffer.setData (photo);
    buffer.open (QIODevice::ReadOnly);
    QImageReader imageReader (&buffer);
    QImage image = imageReader.read();

    if (image.isNull())
        image = QImage (":/faces/faces/generic-user.png");

    jids.append (vCard.from());
    users.append (vCard.fullName());

    emit newUser (vCard.fullName(), vCard.from(), image);
}
Ejemplo n.º 15
0
bool readImageWithPrescale(QImageReader& reader, QImage& image, double& prescaleFactor)
{
    // used to scale the file before it is actually read to memory
    prescaleFactor = 1.0;

    int height = reader.size().height();
    if(height > HALF_DECIMATION_THRESHOLD_H)
        prescaleFactor = 0.5;
    else if(height > QUARTER_DECIMATION_THRESHOLD_H)
        prescaleFactor = 0.25;
    else if(height > EIGHTH_DECIMATION_THRESHOLD_H)
        prescaleFactor = 0.125;

    if(prescaleFactor != 1.0)
        reader.setScaledSize(QSize(reader.size().width() * prescaleFactor, reader.size().height() * prescaleFactor));

    return reader.read(&image);
}
Ejemplo n.º 16
0
void Document::pages( QVector<Okular::Page*> * pagesVector )
{
    qSort( mEntries.begin(), mEntries.end(), caseSensitiveNaturalOrderLessThen );
    QScopedPointer< QIODevice > dev;

    int count = 0;
    pagesVector->clear();
    pagesVector->resize( mEntries.size() );
    QImageReader reader;
    foreach(const QString &file, mEntries) {
        if ( mArchive ) {
            const KArchiveFile *entry = static_cast<const KArchiveFile*>( mArchiveDir->entry( file ) );
            if ( entry ) {
                dev.reset( entry->createDevice() );
            }
        } else if ( mDirectory ) {
            dev.reset( mDirectory->createDevice( file ) );
        } else {
            dev.reset( mUnrar->createDevice( file ) );
        }

        if ( ! dev.isNull() ) {
            reader.setDevice( dev.data() );
            if ( reader.canRead() )
            {
                QSize pageSize = reader.size();
                if ( !pageSize.isValid() ) {
                    const QImage i = reader.read();
                    if ( !i.isNull() )
                        pageSize = i.size();
                }
                if ( pageSize.isValid() ) {
                    pagesVector->replace( count, new Okular::Page( count, pageSize.width(), pageSize.height(), Okular::Rotation0 ) );
                    mPageMap.append(file);
                    count++;
                } else {
                    qCDebug(OkularComicbookDebug) << "Ignoring" << file << "doesn't seem to be an image even if QImageReader::canRead returned true";
                }
            }
        }
    }
    pagesVector->resize( count );
}
Ejemplo n.º 17
0
QImage PictureHelper::loadQImage(QString url)
{
	QImageReader reader;
	reader.setFileName(getImagePath(url));
	// Resize img if too large (1280x768)
	QSize imgSize = reader.size();
	if (imgSize.width()<imgSize.height()) {
		if (imgSize.height()>720) {
			imgSize.setWidth((int)imgSize.width() * 720 / imgSize.height());
			imgSize.setHeight(720);
			reader.setScaledSize(imgSize);
		}
	} else if (imgSize.width()>imgSize.height()) {
		if (imgSize.width() > 720) {
			imgSize.setHeight((int)imgSize.height() * 720 / imgSize.width());
			imgSize.setWidth(720);
			reader.setScaledSize(imgSize);
		}
	}
    return reader.read();
}
Ejemplo n.º 18
0
void DlgEditAvatar::actBrowse()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)"));
    if(fileName.isEmpty())
    {
        imageLabel->setText(tr("No image chosen."));
        return;
    }

    QImage image;
    QImageReader imgReader;
    imgReader.setDecideFormatFromContent(true);
    imgReader.setFileName(fileName);
    if(!imgReader.read(&image))
    {
        qDebug() << "Avatar image loading failed for file:" << fileName;
        imageLabel->setText(tr("Invalid image chosen."));
        return;
    }
    imageLabel->setPixmap(QPixmap::fromImage(image).scaled(400, 200, Qt::KeepAspectRatio, Qt::SmoothTransformation));
}
QPixmap loadPixmap(const QString &path)
{
    qreal ratio = 1.0;
    QPixmap pixmap;

    const qreal devicePixelRatio = qApp->devicePixelRatio();

    if (!qFuzzyCompare(ratio, devicePixelRatio)) {
        QImageReader reader;
        reader.setFileName(qt_findAtNxFile(path, devicePixelRatio, &ratio));
        if (reader.canRead()) {
            reader.setScaledSize(reader.size() * (devicePixelRatio / ratio));
            pixmap = QPixmap::fromImage(reader.read());
            pixmap.setDevicePixelRatio(devicePixelRatio);
        }
    } else {
        pixmap.load(path);
    }

    return pixmap;
}
Ejemplo n.º 20
0
void ImageLoader::run()
{
    typedef QHash<ImageItem*,Data>::iterator Iterator;
    
    QImageReader reader;

#ifdef Q_OS_WIN
    for(Iterator data=m_data.begin(); data!=m_data.end() && m_run; ++data) {
        data->image = QImage(data->path).scaled(m_size, m_size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        data->isLoaded = true;
        emit sigItemContentChanged(data.key());
    }
#else
    for(Iterator data=m_data.begin(); data!=m_data.end() && m_run; ++data) {
        reader.setFileName(data->path);
        qreal w = m_size;
        qreal h = m_size;
        

        if (reader.supportsOption(QImageIOHandler::Size)) {
            QSizeF imgSize = reader.size();
            
            if(imgSize.width() > imgSize.height()) {
                qreal div = m_size / imgSize.width();
                h = imgSize.height() * div;
            }
            else {
                qreal div = m_size / imgSize.height();
                w = imgSize.width() * div;
            }
        }

        
        reader.setScaledSize(QSize(w,h));
        data->image    = reader.read();
        data->isLoaded = true;
        emit sigItemContentChanged(data.key());
    }
#endif
}
Ejemplo n.º 21
0
void RefImage::thumbFromFile()
{
    QFile file(imagePath());

    if (file.exists())
    {
        QImageReader* imageReader = new QImageReader(imagePath());
        int imageWidth = imageReader->size().width() * (float)CAROUSEL_HEIGHT/imageReader->size().height();
        int imageHeight = CAROUSEL_HEIGHT;

        imageReader->setScaledSize(QSize(imageWidth, imageHeight));
        QImage image;
        if (imageReader->read(&image))
        {
            insertThumb(QPixmap::fromImage(image));
        }
        else
        {
            qDebug() << "read failed";
        }
    }
}
Ejemplo n.º 22
0
QSizeF HbIconSource::defaultSize()
{
    // If the default size has not been fetched yet, do it now.
    if (!mDefaultSize.isValid()) {
        type(); // make sure type is initialized
        if (mType == "NVG") {
#ifndef HB_BOOTSTRAPPED
#ifdef HB_NVG_CS_ICON
            if (!mByteArray) {
                QFile file(mFilename);
                if (!file.open(QIODevice::NotOpen | QIODevice::ReadOnly)) {
                    return QSizeF();
                }
                mByteArray = new QByteArray(file.readAll());
            }
            HbNvgEngine nvgEngine;
            mDefaultSize = nvgEngine.contentDimensions(*mByteArray);
#endif // HB_NVG_CS_ICON
#else // HB_BOOTSTRAPPED

            if (!mByteArray) {
                QFile file(mFilename);
                if (!file.open(QIODevice::NotOpen | QIODevice::ReadOnly)) {
                    return QSizeF();
                }
                mByteArray = new QByteArray(file.readAll());
            }

            mDefaultSize = nvgContentDimensions(*mByteArray);
#endif
        } else if (mType == "SVG") {
            QSvgRenderer *renderer = svgRenderer();
            if (renderer) { // isValid() is already checked in svgRenderer()
                mDefaultSize = renderer->defaultSize();
            }
            releaseSvgRenderer();
        } else if (mType == "PIC") {
            if (!mPicture) {
                mPicture = new QPicture;
                mPicture->load(mFilename);
            }
            mDefaultSize = mPicture->boundingRect().size();
        }
        // Image reader supports getting the default size without rasterizing the image so
        // using it with the formats that it supports.
        else if (mType == "MNG" || mType == "GIF" || mType == "JPG" || mType == "PNG") {
            // Note that QImageReader::canRead() results in opening the file and so the
            // file will be locked until the QImageReader instance is
            // destroyed. Therefore the image reader instance must be destroyed as soon
            // as possible and must not be kept for later use.
            // Exception: Files on Z drive on Symbian. See canKeepOpen() and releaseImageReader().
            QImageReader *reader = imageReader();
            if (reader) { // canRead() is already checked in imageReader()
                if (mType != "MNG") {
                    mDefaultSize = reader->size();
                } else {
                    // MNG handler does not support size query so have to render it to get the size
                    QImage img = reader->read();
                    mDefaultSize = img.size();
                }
            }
            releaseImageReader();
        } else if (mType != "BLOB") {
            if (!mPixmap) {
                mPixmap = new QPixmap(mFilename);
            }
            mDefaultSize = mPixmap->size();
        }
    }

    return QSizeF(mDefaultSize);
}
Ejemplo n.º 23
0
void ThumbView::addThumb(QString &imageFullPath)
{
	QStandardItem *thumbIitem = new QStandardItem();
	QImageReader thumbReader;
	QSize hintSize;
	QSize currThumbSize;
	static QImage thumb;

	if (GData::thumbsLayout == Squares)
		hintSize = QSize(thumbWidth / 2, thumbWidth / 2);
	else if (GData::thumbsLayout == Classic)
		hintSize = QSize(thumbWidth, thumbHeight + 
							(GData::showLabels? QFontMetrics(font()).height() + 5 : 0));
	
	thumbFileInfo = QFileInfo(imageFullPath);
	thumbIitem->setData(true, LoadedRole);
	thumbIitem->setData(0, SortRole);
	thumbIitem->setData(thumbFileInfo.filePath(), FileNameRole);
	if (GData::thumbsLayout != Squares && GData::showLabels)
		thumbIitem->setData(thumbFileInfo.fileName(), Qt::DisplayRole);

	thumbReader.setFileName(imageFullPath);
	currThumbSize = thumbReader.size();
	if (currThumbSize.isValid())
	{
		if (!GData::noEnlargeSmallThumb
			|| (currThumbSize.width() > thumbWidth || currThumbSize.height() > thumbHeight))
		{
			currThumbSize.scale(QSize(thumbWidth, thumbHeight), Qt::KeepAspectRatio);
		}
			
		thumbReader.setScaledSize(currThumbSize);
		thumb = thumbReader.read();

		if (GData::exifThumbRotationEnabled)
		{
			imageView->rotateByExifRotation(thumb, imageFullPath);
			currThumbSize = thumb.size();
			currThumbSize.scale(QSize(thumbWidth, thumbHeight), Qt::KeepAspectRatio);
		}
			
		thumbIitem->setIcon(QPixmap::fromImage(thumb));
	}
	else
	{
		thumbIitem->setIcon(QIcon::fromTheme("image-missing",
								QIcon(":/images/error_image.png")).pixmap(BAD_IMG_SZ, BAD_IMG_SZ));
		currThumbSize.setHeight(BAD_IMG_SZ);
		currThumbSize.setWidth(BAD_IMG_SZ);
	}

	if (GData::thumbsLayout == Compact)
	{
		if (GData::showLabels)
			currThumbSize.setHeight(currThumbSize.height() + QFontMetrics(font()).height() + 5);
		thumbIitem->setSizeHint(currThumbSize);
	}
	else
		thumbIitem->setSizeHint(hintSize);

	thumbViewModel->appendRow(thumbIitem);
}
Ejemplo n.º 24
0
QuetzalFieldsDialog::QuetzalFieldsDialog(const char *title, const char *primary,
										 const char *secondary, PurpleRequestFields *fields,
										 const char *ok_text, GCallback ok_cb,
										 const char *cancel_text, GCallback cancel_cb,
										 void *user_data, QWidget *parent)
											 : QuetzalRequestDialog(PURPLE_REQUEST_FIELDS, user_data, parent)
{
	m_ok_cb = (PurpleRequestFieldsCb) ok_cb;
	m_cancel_cb = (PurpleRequestFieldsCb) cancel_cb;
	m_fields = fields;
	DataItem root = createItem(title, primary, secondary);
	GList *group_it = purple_request_fields_get_groups(m_fields);
	bool useGroupBox = group_it->next;
	debug() << "useGroupBox" << useGroupBox;
	for (; group_it; group_it = group_it->next) {
		PurpleRequestFieldGroup *group = reinterpret_cast<PurpleRequestFieldGroup*>(group_it->data);
		DataItem groupItem;
		if (useGroupBox)
			groupItem = DataItem(purple_request_field_group_get_title(group));
		GList *field_it = purple_request_field_group_get_fields(group);
		for (; field_it; field_it = field_it->next) {
			PurpleRequestField *field = reinterpret_cast<PurpleRequestField*>(field_it->data);
			debug() << field->id << purple_request_field_is_visible(field)
					<< purple_request_field_get_type(field);
			if (!purple_request_field_is_visible(field))
				continue;
			DataItem item(purple_request_field_get_id(field),
						  purple_request_field_get_label(field),
						  QVariant());
			switch (purple_request_field_get_type(field)) {
			case PURPLE_REQUEST_FIELD_STRING:
				item.setData(QString::fromUtf8(purple_request_field_string_get_default_value(field)));
				item.setProperty("multiline", purple_request_field_string_is_multiline(field));
				item.setProperty("password", bool(purple_request_field_string_is_masked(field)));
				item.setReadOnly(!purple_request_field_string_is_editable(field));
				debug() << item.name() << item.data() << item.property("password") << item.isReadOnly();
				break;
			case PURPLE_REQUEST_FIELD_INTEGER:
				item.setData(purple_request_field_int_get_default_value(field));
				item.setProperty("minValue", G_MININT);
				item.setProperty("maxValue", G_MAXINT);
				break;
			case PURPLE_REQUEST_FIELD_BOOLEAN:
				item.setData(bool(purple_request_field_bool_get_default_value(field)));
				break;
			case PURPLE_REQUEST_FIELD_CHOICE:
				{
					GList *labels = purple_request_field_choice_get_labels(field);
					QStringList alternatives;
					for (; labels; labels = labels->next)
						alternatives << QString::fromUtf8(reinterpret_cast<char*>(labels->data));
					item.setData(alternatives.value(purple_request_field_choice_get_default_value(field)));
					item.setProperty("alternatives", alternatives);
				}
				break;
			case PURPLE_REQUEST_FIELD_LIST:
				break;
			case PURPLE_REQUEST_FIELD_LABEL:
				item.setData(purple_request_field_get_label(field));
				item.setReadOnly(true);
				item.setProperty("hideTitle", true);
				break;
			case PURPLE_REQUEST_FIELD_IMAGE:
				{
					QImageReader reader;
					QByteArray data = QByteArray::fromRawData(purple_request_field_image_get_buffer(field),
															  purple_request_field_image_get_size(field));
					QBuffer buffer(&data);
					reader.setDevice(&buffer);
					QSize imageSize = reader.size();
					if (imageSize.isValid()) {
						imageSize.setWidth(imageSize.width() * purple_request_field_image_get_scale_x(field));
						imageSize.setHeight(imageSize.height() * purple_request_field_image_get_scale_y(field));
						reader.setScaledSize(imageSize);
					}
					item.setData(qVariantFromValue(reader.read()));
					item.setProperty("imageSize", qVariantFromValue(imageSize));
					item.setReadOnly(true);
				}
				break;
			case PURPLE_REQUEST_FIELD_ACCOUNT:
				break;
			case PURPLE_REQUEST_FIELD_NONE:
			default:
				continue;
			}
			item.setProperty("mandatory", purple_request_field_is_required(field));
			if (useGroupBox)
				groupItem.addSubitem(item);
			else
				root.addSubitem(item);
		}
		if (useGroupBox)
			root.addSubitem(groupItem);
	}
	createItem(root, ok_text, cancel_text);
	return;
}
Ejemplo n.º 25
0
void PictureLoader::processLoadQueue()
{
    if (loadQueueRunning)
        return;

    loadQueueRunning = true;
    forever {
        mutex.lock();
        if (loadQueue.isEmpty()) {
            mutex.unlock();
            loadQueueRunning = false;
            return;
        }
        PictureToLoad ptl = loadQueue.takeFirst();
        mutex.unlock();

        //The list of paths to the folders in which to search for images
        QList<QString> picsPaths = QList<QString>() << _picsPath + "/CUSTOM/" + ptl.getCard()->getCorrectedName();


        QString setName=ptl.getSetName();
        if(!setName.isEmpty())
        {
            picsPaths   << _picsPath + "/" + setName + "/" + ptl.getCard()->getCorrectedName()
                        << _picsPath + "/downloadedPics/" + setName + "/" + ptl.getCard()->getCorrectedName();
        }

        QImage image;
        QImageReader imgReader;
        imgReader.setDecideFormatFromContent(true);
        bool found = false;

        //Iterates through the list of paths, searching for images with the desired name with any QImageReader-supported extension
        for (int i = 0; i < picsPaths.length() && !found; i ++) {
            imgReader.setFileName(picsPaths.at(i));
            if (imgReader.read(&image)) {
                emit imageLoaded(ptl.getCard(), image);
                found = true;
                break;
            }
            imgReader.setFileName(picsPaths.at(i) + ".full");
            if (imgReader.read(&image)) {
                emit imageLoaded(ptl.getCard(), image);
                found = true;
            }
        }

        if (!found) {
            if (picDownload) {
                cardsToDownload.append(ptl);
                if (!downloadRunning)
                    startNextPicDownload();
            } else {
                if (ptl.nextSet())
                    loadQueue.prepend(ptl);
                else
                    emit imageLoaded(ptl.getCard(), QImage());
            }
        }
    }
}
Ejemplo n.º 26
0
void PictureLoader::processLoadQueue()
{
    if (loadQueueRunning)
        return;

    loadQueueRunning = true;
    forever {
        mutex.lock();
        if (loadQueue.isEmpty()) {
            mutex.unlock();
            loadQueueRunning = false;
            return;
        }
        cardBeingLoaded = loadQueue.takeFirst();
        mutex.unlock();

        QString setName = cardBeingLoaded.getSetName();
        QString correctedCardname = cardBeingLoaded.getCard()->getCorrectedName();
        qDebug() << "Trying to load picture (set: " << setName << " card: " << correctedCardname << ")";

        //The list of paths to the folders in which to search for images
        QList<QString> picsPaths = QList<QString>() << _picsPath + "/CUSTOM/" + correctedCardname;

        if(!setName.isEmpty())
        {
            picsPaths   << _picsPath + "/" + setName + "/" + correctedCardname
                        << _picsPath + "/downloadedPics/" + setName + "/" + correctedCardname;
        }

        QImage image;
        QImageReader imgReader;
        imgReader.setDecideFormatFromContent(true);
        bool found = false;

        //Iterates through the list of paths, searching for images with the desired name with any QImageReader-supported extension
        for (int i = 0; i < picsPaths.length() && !found; i ++) {
            imgReader.setFileName(picsPaths.at(i));
            if (imgReader.read(&image)) {
                qDebug() << "Picture found on disk (set: " << setName << " card: " << correctedCardname << ")";
                emit imageLoaded(cardBeingLoaded.getCard(), image);
                found = true;
                break;
            }
            imgReader.setFileName(picsPaths.at(i) + ".full");
            if (imgReader.read(&image)) {
                qDebug() << "Picture.full found on disk (set: " << setName << " card: " << correctedCardname << ")";
                emit imageLoaded(cardBeingLoaded.getCard(), image);
                found = true;
            }
        }

        if (!found) {
            if (picDownload) {
                qDebug() << "Picture NOT found, trying to download (set: " << setName << " card: " << correctedCardname << ")";
                cardsToDownload.append(cardBeingLoaded);
                cardBeingLoaded=0;
                if (!downloadRunning)
                    startNextPicDownload();
            } else {
                if (cardBeingLoaded.nextSet())
                {
                    qDebug() << "Picture NOT found and download disabled, moving to next set (newset: " << setName << " card: " << correctedCardname << ")";
                    mutex.lock();
                    loadQueue.prepend(cardBeingLoaded);
                    cardBeingLoaded=0;
                    mutex.unlock();
                } else {
                    qDebug() << "Picture NOT found, download disabled, no more sets to try: BAILING OUT (oldset: " << setName << " card: " << correctedCardname << ")";
                    emit imageLoaded(cardBeingLoaded.getCard(), QImage());
                }
            }
        }
    }
}
Ejemplo n.º 27
0
/**
 * Loads the thumbnail from the metadata.
 * If no thumbnail is embedded, the whole image
 * is loaded and downsampled in a fast manner.
 * @param file the file to be loaded
 * @return QImage the loaded image. Null if no image
 * could be loaded at all.
 **/ 
QImage DkThumbNail::computeIntern(const QFileInfo file, const QSharedPointer<QByteArray> ba, 
								  int forceLoad, int maxThumbSize, int minThumbSize, 
								  bool rescale) {
	
	DkTimer dt;
	//qDebug() << "[thumb] file: " << file.absoluteFilePath();

	// see if we can read the thumbnail from the exif data
	QImage thumb;
	DkMetaDataT metaData;

	try {
		if (!ba || ba->isEmpty())
			metaData.readMetaData(file);
		else
			metaData.readMetaData(file, ba);

		// read the full image if we want to create new thumbnails
		if (forceLoad != force_save_thumb)
			thumb = metaData.getThumbnail();
	}
	catch(...) {
		// do nothing - we'll load the full file
	}
	removeBlackBorder(thumb);

	if (thumb.isNull() && forceLoad == force_exif_thumb)
		return QImage();

	bool exifThumb = !thumb.isNull();

	int orientation = metaData.getOrientation();
	int imgW = thumb.width();
	int imgH = thumb.height();
	int tS = minThumbSize;

	// as found at: http://olliwang.com/2010/01/30/creating-thumbnail-images-in-qt/
	QString filePath = (file.isSymLink()) ? file.symLinkTarget() : file.absoluteFilePath();
	QImageReader* imageReader;
	
	if (!ba || ba->isEmpty())
		imageReader = new QImageReader(filePath);
	else {
		QBuffer buffer;
		buffer.setData(ba->data());
		buffer.open(QIODevice::ReadOnly);
		imageReader = new QImageReader(&buffer, QFileInfo(filePath).suffix().toStdString().c_str());
		buffer.close();
	}

	if (thumb.isNull() || thumb.width() < tS && thumb.height() < tS) {

		imgW = imageReader->size().width();
		imgH = imageReader->size().height();	// locks the file!
	}
	//else if (!thumb.isNull())
	//	qDebug() << "EXIV thumb loaded: " << thumb.width() << " x " << thumb.height();
	
	if (rescale && (imgW > maxThumbSize || imgH > maxThumbSize)) {
		if (imgW > imgH) {
			imgH = (float)maxThumbSize / imgW * imgH;
			imgW = maxThumbSize;
		} 
		else if (imgW < imgH) {
			imgW = (float)maxThumbSize / imgH * imgW;
			imgH = maxThumbSize;
		}
		else {
			imgW = maxThumbSize;
			imgH = maxThumbSize;
		}
	}

	if (thumb.isNull() || thumb.width() < tS && thumb.height() < tS || forceLoad == force_full_thumb || forceLoad == force_save_thumb) {
		
		// flip size if the image is rotated by 90°
		if (metaData.isTiff() && abs(orientation) == 90) {
			int tmpW = imgW;
			imgW = imgH;
			imgH = tmpW;
			qDebug() << "EXIV size is flipped...";
		}

		QSize initialSize = imageReader->size();

		imageReader->setScaledSize(QSize(imgW, imgH));
		thumb = imageReader->read();

		// try to read the image
		if (thumb.isNull()) {
			DkBasicLoader loader;
			
			if (loader.loadGeneral(file, ba, true, true))
				thumb = loader.image();
		}

		// the image is not scaled correctly yet
		if (rescale && !thumb.isNull() && (imgW == -1 || imgH == -1)) {
			imgW = thumb.width();
			imgH = thumb.height();

			if (imgW > maxThumbSize || imgH > maxThumbSize) {
				if (imgW > imgH) {
					imgH = (float)maxThumbSize / imgW * imgH;
					imgW = maxThumbSize;
				} 
				else if (imgW < imgH) {
					imgW = (float)maxThumbSize / imgH * imgW;
					imgH = maxThumbSize;
				}
				else {
					imgW = maxThumbSize;
					imgH = maxThumbSize;
				}
			}

			thumb = thumb.scaled(QSize(imgW*2, imgH*2), Qt::KeepAspectRatio, Qt::FastTransformation);
			thumb = thumb.scaled(QSize(imgW, imgH), Qt::KeepAspectRatio, Qt::SmoothTransformation);
		}

		// is there a nice solution to do so??
		imageReader->setFileName("josef");	// image reader locks the file -> but there should not be one so we just set it to another file...
		delete imageReader;

	}
	else if (rescale) {
		thumb = thumb.scaled(QSize(imgW, imgH), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
		//qDebug() << "thumb loaded from exif...";
	}

	if (orientation != -1 && orientation != 0 && (metaData.isJpg() || metaData.isRaw())) {
		QTransform rotationMatrix;
		rotationMatrix.rotate((double)orientation);
		thumb = thumb.transformed(rotationMatrix);
	}

	// save the thumbnail if the caller either forces it, or the save thumb is requested and the image did not have any before
	if (forceLoad == force_save_thumb || (forceLoad == save_thumb && !exifThumb)) {
		
		try {

			QImage sThumb = thumb.copy();
			if (orientation != -1 && orientation != 0) {
				QTransform rotationMatrix;
				rotationMatrix.rotate(-(double)orientation);
				sThumb = sThumb.transformed(rotationMatrix);
			}

			metaData.setThumbnail(sThumb);

			if (!ba || ba->isEmpty())
				metaData.saveMetaData(file);
			else
				metaData.saveMetaData(file, ba);

			qDebug() << "[thumb] saved to exif data";
		}
		catch(...) {
			qDebug() << "Sorry, I could not save the metadata";
		}
	}


	if (!thumb.isNull())
		qDebug() << "[thumb] " << file.fileName() << " loaded in: " << dt.getTotal() << ((exifThumb) ? " from EXIV" : " from File");

	//if (!thumb.isNull())
	//	qDebug() << "thumb: " << thumb.width() << " x " << thumb.height();


	return thumb;
}
Ejemplo n.º 28
0
//
// load image and store into opengl texture
// memorize image size
//
bool frag_pane::loadImage( const QString strFile )
{
   bool bRetCode = false;  
   QImage img;
   QRgb value;
   QImageReader reader;
   int k, iRow, i, j;
   int nWidth, nHeight;

#ifdef _DEBUG
   QImage img2;
#endif // _DEBUG

   GLubyte *image = NULL;
   
   // *** Load Image ***

   // load image using QImageReader
   // set image pixels to one-dimensional 8-bit RGBA buffer

   reader.setFileName( strFile );   
   if( !reader.canRead( ) ) {
      qDebug() << "ERROR! Failed to load image " << strFile;
      goto PIX_EXIT;
    }
   
   if( !reader.read( &img ) ) {
      qDebug() << "ERROR! Failed to read image " << strFile;
      goto PIX_EXIT;
   }
   
	nWidth = img.width( );
	nHeight = img.height( );
     
   image = new GLubyte[nHeight*nWidth*4];
   if( !image ) {
      qDebug() << "ERROR! Memory Allocation Failed.";
      goto PIX_EXIT;
   }

   // to display the texture directory onto pane, set the buffer upside down
   // to copy on FBO, use the image orientation as it is

   for( i = 0; i < nHeight; i++ ) {
      iRow = nHeight - i - 1;
      //iRow = i;
      for( j = 0 ; j < nWidth ; j++ ) {
         k = i * nWidth + j;
         value = img.pixel( j, iRow );
         image[k*4] = qRed( value );
         image[k*4+1] = qGreen( value );
         image[k*4+2] = qBlue( value );
         image[k*4+3] = 255;
      }
   }
	
   // create(or re-create) the FBO to set the loaded image

   if( _in_fbo ) { 
      delete _in_fbo; 
      _in_fbo = NULL; 
   }
         
   makeCurrent( );
   _in_fbo = new QGLFramebufferObject( nWidth, nHeight, GL_TEXTURE_2D ); 
   if( !_in_fbo ) { 
      goto PIX_EXIT;
   }
   
   // set the buffer into texture
   
   glEnable( GL_TEXTURE_2D );
   
   _in_fbo->bind( );  

   glEnable( GL_TEXTURE_2D );    
   glViewport( 0, 0, nWidth, nHeight );
   
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();    

	glOrtho( 0.0, nWidth, 0.0, nHeight, -1.0, 1.0 );
   
   glMatrixMode( GL_MODELVIEW );
   glLoadIdentity( );
  
   glBindTexture( GL_TEXTURE_2D, _in_fbo->texture( ) );
	glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );   
   
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

   glTexImage2D( GL_TEXTURE_2D,
      0,
      GL_RGBA,
      nWidth,
      nHeight,
      0,
      GL_RGBA,
      GL_UNSIGNED_BYTE,
      image );
  
   _in_fbo->release();

   // --- DONE ---
   bRetCode = true;
PIX_EXIT:
   if( image ) {
      delete[] image;
      image = NULL;
   }
   return bRetCode;
}
Ejemplo n.º 29
0
/**
 * Loads the thumbnail from the metadata.
 * If no thumbnail is embedded, the whole image
 * is loaded and downsampled in a fast manner.
 * @param file the file to be loaded
 * @param ba the file buffer (can be empty)
 * @param forceLoad the loading flag (e.g. exiv only)
 * @param maxThumbSize the maximal thumbnail size to be loaded
 * @param minThumbSize the minimal thumbnail size to be loaded
 * @return QImage the loaded image. Null if no image
 * could be loaded at all.
 **/ 
QImage DkThumbNail::computeIntern(const QString& filePath, const QSharedPointer<QByteArray> ba, 
								  int forceLoad, int maxThumbSize, int minThumbSize) {
	
	DkTimer dt;
	//qDebug() << "[thumb] file: " << file.absoluteFilePath();

	// see if we can read the thumbnail from the exif data
	QImage thumb;
	DkMetaDataT metaData;

	QSharedPointer<QByteArray> baZip = QSharedPointer<QByteArray>();
#ifdef WITH_QUAZIP
	if (QFileInfo(mFile).dir().path().contains(DkZipContainer::zipMarker())) 
		baZip = DkZipContainer::extractImage(DkZipContainer::decodeZipFile(filePath), DkZipContainer::decodeImageFile(filePath));
#endif
	try {
		if (baZip && !baZip->isEmpty())	
			metaData.readMetaData(filePath, baZip);
		else if (!ba || ba->isEmpty())
			metaData.readMetaData(filePath);
		else
			metaData.readMetaData(filePath, ba);

		// read the full image if we want to create new thumbnails
		if (forceLoad != force_save_thumb)
			thumb = metaData.getThumbnail();
	}
	catch(...) {
		// do nothing - we'll load the full file
	}
	removeBlackBorder(thumb);

	if (thumb.isNull() && forceLoad == force_exif_thumb)
		return QImage();

	bool exifThumb = !thumb.isNull();

	int orientation = metaData.getOrientation();
	int imgW = thumb.width();
	int imgH = thumb.height();
	int tS = minThumbSize;

	// as found at: http://olliwang.com/2010/01/30/creating-thumbnail-images-in-qt/
	QFileInfo fInfo(filePath);
	QString lFilePath = fInfo.isSymLink() ? fInfo.symLinkTarget() : filePath;
	fInfo = lFilePath;

	QImageReader* imageReader = 0;
	
	if (!ba || ba->isEmpty())
		imageReader = new QImageReader(lFilePath);
	else {
		QBuffer buffer;
		buffer.setData(ba->data());
		buffer.open(QIODevice::ReadOnly);
		imageReader = new QImageReader(&buffer, fInfo.suffix().toStdString().c_str());
		buffer.close();
	}

	if (thumb.isNull() || (thumb.width() < tS && thumb.height() < tS)) {

		imgW = imageReader->size().width();		// crash detected: unhandled exception at 0x66850E9A (msvcr110d.dll) in nomacs.exe: 0xC0000005: Access violation reading location 0x0000C788.
		imgH = imageReader->size().height();	// locks the file!
	}
	
	if (forceLoad != DkThumbNailT::force_exif_thumb && (imgW > maxThumbSize || imgH > maxThumbSize)) {
		if (imgW > imgH) {
			imgH = qRound((float)maxThumbSize / imgW * imgH);
			imgW = maxThumbSize;
		} 
		else if (imgW < imgH) {
			imgW = qRound((float)maxThumbSize / imgH * imgW);
			imgH = maxThumbSize;
		}
		else {
			imgW = maxThumbSize;
			imgH = maxThumbSize;
		}
	}

	bool rescale = forceLoad == force_save_thumb;

	if (forceLoad != force_exif_thumb && (thumb.isNull() || thumb.width() < tS && thumb.height() < tS || forceLoad == force_full_thumb || forceLoad == force_save_thumb)) { // braces
		
		// flip size if the image is rotated by 90°
		if (metaData.isTiff() && abs(orientation) == 90) {
			int tmpW = imgW;
			imgW = imgH;
			imgH = tmpW;
			qDebug() << "EXIF size is flipped...";
		}

		QSize initialSize = imageReader->size();

		imageReader->setScaledSize(QSize(imgW, imgH));
		thumb = imageReader->read();

		// try to read the image
		if (thumb.isNull()) {
			DkBasicLoader loader;
			
			if (baZip && !baZip->isEmpty())	{
				if (loader.loadGeneral(lFilePath, baZip, true, true))
				thumb = loader.image();
			}
			else {
				if (loader.loadGeneral(lFilePath, ba, true, true))
					thumb = loader.image();
			}
		}

		// the image is not scaled correctly yet
		if (rescale && !thumb.isNull() && (imgW == -1 || imgH == -1)) {
			imgW = thumb.width();
			imgH = thumb.height();

			if (imgW > maxThumbSize || imgH > maxThumbSize) {
				if (imgW > imgH) {
					imgH = qRound((float)maxThumbSize / imgW * imgH);
					imgW = maxThumbSize;
				} 
				else if (imgW < imgH) {
					imgW = qRound((float)maxThumbSize / imgH * imgW);
					imgH = maxThumbSize;
				}
				else {
					imgW = maxThumbSize;
					imgH = maxThumbSize;
				}
			}

			thumb = thumb.scaled(QSize(imgW*2, imgH*2), Qt::KeepAspectRatio, Qt::FastTransformation);
			thumb = thumb.scaled(QSize(imgW, imgH), Qt::KeepAspectRatio, Qt::SmoothTransformation);
		}

		// is there a nice solution to do so??
		imageReader->setFileName("josef");	// image reader locks the file -> but there should not be one so we just set it to another file...
	}
	else if (rescale) {
		thumb = thumb.scaled(QSize(imgW, imgH), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
	}

	if (imageReader)
		delete imageReader;

	if (orientation != -1 && orientation != 0 && (metaData.isJpg() || metaData.isRaw())) {
		QTransform rotationMatrix;
		rotationMatrix.rotate((double)orientation);
		thumb = thumb.transformed(rotationMatrix);
	}

	// save the thumbnail if the caller either forces it, or the save thumb is requested and the image did not have any before
	if (rescale || (forceLoad == save_thumb && !exifThumb)) {
		
		try {

			QImage sThumb = thumb.copy();
			if (orientation != -1 && orientation != 0) {
				QTransform rotationMatrix;
				rotationMatrix.rotate(-(double)orientation);
				sThumb = sThumb.transformed(rotationMatrix);
			}

			metaData.setThumbnail(sThumb);

			if (!ba || ba->isEmpty())
				metaData.saveMetaData(lFilePath);
			else
				metaData.saveMetaData(lFilePath, ba);

			qDebug() << "[thumb] saved to exif data";
		}
		catch(...) {
			qDebug() << "Sorry, I could not save the metadata";
		}
	}


	if (!thumb.isNull())
		qDebug() << "[thumb] " << fInfo.fileName() << "(" << thumb.width() << " x " << thumb.height() << ") loaded in: " << dt.getTotal() << ((exifThumb) ? " from EXIV" : " from File");

	return thumb;
}
void PhotoBomberApp::manipulatePhoto(const QString &fileName)
{
    QImageReader reader;

    // Set image name from the given file name.
    reader.setFileName(fileName);
    QImage image = getRotateImage(fileName); //reader.read();
    QSize imageSize = image.size();
    QColor color;

    // Gray it out! (this is not the gray-scale algorithm that should be used)
    for (int i = 0; i < imageSize.width(); i++)
        for (int ii = 0; ii < imageSize.height(); ii++) {
            color = QColor(image.pixel(i, ii));
            color.setRed((color.red() + color.green() + color.blue()) / 3);
            color.setGreen(color.red());
            color.setBlue(color.red());
            image.setPixel(i, ii, color.rgb());
        }

    // Paint an image on top of another image, so we add the gray-scaled image first.
    QPainter merger(&image);

    QString appFolder(QDir::homePath());
    appFolder.chop(4);

    QString bomberFileName;
    QString bombfolder;

    // The aspect ratio value is used for selecting correct folder for bomber photos.
    float imageWidth = imageSize.width();
    float imageHeight = imageSize.height();
    float aspectRatio = imageWidth / imageHeight;

    if (aspectRatio == 1) {
        bombfolder = appFolder + "app/native/assets/720x720/images/bombers/";
    } else {
        bombfolder = appFolder + "app/native/assets/images/bombers/";
    }

    // Positions for the bombers; we need these so we can overlay the bomber image at it's correct position.
    // The reason for not making an image as large as the picture is so we can change resolution and or switch
    // between portrait/landscape if we would want to.
    enum positions
    {
        TOP, CENTER, BOTTOM, LEFT, RIGHT
    };

    int vertical = RIGHT;
    int horizontal = BOTTOM;

    switch (random() % 9) {
        case 0:
            bomberFileName = bombfolder + "cow.png";
            vertical = RIGHT;
            horizontal = CENTER;
            break;
        case 1:
            bomberFileName = bombfolder + "crow.png";
            vertical = RIGHT;
            horizontal = BOTTOM;
            break;
        case 2:
            bomberFileName = bombfolder + "dog_2.png";
            vertical = RIGHT;
            horizontal = BOTTOM;
            break;
        case 3:
            bomberFileName = bombfolder + "larsenby.png";
            vertical = RIGHT;
            horizontal = BOTTOM;
            break;
        case 4:
            bomberFileName = bombfolder + "dog_1.png";
            vertical = LEFT;
            horizontal = BOTTOM;
            break;
        case 5:
            bomberFileName = bombfolder + "snail.png";
            vertical = LEFT;
            horizontal = BOTTOM;
            break;
        case 6:
            bomberFileName = bombfolder + "cat.png";
            vertical = RIGHT;
            horizontal = BOTTOM;
            break;
        case 7:
            bomberFileName = bombfolder + "pair.png";
            vertical = CENTER;
            horizontal = BOTTOM;
            break;
        case 8:
            bomberFileName = bombfolder + "seagull.png";
            vertical = LEFT;
            horizontal = TOP;
            break;

        default:
            bomberFileName = bombfolder + "crow.png";
            vertical = RIGHT;
            horizontal = BOTTOM;
            break;
    }

    reader.setFileName(bomberFileName);
    QImage bombimage = reader.read();

    // Read image current size.
    QSize bomberImageSize = bombimage.size();

    int vertical_pos;
    int horizontal_pos;

    // Vertical position
    if (vertical == LEFT) {
        vertical_pos = 0;
    } else if (vertical == CENTER) {
        vertical_pos = imageSize.width() / 2 - bomberImageSize.width() / 2;
    } else if (vertical == RIGHT) {
        vertical_pos = imageSize.width() - bomberImageSize.width();
    }

    // Horizontal position
    if (horizontal == TOP) {
        horizontal_pos = 0;
    } else if (horizontal == CENTER) {
        horizontal_pos = imageSize.height() / 2 - bomberImageSize.height() / 2;
    } else if (horizontal == BOTTOM) {
        horizontal_pos = imageSize.height() - bomberImageSize.height();
    }

    // Add the image and save the composition.
    merger.drawImage(vertical_pos, horizontal_pos, bombimage);
    image.save(fileName, "JPG");

    // Show the photo by using this function that take use of the InvokeManager.
    showPhotoInCard(fileName);
}