📄 qimagereader.cpp
字号:
/******************************************************************************** Copyright (C) 1992-2006 Trolltech ASA. All rights reserved.**** This file is part of the QtGui module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file. Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://www.trolltech.com/products/qt/opensource.html**** If you are unsure which license is appropriate for your use, please** review the following information:** http://www.trolltech.com/products/qt/licensing.html or contact the** sales department at sales@trolltech.com.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************//*! \class QImageReader \brief The QImageReader class provides a format independent interface for reading images from files or other devices. \reentrant \ingroup multimedia \ingroup io The most common way to read images is through QImage and QPixmap's constructors, or by calling QImage::load() and QPixmap::load(). QImageReader is a specialized class which gives you more control when reading images. For example, you can read an image into a specific size by calling setScaledSize(), and you can select a clip rect, effectively loading only parts of an image, by calling setClipRect(). Depending on the underlying support in the image format, this can save memory and speed up loading of images. To read an image, you start by constructing a QImageReader object. Pass either a file name or a device pointer, and the image format to QImageReader's constructor. You can then set several options, such as the clip rect (by calling setClipRect()) and scaled size (by calling setScaledSize()). canRead() returns the image if the QImageReader can read the image (i.e., the image format is supported and the device is open for reading). Call read() to read the image. If any error occurs when reading the image, read() will return a null QImage. You can then call error() to find the type of error that occurred, or errorString() to get a human readable description of what went wrong. Call supportedImageFormats() for a list of formats that QImageReader can read. QImageReader supports all built-in image formats, in addition to any image format plugins that support reading. \legalese Qt supports GIF reading if it is configured that way during installation. If it is, we are required to state that "The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated." \warning If you are in a country that recognizes software patents and in which Unisys holds a patent on LZW compression and/or decompression and you want to use GIF, Unisys may require you to license that technology. Such countries include Canada, Japan, the US, France, Germany, Italy and the UK. GIF support may be removed completely in a future version of Qt. We recommend using the MNG or PNG format. \sa QImageWriter, QImageIOHandler, QImageIOPlugin*//*! \enum QImageReader::ImageReaderError This enum describes the different types of errors that can occur when reading images with QImageReader. \value FileNotFoundError QImageReader was used with a file name, but not file was found with that name. This can also happen if the file name contained no extension, and the file with the correct extension is not supported by Qt. \value DeviceError QImageReader encountered a device error when reading the image. You can consult your particular device for more details on what went wrong. \value UnsupportedFormatError Qt does not support the requested image format. \value InvalidDataError The image data was invalid, and QImageReader was unable to read an image from it. The can happen if the image file is damaged. \value UnknownError An unknown error occurred. If you get this value after calling read(), it is most likely caused by a bug in QImageReader.*/#include "qimagereader.h"#include <qbytearray.h>#include <qdebug.h>#include <qfile.h>#include <qimage.h>#include <qimageiohandler.h>#include <qlist.h>#include <qrect.h>#include <qset.h>#include <qsize.h>#include <qcolor.h>#include <qvariant.h>// factory loader#include <qcoreapplication.h>#include <private/qfactoryloader_p.h>// image handlers#include <private/qbmphandler_p.h>#include <private/qppmhandler_p.h>#include <private/qxbmhandler_p.h>#include <private/qxpmhandler_p.h>#ifndef QT_NO_IMAGEFORMAT_PNG#include <private/qpnghandler_p.h>#endif#ifndef QT_NO_LIBRARYQ_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QImageIOHandlerFactoryInterface_iid, QCoreApplication::libraryPaths(), QLatin1String("/imageformats")))#endif static QImageIOHandler *createReadHandler(QIODevice *device, const QByteArray &format){ QByteArray form = format.toLower(); QImageIOHandler *handler = 0;#ifndef QT_NO_LIBRARY // check if we have plugins that support the image format QFactoryLoader *l = loader(); QStringList keys = l->keys(); const qint64 pos = device->pos(); for (int i = 0; i < keys.count(); ++i) { QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(keys.at(i))); if (plugin && plugin->capabilities(device, form) & QImageIOPlugin::CanRead) { handler = plugin->create(device, form); break; } device->seek(pos); }#endif // QT_NO_LIBRARY // check if we have built-in support for the format name if (!format.isEmpty()) { if (false) { #ifndef QT_NO_IMAGEFORMAT_PNG } else if (form == "png") { handler = new QPngHandler;#endif#ifndef QT_NO_IMAGEFORMAT_BMP } else if (form == "bmp") { handler = new QBmpHandler;#endif#ifndef QT_NO_IMAGEFORMAT_XPM } else if (form == "xpm") { handler = new QXpmHandler;#endif#ifndef QT_NO_IMAGEFORMAT_XBM } else if (form == "xbm") { handler = new QXbmHandler; handler->setOption(QImageIOHandler::SubType, form);#endif#ifndef QT_NO_IMAGEFORMAT_PPM } else if (form == "pbm" || form == "pbmraw" || form == "pgm" || form == "pgmraw" || form == "ppm" || form == "ppmraw") { handler = new QPpmHandler; handler->setOption(QImageIOHandler::SubType, form);#endif } } // check if any of our built-in formats can read images from the device if (!handler) { QByteArray subType; if (false) { #ifndef QT_NO_IMAGEFORMAT_PNG } else if (QPngHandler::canRead(device)) { handler = new QPngHandler;#endif#ifndef QT_NO_IMAGEFORMAT_BMP } else if (QBmpHandler::canRead(device)) { handler = new QBmpHandler;#endif#ifndef QT_NO_IMAGEFORMAT_XPM } else if (QXpmHandler::canRead(device)) { handler = new QXpmHandler;#endif#ifndef QT_NO_IMAGEFORMAT_PPM } else if (QPpmHandler::canRead(device, &subType)) { handler = new QPpmHandler; handler->setOption(QImageIOHandler::SubType, subType);#endif#ifndef QT_NO_IMAGEFORMAT_XBM } else if (QXbmHandler::canRead(device)) { handler = new QXbmHandler;#endif } } if (!handler) return 0; handler->setDevice(device); handler->setFormat(format); return handler;}class QImageReaderPrivate{public: QImageReaderPrivate(QImageReader *qq); ~QImageReaderPrivate(); // device QByteArray format; QIODevice *device; bool deleteDevice; QImageIOHandler *handler; bool initHandler(); // image options QRect clipRect; QSize scaledSize; QRect scaledClipRect; QMap<QString, QString> text; void getText(); // error QImageReader::ImageReaderError imageReaderError; QString errorString; QImageReader *q;};/*! \internal*/QImageReaderPrivate::QImageReaderPrivate(QImageReader *qq){ device = 0; deleteDevice = false; handler = 0; imageReaderError = QImageReader::UnknownError; errorString = QT_TRANSLATE_NOOP(QImageReader, "Unknown error"); q = qq;}/*! \internal*/QImageReaderPrivate::~QImageReaderPrivate(){ if (deleteDevice) delete device; delete handler;}/*! \internal*/bool QImageReaderPrivate::initHandler(){ // check some preconditions if (!device || (!deleteDevice && !device->isOpen())) { imageReaderError = QImageReader::DeviceError; errorString = QT_TRANSLATE_NOOP(QImageReader, "Invalid device"); return false; } // probe the file extension if (deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly)) { QList<QByteArray> extensions = QImageReader::supportedImageFormats(); int currentExtension = 0; QFile *file = static_cast<QFile *>(device); QString fileName = file->fileName(); do { file->setFileName(fileName + QLatin1Char('.') + extensions.at(currentExtension++)); file->open(QIODevice::ReadOnly); } while (!file->isOpen() && currentExtension < extensions.size()); if (!device->isOpen()) { imageReaderError = QImageReader::FileNotFoundError; errorString = QT_TRANSLATE_NOOP(QImageReader, "File not found"); return false; } }#ifndef QT_NO_LIBRARY // assign a handler if (!handler && (handler = ::createReadHandler(device, format)) == 0) { imageReaderError = QImageReader::UnsupportedFormatError; errorString = QT_TRANSLATE_NOOP(QImageReader, "Unsupported image format"); return false; }#endif return true;}/*! \internal*/void QImageReaderPrivate::getText(){ if (!text.isEmpty() || (!handler && !initHandler()) || !handler->supportsOption(QImageIOHandler::Description)) return; foreach (QString pair, handler->option(QImageIOHandler::Description).toString().split("\n\n")) { int index = pair.indexOf(":"); if (index >= 0 && pair.indexOf(" ") < index) { text.insert("Description", pair.simplified()); } else { QString key = pair.left(index); text.insert(key, pair.mid(index + 2).simplified()); } }}/*! Constructs an empty QImageReader object. Before reading an image, call setDevice() or setFileName().*/QImageReader::QImageReader() : d(new QImageReaderPrivate(this)){}/*! Constructs a QImageReader object with the device \a device and the image format \a format.*/QImageReader::QImageReader(QIODevice *device, const QByteArray &format) : d(new QImageReaderPrivate(this)){ d->device = device; d->format = format;}/*! Constructs a QImageReader object with the file name \a fileName and the image format \a format. \sa setFileName()*/QImageReader::QImageReader(const QString &fileName, const QByteArray &format) : d(new QImageReaderPrivate(this)){ QFile *file = new QFile(fileName); d->device = file; d->deleteDevice = true; d->format = format;}/*! Destructs the QImageReader object.*/QImageReader::~QImageReader(){ delete d;}/*! Sets the format QImageReader will use when reading images, to \a format. \a format is a case insensitive text string. Example: \code QImageReader reader; reader.setFormat("png"); // same as reader.setFormat("PNG"); \endcode You can call supportedImageFormats() for the full list of formats QImageReader supports. \sa format()*/void QImageReader::setFormat(const QByteArray &format){ d->format = format;}/*! Returns the format QImageReader uses for reading images. \sa setFormat()*/QByteArray QImageReader::format() const{ return d->format;}/*! Sets QImageReader's device to \a device. If a device has already been set, the old device is removed from QImageReader and is otherwise left unchanged. If the device is not already open, QImageReader will attempt to open the device in \l QIODevice::ReadOnly mode by calling open(). Note that this does not work for certain devices, such as QProcess, QTcpSocket and QUdpSocket, where more logic is required to open the device. \sa device(), setFileName()*/void QImageReader::setDevice(QIODevice *device){ if (d->device && d->deleteDevice) delete d->device; d->device = device; d->deleteDevice = false; delete d->handler; d->handler = 0; d->text.clear();}/*! Returns the device currently assigned to QImageReader, or 0 if no device has been assigned.*/QIODevice *QImageReader::device() const{ return d->device;}/*! Sets the file name of QImageReader to \a fileName. Internally, QImageReader will create a QFile object and open it in \l QIODevice::ReadOnly mode, and use this when reading images. If \a fileName does not include a file extension (e.g., .png or .bmp), QImageReader will cycle through all supported extensions until it finds a matching file. \sa fileName(), setDevice(), supportedImageFormats()*/void QImageReader::setFileName(const QString &fileName){ setDevice(new QFile(fileName)); d->deleteDevice = true;}/*! If the currently assigned device is a QFile, or if setFileName() has been called, this function returns the name of the file QImageReader reads from. Otherwise (i.e., if no device has been assigned or the device is not a QFile), an empty QString is returned. \sa setFileName(), setDevice()*/QString QImageReader::fileName() const{ QFile *file = qobject_cast<QFile *>(d->device); return file ? file->fileName() : QString();}/*! Returns the size of the image. This function may or may not read the entire image, depending on whether the image format supports checking the size of an image before loading it.*/QSize QImageReader::size() const{ if (!d->initHandler()) return QSize(); if (d->handler->supportsOption(QImageIOHandler::Size)) return d->handler->option(QImageIOHandler::Size).toSize(); QImage image; if (!d->handler->read(&image)) { // ### skips a frame in animations d->imageReaderError = InvalidDataError; d->errorString = QT_TRANSLATE_NOOP(QImageReader, "Unable to read image data"); return QSize(); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -