コード例 #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;
}
コード例 #2
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();
}
コード例 #3
0
void LoadFilter::detectFormat()
{
    // FIXME: work-around bug 242369
    if (priv->fileFormatQt.isEmpty() &&
        priv->fileFormat.isEmpty() &&
        priv->fileName.endsWith(".mp4")) {
        if (priv->filterError == QuillImageFilter::NoError)
            priv->filterError = QuillImageFilter::UnsupportedFormatError;
        priv->isInvalid = true;
        priv->fileFormat = "video/mp4";
        return;
    }

    if (priv->fileFormatQt.isEmpty() &&
        (priv->fileFormat.isEmpty() || priv->fileFormat.startsWith("image/"))) {
        QImageReader reader;
        if (!priv->iODevice)
            reader.setFileName(priv->fileName);
        else
            reader.setDevice(priv->iODevice);

        priv->fileFormatQt = formatFromReader(&reader);
    }

    if (priv->fileFormat.isEmpty()) {
        priv->fileFormat = MimeType::fromQImageFormat(priv->fileFormatQt);
    }

    if (priv->fileFormatQt.isEmpty()) {
        if (priv->filterError == QuillImageFilter::NoError)
            priv->filterError = QuillImageFilter::UnsupportedFormatError;
        priv->isInvalid = true;
    }
}
コード例 #4
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());
    }
}
コード例 #5
0
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);
    }
}
コード例 #6
0
bool syImgReaderCodec::OpenInput(const syString filename) {
    bool result = false;
    syString newfilename = filename;
    if(m_Filename != "" && filename.empty()) {
        newfilename = m_Filename;
    } else {
        newfilename = filename;
    }
    if(m_Reader && syString(m_Reader->fileName()) != newfilename) {
        CloseInput();
        if(m_Reader) {
            m_Reader->setFileName(newfilename);
            m_Filename = filename;
        }
    }
    if(!m_Reader) {
        m_Reader = new QImageReader(newfilename);
        m_Filename = newfilename;
    }
    result = m_Reader->canRead();
    if(result) {
        if(m_Image) {
            delete m_Image;
        }
        m_Image = new QImage(GetWidth(),GetHeight(),QImage::Format_RGB32);
    }
    return result;
}
コード例 #7
0
bool ImageStripScene::setCurrentDirectory(const QString& path)
{
    QMutexLocker locker(&m_mutex);
    QDir         directory(path);
    QImageReader reader;
    
    if(directory.exists()) {
        clear();
        
        if(m_loader) {
            m_loader->disconnect(this);
            m_loader->stopExecution();
            
            if(!m_loader->wait(500)) {
                m_loader->terminate();
                m_loader->wait();
            }
        }
        
        delete m_loader;
        
        m_numItems = 0;
        m_loader   = new ImageLoader(m_imgSize);
        connect(m_loader, SIGNAL(sigItemContentChanged(ImageItem*)), SLOT(slotItemContentChanged(ImageItem*)));
        
        QStringList            files  = directory.entryList(QDir::Files);
        QGraphicsLinearLayout* layout = new QGraphicsLinearLayout();
        
        for(QStringList::iterator name=files.begin(); name!=files.end(); ++name) {
            QString path = directory.absoluteFilePath(*name);
            reader.setFileName(path);
            
            if(reader.canRead()) {
                ImageItem* item = new ImageItem(m_imgSize, path, m_loader);
                m_loader->addPath(item, path);
                layout->addItem(item);
                ++m_numItems;
            }
        }
        
        QGraphicsWidget* widget = new QGraphicsWidget();
        widget->setLayout(layout);
        widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        
        addItem(widget);
        setSceneRect(widget->boundingRect());
        
        m_loader->start(QThread::LowPriority);
        return true;
    }
    
    return false;
}
コード例 #8
0
ファイル: utils.cpp プロジェクト: rekols/redict
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;
}
コード例 #9
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();
}
コード例 #10
0
ファイル: dlg_edit_avatar.cpp プロジェクト: DINKIN/Cockatrice
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));
}
コード例 #11
0
ファイル: mainwindow.cpp プロジェクト: laybatin/ImageDomino
/*
 * DirFilesFilter
 * QFileSystemModel의 버그(캐시?) 인지 setNameFilter를 해도 계속해서 디렉토리나 파일이 보임
 * 그래서 디렉토리를 조회하여 직접 리스트를 만듬
 */
