void QDeclarativeGeoMapPixmapObject::finished() { if (m_reply->error() != QNetworkReply::NoError) { m_reply->deleteLater(); m_reply = 0; return; } QImage image; QImageReader imageReader(m_reply); if (imageReader.read(&image)) { setPixmap(QPixmap::fromImage(image)); setStatus(QDeclarativeGeoMapPixmapObject::Ready); } else { setPixmap(QPixmap()); setStatus(QDeclarativeGeoMapPixmapObject::Error); //qWarning() << "image read fail"; } m_reply->deleteLater(); m_reply = 0; }
QImage UCScalingImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) { Q_UNUSED(requestedSize); int separatorPosition = id.indexOf("/"); float scaleFactor = id.left(separatorPosition).toFloat(); QString path = id.mid(separatorPosition+1); QFile file(path); if (file.open(QIODevice::ReadOnly)) { QImage image; QImageReader imageReader(&file); if (!qFuzzyCompare(scaleFactor, (float)1.0)) { QSize realSize = imageReader.size(); imageReader.setScaledSize(realSize * scaleFactor); } imageReader.read(&image); *size = image.size(); return image; } else { return QImage(); } }
void QgsLayoutItemPicture::loadRemotePicture( const QString &url ) { //remote location QgsNetworkContentFetcher fetcher; QEventLoop loop; connect( &fetcher, &QgsNetworkContentFetcher::finished, &loop, &QEventLoop::quit ); fetcher.fetchContent( QUrl( url ) ); //wait until picture fetched loop.exec( QEventLoop::ExcludeUserInputEvents ); QNetworkReply *reply = fetcher.reply(); if ( reply ) { QImageReader imageReader( reply ); mImage = imageReader.read(); mMode = FormatRaster; } else { mMode = FormatUnknown; } }
// Update the information labels in the bottom left corner of the dialog // and switches the editor mode, if required, according to the detected data type. void EditDialog::updateCellInfoAndMode(const QByteArray& data) { QByteArray cellData = data; switchEditorMode(ui->buttonAutoSwitchMode->isChecked()); // Image data needs special treatment if (dataType == Image || dataType == SVG) { QBuffer imageBuffer(&cellData); QImageReader imageReader(&imageBuffer); // Display the image format QString imageFormat = imageReader.format(); ui->labelType->setText(tr("Type of data currently in cell: %1 Image").arg(imageFormat.toUpper())); // Display the image dimensions and size QSize imageDimensions = imageReader.size(); int imageSize = cellData.size(); QString labelSizeText = tr("%1x%2 pixel(s)").arg(imageDimensions.width()).arg(imageDimensions.height()) + ", " + humanReadableSize(imageSize); ui->labelSize->setText(labelSizeText); return; } // Use a switch statement for the other data types to keep things neat :) switch (dataType) { case Null: // NULL data type ui->labelType->setText(tr("Type of data currently in cell: NULL")); ui->labelSize->setText(tr("%n byte(s)", "", 0)); ui->editorText->setStyleSheet("QTextEdit{ font-style: italic; }"); ui->editorText->setPlaceholderText(Settings::getValue("databrowser", "null_text").toString()); break; case Text: { // Text only // Determine the length of the cell text in characters (possibly different to number of bytes). int textLength = QString(cellData).length(); ui->labelType->setText(tr("Type of data currently in cell: Text / Numeric")); ui->labelSize->setText(tr("%n char(s)", "", textLength)); break; } case JSON: { // Valid JSON // Determine the length of the cell text in characters (possibly different to number of bytes). int jsonLength = QString(cellData).length(); ui->labelType->setText(tr("Type of data currently in cell: Valid JSON")); ui->labelSize->setText(tr("%n char(s)", "", jsonLength)); break; } default: // Determine the length of the cell data int dataLength = cellData.length(); // If none of the above data types, consider it general binary data ui->labelType->setText(tr("Type of data currently in cell: Binary")); ui->labelSize->setText(tr("%n byte(s)", "", dataLength)); break; } }
void EditDialog::exportData() { QStringList filters; switch (dataType) { case Image: { // Images get special treatment. // Determine the likely filename extension. QByteArray cellData = hexEdit->data(); QBuffer imageBuffer(&cellData); QImageReader imageReader(&imageBuffer); QString imageFormat = imageReader.format(); filters << tr("%1 Image").arg(imageFormat.toUpper()) % " (*." % imageFormat.toLower() % ")"; break; } case Binary: filters << tr("Binary files (*.bin)"); break; case Text: // Base the XML case on the mode, not the data type since XML detection is currently not implemented. if (ui->comboMode->currentIndex() == XmlEditor) filters << tr("XML files (*.xml)") << tr("Text files (*.txt)"); else filters << tr("Text files (*.txt)") << tr("XML files (*.xml)"); break; case JSON: filters << tr("JSON files (*.json)"); break; case SVG: filters << tr("SVG files (*.svg)"); break; case Null: return; } if (dataSource == HexBuffer) filters << tr("Hex dump files (*.txt)"); filters << tr("All files (*)"); QString selectedFilter = filters.first(); QString fileName = FileDialog::getSaveFileName( CreateDataFile, this, tr("Choose a filename to export data"), filters.join(";;"), /* defaultFileName */ QString(), &selectedFilter); if(fileName.size() > 0) { QFile file(fileName); if(file.open(QIODevice::WriteOnly)) { switch (dataSource) { case HexBuffer: // Data source is the hex buffer // If text option has been selected, the readable representation of the content is saved to file. if (selectedFilter == tr("Hex dump files (*.txt)")) file.write(hexEdit->toReadableString().toUtf8()); else file.write(hexEdit->data()); break; case TextBuffer: // Data source is the text buffer file.write(ui->editorText->toPlainText().toUtf8()); break; case SciBuffer: // Data source is the Scintilla buffer file.write(sciEdit->text().toUtf8()); break; } file.close(); } } }
void QgsComposerPicture::loadPicture( const QFile& file ) { if ( !file.exists() || ( mUseSourceExpression && mPictureExpr->hasEvalError() ) ) { mMode = Unknown; } else { QFileInfo sourceFileInfo( file ); QString sourceFileSuffix = sourceFileInfo.suffix(); if ( sourceFileSuffix.compare( "svg", Qt::CaseInsensitive ) == 0 ) { //try to open svg mSVG.load( file.fileName() ); if ( mSVG.isValid() ) { mMode = SVG; QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size mDefaultSvgSize.setWidth( viewBox.width() ); mDefaultSvgSize.setHeight( viewBox.height() ); } else { mMode = Unknown; } } else { //try to open raster with QImageReader QImageReader imageReader( file.fileName() ); if ( imageReader.read( &mImage ) ) { mMode = RASTER; } else { mMode = Unknown; } } } if ( mMode != Unknown ) //make sure we start with a new QImage { recalculateSize(); } else if ( !( file.fileName().isEmpty() ) || ( mUseSourceExpression && mPictureExpr && mPictureExpr->hasEvalError() ) ) { //trying to load an invalid file or bad expression, show cross picture mMode = SVG; QString badFile = QString( ":/images/composer/missing_image.svg" ); mSVG.load( badFile ); if ( mSVG.isValid() ) { mMode = SVG; QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size mDefaultSvgSize.setWidth( viewBox.width() ); mDefaultSvgSize.setHeight( viewBox.height() ); recalculateSize(); } } emit itemChanged(); }
bool PictureShared::identifyAndLoad(const QByteArray& _array) { if (_array.size() < 5) { kError(30508) << "Picture is less than 5 bytes long!" << endl; return false; } QByteArray array = _array; QString strExtension; bool flag = false; // Try to find the file type by comparing magic on the first few bytes! // ### TODO: could not QImageIO::imageFormat do it too? (At least most of them?) if ((array[0] == char(0x89)) && (array[1] == 'P') && (array[2] == 'N') && (array[3] == 'G')) { strExtension = "png"; } else if ((array[0] == char(0xff)) && (array[1] == char(0xd8)) && (array[2] == char(0xff)) && (array[3] == char(0xe0))) { strExtension = "jpeg"; } else if ((array[0] == 'B') && (array[1] == 'M')) { strExtension = "bmp"; } else if ((array[0] == '<') && (array[1] == '?') && (array[2] == 'x') && (array[3] == 'm') && (array[4] == 'l')) { strExtension = "svg"; } else if ((array[0] == 'Q') && (array[1] == 'P') && (array[2] == 'I') && (array[3] == 'C')) { strExtension = "qpic"; } else if ((array[0] == '%') && (array[1] == '!') && (array[2] == 'P') && (array[3] == 'S')) { strExtension = "eps"; } else if ((array[0] == char(0xc5)) && (array[1] == char(0xd0)) && (array[2] == char(0xd3)) && (array[3] == char(0xc6))) { // So called "MS-DOS EPS file" strExtension = "eps"; } else if ((array[0] == 'G') && (array[1] == 'I') && (array[2] == 'F') && (array[3] == '8')) { // GIF (87a or 89a) strExtension = "gif"; } else if ((array[0] == char(0037)) && (array[1] == char(0213))) { // Gzip QBuffer buffer(&array); buffer.open(QIODevice::ReadOnly); const bool flag = loadCompressed(&buffer, "application/x-gzip", "tmp"); buffer.close(); return flag; } else if ((array[0] == 'B') && (array[1] == 'Z') && (array[2] == 'h')) { // BZip2 QBuffer buffer(&array); buffer.open(QIODevice::ReadOnly); const bool flag = loadCompressed(&buffer, "application/x-bzip", "tmp"); buffer.close(); return flag; } else { kDebug(30508) << "Cannot identify the type of temp file!" << " Trying to convert to PNG! (in PictureShared::loadTmp" << endl; // Do not trust QBuffer and do not work directly on the QByteArray array // DF: It would be faster to work on array here, and to create a completely // different QBuffer for the writing code! QBuffer buf(&array); if (!buf.open(QIODevice::ReadOnly)) { kError(30508) << "Could not open read buffer!" << endl; return false; } QImageReader imageReader(&buf); QImage image = imageReader.read(); if (image.isNull()) { kError(30508) << "Could not read image!" << endl; return false; } buf.close(); if (!buf.open(QIODevice::WriteOnly | QIODevice::Truncate)) { kError(30508) << "Could not open write buffer!" << endl; return false; } QImageWriter imageWriter(&buf, "PNG"); if (!imageWriter.write(image)) { kError(30508) << "Could not write converted image!" << endl; return false; } buf.close(); array = buf.buffer(); strExtension = "png"; } kDebug(30508) << "Temp file considered to be" << strExtension; clearAndSetMode(strExtension); if (m_base) flag = m_base->loadData(array, strExtension); setExtension(strExtension); return flag; }
void QDeclarativeGeoMapPixmapObject::load() { // need to deal with absolute / relative local / remote files QUrl url = QDeclarativeEngine::contextForObject(this)->resolvedUrl(m_source); QString path; if (url.scheme().compare(QLatin1String("qrc"), Qt::CaseInsensitive) == 0) { if (url.authority().isEmpty()) path = QLatin1Char(':') + url.path(); } else if (url.scheme().compare(QLatin1String("file"), Qt::CaseInsensitive) == 0) { path = url.toLocalFile(); } if (!path.isEmpty()) { QFile f(path); if (f.open(QIODevice::ReadOnly)) { QImage image; QImageReader imageReader(&f); if (imageReader.read(&image)) { setPixmap(QPixmap::fromImage(image)); setStatus(QDeclarativeGeoMapPixmapObject::Ready); } else { setPixmap(QPixmap()); setStatus(QDeclarativeGeoMapPixmapObject::Error); //qWarning() << "image read fail"; } } else { setPixmap(QPixmap()); setStatus(QDeclarativeGeoMapPixmapObject::Error); //qWarning() << "file open fail"; } } else { if (m_reply) { m_reply->abort(); m_reply->deleteLater(); m_reply = 0; } QDeclarativeEngine *engine = QDeclarativeEngine::contextForObject(this)->engine(); if (engine) { QNetworkAccessManager *nam = engine->networkAccessManager(); m_reply = nam->get(QNetworkRequest(url)); if (m_reply->isFinished()) { if (m_reply->error() == QNetworkReply::NoError) { finished(); } else { error(m_reply->error()); } delete m_reply; m_reply = 0; return; } setStatus(QDeclarativeGeoMapPixmapObject::Loading); connect(m_reply, SIGNAL(finished()), this, SLOT(finished())); connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); } else { setPixmap(QPixmap()); setStatus(QDeclarativeGeoMapPixmapObject::Error); //qWarning() << "null engine fail"; } } }
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); }
int readEmf(CustomItem* item) { item->setProcessing(EProcessingState::eProcessing); QImage image; int image_width = 0; int image_height = 0; do { FnConvertFPage2Bitmap* pfnConvertFPage2Bitmap = NULL; //Check handle. if (NULL == hXPSConvert) { break; } //Get ConvertFPage2Bitmap() pointer. pfnConvertFPage2Bitmap = (FnConvertFPage2Bitmap*)GetProcAddress(hXPSConvert, "ConvertFPage2Bitmap"); //Validate function pointer. if (NULL == pfnConvertFPage2Bitmap) { break; } //Path the image to be stored QString strImagePath = strExtractedFolder + QString("Image%1.png").arg(item->itemNo()); //Convert UNICODE to ASCII string QByteArray bImagePath = strImagePath.toLocal8Bit(); CONST CHAR* chImagePath = bImagePath.data(); QString strPage = item->imagePath(); //Replace all '/' with '\' strPage.replace("/", "\\"); //Remove any preceeding '\'. if (true == strPage.startsWith("\\")) { strPage.remove(0, 1); } //Fixed page path. QString strPagePath = strExtractedFolder + strPage; //Convert UNICODE to ASCII string QByteArray bPagePath = strPagePath.toLocal8Bit(); CONST CHAR* chFixedPagePath = bPagePath.data(); //Job Container path QByteArray bJobFolder = strExtractedFolder.toLocal8Bit(); CONST CHAR* chJobFolder = bJobFolder.data(); //Convert Fixed page to bitmap if (false == pfnConvertFPage2Bitmap(chJobFolder, chFixedPagePath, chImagePath, 96, 96)) { break; } QString strImageFile(chImagePath); //Load image. QImageReader imageReader(strImageFile); QSize size; int nMaxImageSze = 1000; image_width = nMaxImageSze; image_height = nMaxImageSze; if (imageReader.supportsOption(QImageIOHandler::Size)) { size = imageReader.size(); image_width = size.width(); image_height = size.height(); } double ratio = (double)image_width / (double)image_height; if (image_width <= image_height) { image_height = nMaxImageSze; image_width = ratio * image_height; } else { image_width = nMaxImageSze; image_height = image_width / ratio; } imageReader.setScaledSize(QSize(image_width, image_height)); image = imageReader.read(); } while (0); if (image.isNull()) { QImage imageIcon(QLatin1String("Image.png")); image = imageIcon; image = image.scaled(image_width, image_height, Qt::KeepAspectRatio, Qt::SmoothTransformation); } item->setPixmap(QPixmap::fromImage(image)); item->setProcessing(EProcessingState::eProcessed); return 0; }
/** * \brief Load the image(s), wraps LoadImage() */ bool MythUIImage::Load(bool allowLoadInBackground, bool forceStat) { d->m_UpdateLock.lockForRead(); QSize bForceSize = m_ForceSize; QString bFilename = m_Filename; bFilename.detach(); d->m_UpdateLock.unlock(); QString filename = bFilename; if (bFilename.isEmpty()) { Clear(); SetRedraw(); return false; } Clear(); // SetRedraw(); // if (!IsVisible(true)) // return false; int w = -1; int h = -1; if (!bForceSize.isNull()) { if (bForceSize.width() != -1) w = bForceSize.width(); if (bForceSize.height() != -1) h = bForceSize.height(); } QString imagelabel; int j = 0; for (int i = m_LowNum; i <= m_HighNum && !m_animatedImage; i++) { if (!m_animatedImage && m_HighNum != m_LowNum && bFilename.contains("%1")) filename = bFilename.arg(i); imagelabel = GenImageLabel(filename, w, h); // Only load in the background if allowed and the image is // not already in our mem cache ImageCacheMode cacheMode = kCacheCheckMemoryOnly; if (forceStat) cacheMode = (ImageCacheMode) ((int)kCacheCheckMemoryOnly | (int)kCacheForceStat); ImageCacheMode cacheMode2 = (!forceStat) ? kCacheNormal : (ImageCacheMode) ((int)kCacheNormal | (int)kCacheForceStat); if ((allowLoadInBackground) && (!GetMythUI()->LoadCacheImage(filename, imagelabel, GetPainter(), cacheMode)) && (!getenv("DISABLETHREADEDMYTHUIIMAGE"))) { VERBOSE(VB_GUI|VB_FILE|VB_EXTRA, LOC + QString( "Load(), spawning thread to load '%1'").arg(filename)); ImageLoadThread *bImgThread = new ImageLoadThread( this, bFilename, filename, i, bForceSize, cacheMode2); GetMythUI()->GetImageThreadPool()->start(bImgThread); } else { // Perform a blocking load VERBOSE(VB_GUI|VB_FILE|VB_EXTRA, LOC + QString( "Load(), loading '%1' in foreground").arg(filename)); QString tmpFilename; if ((filename.startsWith("/")) || (filename.startsWith("http://")) || (filename.startsWith("https://")) || (filename.startsWith("ftp://"))) tmpFilename = filename; MythImageReader imageReader(tmpFilename); if (imageReader.supportsAnimation()) { LoadAnimatedImage( imageReader, filename, bForceSize, cacheMode2); } else { MythImage *image = LoadImage( imageReader, filename, bForceSize, cacheMode2); if (image) { if (bForceSize.isNull()) SetSize(image->size()); m_ImagesLock.lock(); m_Images[j] = image; m_ImagesLock.unlock(); SetRedraw(); d->m_UpdateLock.lockForWrite(); m_LastDisplay = QTime::currentTime(); d->m_UpdateLock.unlock(); } else { m_ImagesLock.lock(); m_Images[j] = NULL; m_ImagesLock.unlock(); } } } ++j; } return true; }