void MainWindow::DirFilesFilter(QString path) {
    qDebug() << "directoryLoaded";

    QModelIndex fileIdx = files_->index(path);
    int numRows = files_->rowCount(fileIdx);


    QImageReader imgReader;
    for (int index=0; index<numRows; index++) {
        QModelIndex mi = files_->index(index, 0, fileIdx);
        QFileInfo fileInfo = files_->fileInfo(mi);
        imgReader.setFileName(fileInfo.absoluteFilePath());
        if(imgReader.canRead())
            extfilter_imgs_ << fileInfo;
    }


    //extfilter_imgs 파일들을 모델로 만든다.
    FilesModelUpdate();

}
コード例 #12
0
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;
}
コード例 #13
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
}
コード例 #14
0
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);
}
コード例 #15
0
/** Albums have covers usually. */
void LibraryItemDelegate::drawAlbum(QPainter *painter, QStyleOptionViewItem &option, QStandardItem *item) const
{
	/// XXX: reload cover with high resolution when one has increased coverSize (every 64px)
	static QImageReader imageReader;
	SettingsPrivate *settingsPrivate = SettingsPrivate::instance();

	// Album has no picture yet
	bool itemHasNoIcon = item->icon().isNull();
	if (itemHasNoIcon) {

		// Check first if an inner cover should be displayed
		if (item->data(Miam::DF_InternalCover).toString().isEmpty()) {
			QString coverPath = item->data(Miam::DF_CoverPath).toString();
			if (!coverPath.isEmpty()) {
				// qDebug() << Q_FUNC_INFO << "loading external cover from harddrive";
				imageReader.setFileName(QDir::fromNativeSeparators(coverPath));
				imageReader.setScaledSize(QSize(_coverSize, _coverSize));
				item->setIcon(QPixmap::fromImage(imageReader.read()));
				itemHasNoIcon = false;
			}
		} else {
			FileHelper fh(item->data(Miam::DF_InternalCover).toString());
			std::unique_ptr<Cover> cover(fh.extractCover());
			if (cover) {
				QPixmap p;
				if (p.loadFromData(cover->byteArray(), cover->format())) {
					if (!p.isNull()) {
						item->setIcon(p);
						itemHasNoIcon = false;
					}
				//} else {
				//	qDebug() << Q_FUNC_INFO << "couldn't load data into QPixmap";
				}
			//} else {
			//	qDebug() << Q_FUNC_INFO << "couldn't extract inner cover";
			}
		}
	}

	painter->save();
	QRect cover;
	if (QGuiApplication::isLeftToRight()) {
		cover = QRect(option.rect.x() + 1, option.rect.y() + 1, _coverSize, _coverSize);
	} else {
		cover = QRect(option.rect.width() + 19 - _coverSize - 1, option.rect.y() + 1, _coverSize, _coverSize);
	}
	// If font size is greater than the cover, align it
	if (_coverSize < option.rect.height() - 2) {
		painter->translate(0, (option.rect.height() - 1 - _coverSize) / 2);
	}

	if (itemHasNoIcon) {
		if (_iconOpacity <= 0.25) {
			painter->setOpacity(_iconOpacity);
		} else {
			painter->setOpacity(0.25);
		}
		painter->drawPixmap(cover, QPixmap(":/icons/disc"));
	} else {
		painter->setOpacity(_iconOpacity);
		QPixmap p = option.icon.pixmap(QSize(_coverSize, _coverSize));
		painter->drawPixmap(cover, p);
	}
	painter->restore();

	// Add an icon on the right if album is from some remote location
	bool isRemote = item->data(Miam::DF_IsRemote).toBool();
	int offsetWidth = 0;
	if (isRemote) {
		int iconSize = 31;
		QRect iconRemoteRect(option.rect.x() + option.rect.width() - (iconSize + 4),
							 (option.rect.height() - iconSize)/ 2 + option.rect.y() + 2,
							 iconSize,
							 iconSize);
		QPixmap iconRemote(item->data(Miam::DF_IconPath).toString());
		painter->save();
		painter->setOpacity(0.5);
		painter->drawPixmap(iconRemoteRect, iconRemote);
		painter->restore();
		offsetWidth = iconSize;
	}

	option.textElideMode = Qt::ElideRight;
	QRect rectText;

	// It's possible to have missing covers in your library, so we need to keep alignment.
	if (QGuiApplication::isLeftToRight()) {
		rectText = QRect(option.rect.x() + _coverSize + 5,
						 option.rect.y(),
						 option.rect.width() - (_coverSize + 7) - offsetWidth,
						 option.rect.height() - 1);
	} else {
		rectText = QRect(option.rect.x(), option.rect.y(), option.rect.width() - _coverSize - 5, option.rect.height());
	}

	QFontMetrics fmf(settingsPrivate->font(SettingsPrivate::FF_Library));
	QString s = fmf.elidedText(option.text, Qt::ElideRight, rectText.width());

	this->paintText(painter, option, rectText, s, item);
}
コード例 #16
0
ファイル: thumbview.cpp プロジェクト: JHooverman/phototonic
void ThumbView::loadThumbsRange()
{
	static bool inProgress = false;
	static QImageReader thumbReader;
	static QSize currThumbSize;
	static int currRowCount;
	static QString imageFileName;
	QImage thumb;
	int currThumb;
	bool imageReadOk;

	if (inProgress) {
		abortOp = true;
		QTimer::singleShot(0, this, SLOT(loadThumbsRange()));
		return;
	}

	inProgress = true;
	currRowCount = thumbViewModel->rowCount();

	for (	scrolledForward? currThumb = thumbsRangeFirst : currThumb = thumbsRangeLast;
			(scrolledForward? currThumb <= thumbsRangeLast : currThumb >= thumbsRangeFirst);
			scrolledForward? ++currThumb : --currThumb) {

		if (abortOp || thumbViewModel->rowCount() != currRowCount || currThumb < 0) {
			break;
		}

		if (thumbViewModel->item(currThumb)->data(LoadedRole).toBool()) {
			continue;
		}

		imageFileName = thumbViewModel->item(currThumb)->data(FileNameRole).toString();
		thumbReader.setFileName(imageFileName);
		currThumbSize = thumbReader.size();
		imageReadOk = false;

		if (currThumbSize.isValid()) {
			if (!GData::noEnlargeSmallThumb
				|| (currThumbSize.width() > thumbWidth || currThumbSize.height() > thumbHeight))
			{
				currThumbSize.scale(QSize(thumbWidth, thumbHeight), Qt::KeepAspectRatio);
			}

			thumbReader.setScaledSize(currThumbSize);
			imageReadOk = thumbReader.read(&thumb);
		}

		if (imageReadOk) {
			if (GData::exifThumbRotationEnabled) {
				imageView->rotateByExifRotation(thumb, imageFileName);
				currThumbSize = thumb.size();
				currThumbSize.scale(QSize(thumbWidth, thumbHeight), Qt::KeepAspectRatio);
			}
			
			thumbViewModel->item(currThumb)->setIcon(QPixmap::fromImage(thumb));
		} else {
			thumbViewModel->item(currThumb)->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);
			thumbViewModel->item(currThumb)->setSizeHint(currThumbSize);
			if (isThumbVisible(thumbViewModel->item(currThumb)->index()))
				setRowHidden(currThumb, false);
		}

		thumbViewModel->item(currThumb)->setData(true, LoadedRole);

		QApplication::processEvents();
	}

	if (GData::thumbsLayout == Compact && thumbViewModel->rowCount() > 0) {
		setRowHidden(0 , false);
	}

	inProgress = false;
	abortOp = false;
}
コード例 #17
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;
}
コード例 #18
0
ファイル: thumbview.cpp プロジェクト: JHooverman/phototonic
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);
}
コード例 #19
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;
}
コード例 #20
0
ファイル: DkThumbs.cpp プロジェクト: pmattern/nomacs
/**
 * 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;
}
コード例 #21
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());
            }
        }
    }
}
コード例 #22
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());
                }
            }
        }
    }
}