source: trunk/src/gui/image/qimagereader.cpp@ 651

Last change on this file since 651 was 651, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.2 sources.

File size: 44.5 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtGui module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42//#define QIMAGEREADER_DEBUG
43
44/*!
45 \class QImageReader
46 \brief The QImageReader class provides a format independent interface
47 for reading images from files or other devices.
48
49 \reentrant
50 \ingroup painting
51 \ingroup io
52
53 The most common way to read images is through QImage and QPixmap's
54 constructors, or by calling QImage::load() and
55 QPixmap::load(). QImageReader is a specialized class which gives
56 you more control when reading images. For example, you can read an
57 image into a specific size by calling setScaledSize(), and you can
58 select a clip rect, effectively loading only parts of an image, by
59 calling setClipRect(). Depending on the underlying support in the
60 image format, this can save memory and speed up loading of images.
61
62 To read an image, you start by constructing a QImageReader object.
63 Pass either a file name or a device pointer, and the image format
64 to QImageReader's constructor. You can then set several options,
65 such as the clip rect (by calling setClipRect()) and scaled size
66 (by calling setScaledSize()). canRead() returns the image if the
67 QImageReader can read the image (i.e., the image format is
68 supported and the device is open for reading). Call read() to read
69 the image.
70
71 If any error occurs when reading the image, read() will return a
72 null QImage. You can then call error() to find the type of error
73 that occurred, or errorString() to get a human readable
74 description of what went wrong.
75
76 Call supportedImageFormats() for a list of formats that
77 QImageReader can read. QImageReader supports all built-in image
78 formats, in addition to any image format plugins that support
79 reading.
80
81 QImageReader autodetects the image format by default, by looking at the
82 provided (optional) format string, the file name suffix, and the data
83 stream contents. You can enable or disable this feature, by calling
84 setAutoDetectImageFormat().
85
86 \sa QImageWriter, QImageIOHandler, QImageIOPlugin
87*/
88
89/*!
90 \enum QImageReader::ImageReaderError
91
92 This enum describes the different types of errors that can occur
93 when reading images with QImageReader.
94
95 \value FileNotFoundError QImageReader was used with a file name,
96 but not file was found with that name. This can also happen if the
97 file name contained no extension, and the file with the correct
98 extension is not supported by Qt.
99
100 \value DeviceError QImageReader encountered a device error when
101 reading the image. You can consult your particular device for more
102 details on what went wrong.
103
104 \value UnsupportedFormatError Qt does not support the requested
105 image format.
106
107 \value InvalidDataError The image data was invalid, and
108 QImageReader was unable to read an image from it. The can happen
109 if the image file is damaged.
110
111 \value UnknownError An unknown error occurred. If you get this
112 value after calling read(), it is most likely caused by a bug in
113 QImageReader.
114*/
115#include "qimagereader.h"
116
117#include <qbytearray.h>
118#ifdef QIMAGEREADER_DEBUG
119#include <qdebug.h>
120#endif
121#include <qfile.h>
122#include <qfileinfo.h>
123#include <qimage.h>
124#include <qimageiohandler.h>
125#include <qlist.h>
126#include <qrect.h>
127#include <qset.h>
128#include <qsize.h>
129#include <qcolor.h>
130#include <qvariant.h>
131
132// factory loader
133#include <qcoreapplication.h>
134#include <private/qfactoryloader_p.h>
135
136// image handlers
137#include <private/qbmphandler_p.h>
138#include <private/qppmhandler_p.h>
139#include <private/qxbmhandler_p.h>
140#include <private/qxpmhandler_p.h>
141#ifndef QT_NO_IMAGEFORMAT_PNG
142#include <private/qpnghandler_p.h>
143#endif
144
145QT_BEGIN_NAMESPACE
146
147#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
148Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
149 (QImageIOHandlerFactoryInterface_iid, QLatin1String("/imageformats")))
150#endif
151
152enum _qt_BuiltInFormatType {
153#ifndef QT_NO_IMAGEFORMAT_PNG
154 _qt_PngFormat,
155#endif
156 _qt_BmpFormat,
157#ifndef QT_NO_IMAGEFORMAT_PPM
158 _qt_PpmFormat,
159 _qt_PgmFormat,
160 _qt_PbmFormat,
161#endif
162#ifndef QT_NO_IMAGEFORMAT_XBM
163 _qt_XbmFormat,
164#endif
165#ifndef QT_NO_IMAGEFORMAT_XPM
166 _qt_XpmFormat,
167#endif
168 _qt_NumFormats,
169 _qt_NoFormat = -1
170};
171
172struct _qt_BuiltInFormatStruct
173{
174 _qt_BuiltInFormatType type;
175 const char *extension;
176};
177
178static const _qt_BuiltInFormatStruct _qt_BuiltInFormats[] = {
179#ifndef QT_NO_IMAGEFORMAT_PNG
180 {_qt_PngFormat, "png"},
181#endif
182 {_qt_BmpFormat, "bmp"},
183#ifndef QT_NO_IMAGEFORMAT_PPM
184 {_qt_PpmFormat, "ppm"},
185 {_qt_PgmFormat, "pgm"},
186 {_qt_PbmFormat, "pbm"},
187#endif
188#ifndef QT_NO_IMAGEFORMAT_XBM
189 {_qt_XbmFormat, "xbm"},
190#endif
191#ifndef QT_NO_IMAGEFORMAT_XPM
192 {_qt_XpmFormat, "xpm"},
193#endif
194 {_qt_NoFormat, ""}
195};
196
197static QImageIOHandler *createReadHandlerHelper(QIODevice *device,
198 const QByteArray &format,
199 bool autoDetectImageFormat,
200 bool ignoresFormatAndExtension)
201{
202 if (!autoDetectImageFormat && format.isEmpty())
203 return 0;
204
205 QByteArray form = format.toLower();
206 QImageIOHandler *handler = 0;
207
208#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
209 // check if we have plugins that support the image format
210 QFactoryLoader *l = loader();
211 QStringList keys = l->keys();
212#endif
213 QByteArray suffix;
214
215#ifdef QIMAGEREADER_DEBUG
216 qDebug() << "QImageReader::createReadHandler( device =" << (void *)device << ", format =" << format << "),"
217 << keys.size() << "plugins available: " << keys;
218#endif
219
220#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
221 int suffixPluginIndex = -1;
222 if (device && format.isEmpty() && autoDetectImageFormat && !ignoresFormatAndExtension) {
223 // if there's no format, see if \a device is a file, and if so, find
224 // the file suffix and find support for that format among our plugins.
225 // this allows plugins to override our built-in handlers.
226 if (QFile *file = qobject_cast<QFile *>(device)) {
227#ifdef QIMAGEREADER_DEBUG
228 qDebug() << "QImageReader::createReadHandler: device is a file:" << file->fileName();
229#endif
230 if (!(suffix = QFileInfo(file->fileName()).suffix().toLower().toLatin1()).isEmpty()) {
231 int index = keys.indexOf(QString::fromLatin1(suffix));
232 if (index != -1) {
233#ifdef QIMAGEREADER_DEBUG
234 qDebug() << "QImageReader::createReadHandler: suffix recognized; the"
235 << suffix << "plugin might be able to read this";
236#endif
237 suffixPluginIndex = index;
238 }
239 }
240 }
241 }
242#endif // QT_NO_LIBRARY
243
244 QByteArray testFormat = !form.isEmpty() ? form : suffix;
245
246 if (ignoresFormatAndExtension)
247 testFormat = QByteArray();
248
249#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
250 if (suffixPluginIndex != -1) {
251 // check if the plugin that claims support for this format can load
252 // from this device with this format.
253 const qint64 pos = device ? device->pos() : 0;
254 QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(QString::fromLatin1(suffix)));
255 if (plugin && plugin->capabilities(device, testFormat) & QImageIOPlugin::CanRead) {
256 handler = plugin->create(device, testFormat);
257#ifdef QIMAGEREADER_DEBUG
258 qDebug() << "QImageReader::createReadHandler: using the" << suffix
259 << "plugin";
260#endif
261 }
262 if (device && !device->isSequential())
263 device->seek(pos);
264 }
265
266 if (!handler && !testFormat.isEmpty() && autoDetectImageFormat && !ignoresFormatAndExtension) {
267 // check if any plugin supports the format (they are not allowed to
268 // read from the device yet).
269 const qint64 pos = device ? device->pos() : 0;
270 for (int i = 0; i < keys.size(); ++i) {
271 if (i != suffixPluginIndex) {
272 QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(keys.at(i)));
273 if (plugin && plugin->capabilities(device, testFormat) & QImageIOPlugin::CanRead) {
274#ifdef QIMAGEREADER_DEBUG
275 qDebug() << "QImageReader::createReadHandler: the" << keys.at(i) << "plugin can read this format";
276#endif
277 handler = plugin->create(device, testFormat);
278 break;
279 }
280 }
281 }
282 if (device && !device->isSequential())
283 device->seek(pos);
284 }
285#endif // QT_NO_LIBRARY
286
287 // if we don't have a handler yet, check if we have built-in support for
288 // the format
289 if (!handler && !testFormat.isEmpty()) {
290 if (false) {
291#ifndef QT_NO_IMAGEFORMAT_PNG
292 } else if (testFormat == "png") {
293 handler = new QPngHandler;
294#endif
295#ifndef QT_NO_IMAGEFORMAT_BMP
296 } else if (testFormat == "bmp") {
297 handler = new QBmpHandler;
298#endif
299#ifndef QT_NO_IMAGEFORMAT_XPM
300 } else if (testFormat == "xpm") {
301 handler = new QXpmHandler;
302#endif
303#ifndef QT_NO_IMAGEFORMAT_XBM
304 } else if (testFormat == "xbm") {
305 handler = new QXbmHandler;
306 handler->setOption(QImageIOHandler::SubType, testFormat);
307#endif
308#ifndef QT_NO_IMAGEFORMAT_PPM
309 } else if (testFormat == "pbm" || testFormat == "pbmraw" || testFormat == "pgm"
310 || testFormat == "pgmraw" || testFormat == "ppm" || testFormat == "ppmraw") {
311 handler = new QPpmHandler;
312 handler->setOption(QImageIOHandler::SubType, testFormat);
313#endif
314 }
315
316#ifdef QIMAGEREADER_DEBUG
317 if (handler)
318 qDebug() << "QImageReader::createReadHandler: using the built-in handler for" << testFormat;
319#endif
320 }
321
322#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
323 if (!handler && (autoDetectImageFormat || ignoresFormatAndExtension)) {
324 // check if any of our plugins recognize the file from its contents.
325 const qint64 pos = device ? device->pos() : 0;
326 for (int i = 0; i < keys.size(); ++i) {
327 if (i != suffixPluginIndex) {
328 QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(keys.at(i)));
329 if (plugin && plugin->capabilities(device, QByteArray()) & QImageIOPlugin::CanRead) {
330 handler = plugin->create(device, testFormat);
331#ifdef QIMAGEREADER_DEBUG
332 qDebug() << "QImageReader::createReadHandler: the" << keys.at(i) << "plugin can read this data";
333#endif
334 break;
335 }
336 }
337 }
338 if (device && !device->isSequential())
339 device->seek(pos);
340 }
341#endif
342
343 if (!handler && (autoDetectImageFormat || ignoresFormatAndExtension)) {
344 // check if any of our built-in handlers recognize the file from its
345 // contents.
346 int currentFormat = 0;
347 if (!suffix.isEmpty()) {
348 // If reading from a file with a suffix, start testing our
349 // built-in handler for that suffix first.
350 for (int i = 0; i < _qt_NumFormats; ++i) {
351 if (_qt_BuiltInFormats[i].extension == suffix) {
352 currentFormat = i;
353 break;
354 }
355 }
356 }
357
358 QByteArray subType;
359 int numFormats = _qt_NumFormats;
360 while (device && numFormats >= 0) {
361 const _qt_BuiltInFormatStruct *formatStruct = &_qt_BuiltInFormats[currentFormat];
362
363 const qint64 pos = device->pos();
364 switch (formatStruct->type) {
365#ifndef QT_NO_IMAGEFORMAT_PNG
366 case _qt_PngFormat:
367 if (QPngHandler::canRead(device))
368 handler = new QPngHandler;
369 break;
370#endif
371#ifndef QT_NO_IMAGEFORMAT_BMP
372 case _qt_BmpFormat:
373 if (QBmpHandler::canRead(device))
374 handler = new QBmpHandler;
375 break;
376#endif
377#ifndef QT_NO_IMAGEFORMAT_XPM
378 case _qt_XpmFormat:
379 if (QXpmHandler::canRead(device))
380 handler = new QXpmHandler;
381 break;
382#endif
383#ifndef QT_NO_IMAGEFORMAT_PPM
384 case _qt_PbmFormat:
385 case _qt_PgmFormat:
386 case _qt_PpmFormat:
387 if (QPpmHandler::canRead(device, &subType)) {
388 handler = new QPpmHandler;
389 handler->setOption(QImageIOHandler::SubType, subType);
390 }
391 break;
392#endif
393#ifndef QT_NO_IMAGEFORMAT_XBM
394 case _qt_XbmFormat:
395 if (QXbmHandler::canRead(device))
396 handler = new QXbmHandler;
397 break;
398#endif
399 default:
400 break;
401 }
402 if (!device->isSequential())
403 device->seek(pos);
404
405 if (handler) {
406#ifdef QIMAGEREADER_DEBUG
407 qDebug() << "QImageReader::createReadHandler: the" << formatStruct->extension
408 << "built-in handler can read this data";
409#endif
410 break;
411 }
412
413 --numFormats;
414 ++currentFormat;
415 currentFormat %= _qt_NumFormats;
416 }
417 }
418
419 if (!handler) {
420#ifdef QIMAGEREADER_DEBUG
421 qDebug() << "QImageReader::createReadHandler: no handlers found. giving up.";
422#endif
423 // no handler: give up.
424 return 0;
425 }
426
427 handler->setDevice(device);
428 if (!form.isEmpty())
429 handler->setFormat(form);
430 return handler;
431}
432
433class QImageReaderPrivate
434{
435public:
436 QImageReaderPrivate(QImageReader *qq);
437 ~QImageReaderPrivate();
438
439 // device
440 QByteArray format;
441 bool autoDetectImageFormat;
442 bool ignoresFormatAndExtension;
443 QIODevice *device;
444 bool deleteDevice;
445 QImageIOHandler *handler;
446 bool initHandler();
447
448 // image options
449 QRect clipRect;
450 QSize scaledSize;
451 QRect scaledClipRect;
452 int quality;
453 QMap<QString, QString> text;
454 void getText();
455
456 // error
457 QImageReader::ImageReaderError imageReaderError;
458 QString errorString;
459
460 QImageReader *q;
461};
462
463/*!
464 \internal
465*/
466QImageReaderPrivate::QImageReaderPrivate(QImageReader *qq)
467 : autoDetectImageFormat(true), ignoresFormatAndExtension(false)
468{
469 device = 0;
470 deleteDevice = false;
471 handler = 0;
472 quality = -1;
473 imageReaderError = QImageReader::UnknownError;
474
475 q = qq;
476}
477
478/*!
479 \internal
480*/
481QImageReaderPrivate::~QImageReaderPrivate()
482{
483 if (deleteDevice)
484 delete device;
485 delete handler;
486}
487
488/*!
489 \internal
490*/
491bool QImageReaderPrivate::initHandler()
492{
493 // check some preconditions
494 if (!device || (!deleteDevice && !device->isOpen())) {
495 imageReaderError = QImageReader::DeviceError;
496 errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Invalid device"));
497 return false;
498 }
499
500 // probe the file extension
501 if (deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly) && autoDetectImageFormat) {
502 QList<QByteArray> extensions = QImageReader::supportedImageFormats();
503 if (!format.isEmpty()) {
504 // Try the most probable extension first
505 int currentFormatIndex = extensions.indexOf(format.toLower());
506 if (currentFormatIndex > 0)
507 extensions.swap(0, currentFormatIndex);
508 }
509
510 int currentExtension = 0;
511
512 QFile *file = static_cast<QFile *>(device);
513 QString fileName = file->fileName();
514
515 do {
516 file->setFileName(fileName + QLatin1Char('.')
517 + QString::fromLatin1(extensions.at(currentExtension++).constData()));
518 file->open(QIODevice::ReadOnly);
519 } while (!file->isOpen() && currentExtension < extensions.size());
520
521 if (!device->isOpen()) {
522 imageReaderError = QImageReader::FileNotFoundError;
523 errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "File not found"));
524 file->setFileName(fileName); // restore the old file name
525 return false;
526 }
527 }
528
529 // assign a handler
530 if (!handler && (handler = createReadHandlerHelper(device, format, autoDetectImageFormat, ignoresFormatAndExtension)) == 0) {
531 imageReaderError = QImageReader::UnsupportedFormatError;
532 errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Unsupported image format"));
533 return false;
534 }
535 return true;
536}
537
538/*!
539 \internal
540*/
541void QImageReaderPrivate::getText()
542{
543 if (!text.isEmpty() || (!handler && !initHandler()) || !handler->supportsOption(QImageIOHandler::Description))
544 return;
545 foreach (QString pair, handler->option(QImageIOHandler::Description).toString().split(
546 QLatin1String("\n\n"))) {
547 int index = pair.indexOf(QLatin1Char(':'));
548 if (index >= 0 && pair.indexOf(QLatin1Char(' ')) < index) {
549 text.insert(QLatin1String("Description"), pair.simplified());
550 } else {
551 QString key = pair.left(index);
552 text.insert(key, pair.mid(index + 2).simplified());
553 }
554 }
555}
556
557/*!
558 Constructs an empty QImageReader object. Before reading an image,
559 call setDevice() or setFileName().
560*/
561QImageReader::QImageReader()
562 : d(new QImageReaderPrivate(this))
563{
564}
565
566/*!
567 Constructs a QImageReader object with the device \a device and the
568 image format \a format.
569*/
570QImageReader::QImageReader(QIODevice *device, const QByteArray &format)
571 : d(new QImageReaderPrivate(this))
572{
573 d->device = device;
574 d->format = format;
575}
576
577/*!
578 Constructs a QImageReader object with the file name \a fileName
579 and the image format \a format.
580
581 \sa setFileName()
582*/
583QImageReader::QImageReader(const QString &fileName, const QByteArray &format)
584 : d(new QImageReaderPrivate(this))
585{
586 QFile *file = new QFile(fileName);
587 d->device = file;
588 d->deleteDevice = true;
589 d->format = format;
590}
591
592/*!
593 Destructs the QImageReader object.
594*/
595QImageReader::~QImageReader()
596{
597 delete d;
598}
599
600/*!
601 Sets the format QImageReader will use when reading images, to \a
602 format. \a format is a case insensitive text string. Example:
603
604 \snippet doc/src/snippets/code/src_gui_image_qimagereader.cpp 0
605
606 You can call supportedImageFormats() for the full list of formats
607 QImageReader supports.
608
609 \sa format()
610*/
611void QImageReader::setFormat(const QByteArray &format)
612{
613 d->format = format;
614}
615
616/*!
617 Returns the format QImageReader uses for reading images.
618
619 You can call this function after assigning a device to the
620 reader to determine the format of the device. For example:
621
622 \snippet doc/src/snippets/code/src_gui_image_qimagereader.cpp 1
623
624 If the reader cannot read any image from the device (e.g., there is no
625 image there, or the image has already been read), or if the format is
626 unsupported, this function returns an empty QByteArray().
627
628 \sa setFormat(), supportedImageFormats()
629*/
630QByteArray QImageReader::format() const
631{
632 if (d->format.isEmpty()) {
633 if (!d->initHandler())
634 return QByteArray();
635 return d->handler->canRead() ? d->handler->format() : QByteArray();
636 }
637
638 return d->format;
639}
640
641/*!
642 If \a enabled is true, image format autodetection is enabled; otherwise,
643 it is disabled. By default, autodetection is enabled.
644
645 QImageReader uses an extensive approach to detecting the image format;
646 firstly, if you pass a file name to QImageReader, it will attempt to
647 detect the file extension if the given file name does not point to an
648 existing file, by appending supported default extensions to the given file
649 name, one at a time. It then uses the following approach to detect the
650 image format:
651
652 \list
653
654 \o Image plugins are queried first, based on either the optional format
655 string, or the file name suffix (if the source device is a file). No
656 content detection is done at this stage. QImageReader will choose the
657 first plugin that supports reading for this format.
658
659 \o If no plugin supports the image format, Qt's built-in handlers are
660 checked based on either the optional format string, or the file name
661 suffix.
662
663 \o If no capable plugins or built-in handlers are found, each plugin is
664 tested by inspecting the content of the data stream.
665
666 \o If no plugins could detect the image format based on data contents,
667 each built-in image handler is tested by inspecting the contents.
668
669 \o Finally, if all above approaches fail, QImageReader will report failure
670 when trying to read the image.
671
672 \endlist
673
674 By disabling image format autodetection, QImageReader will only query the
675 plugins and built-in handlers based on the format string (i.e., no file
676 name extensions are tested).
677
678 \sa QImageIOHandler::canRead(), QImageIOPlugin::capabilities()
679*/
680void QImageReader::setAutoDetectImageFormat(bool enabled)
681{
682 d->autoDetectImageFormat = enabled;
683}
684
685/*!
686 Returns true if image format autodetection is enabled on this image
687 reader; otherwise returns false. By default, autodetection is enabled.
688
689 \sa setAutoDetectImageFormat()
690*/
691bool QImageReader::autoDetectImageFormat() const
692{
693 return d->autoDetectImageFormat;
694}
695
696
697/*!
698 If \a ignored is set to true, then the image reader will ignore
699 specified formats or file extensions and decide which plugin to
700 use only based on the contents in the datastream.
701
702 Setting this flag means that all image plugins gets loaded. Each
703 plugin will read the first bytes in the image data and decide if
704 the plugin is compatible or not.
705
706 This also disables auto detecting the image format.
707
708 \sa decideFormatFromContent()
709*/
710
711void QImageReader::setDecideFormatFromContent(bool ignored)
712{
713 d->ignoresFormatAndExtension = ignored;
714}
715
716
717/*!
718 Returns whether the image reader should decide which plugin to use
719 only based on the contents of the datastream rather than on the file
720 extension.
721
722 \sa setDecideFormatFromContent()
723*/
724
725bool QImageReader::decideFormatFromContent() const
726{
727 return d->ignoresFormatAndExtension;
728}
729
730
731/*!
732 Sets QImageReader's device to \a device. If a device has already
733 been set, the old device is removed from QImageReader and is
734 otherwise left unchanged.
735
736 If the device is not already open, QImageReader will attempt to
737 open the device in \l QIODevice::ReadOnly mode by calling
738 open(). Note that this does not work for certain devices, such as
739 QProcess, QTcpSocket and QUdpSocket, where more logic is required
740 to open the device.
741
742 \sa device(), setFileName()
743*/
744void QImageReader::setDevice(QIODevice *device)
745{
746 if (d->device && d->deleteDevice)
747 delete d->device;
748 d->device = device;
749 d->deleteDevice = false;
750 delete d->handler;
751 d->handler = 0;
752 d->text.clear();
753}
754
755/*!
756 Returns the device currently assigned to QImageReader, or 0 if no
757 device has been assigned.
758*/
759QIODevice *QImageReader::device() const
760{
761 return d->device;
762}
763
764/*!
765 Sets the file name of QImageReader to \a fileName. Internally,
766 QImageReader will create a QFile object and open it in \l
767 QIODevice::ReadOnly mode, and use this when reading images.
768
769 If \a fileName does not include a file extension (e.g., .png or .bmp),
770 QImageReader will cycle through all supported extensions until it finds
771 a matching file.
772
773 \sa fileName(), setDevice(), supportedImageFormats()
774*/
775void QImageReader::setFileName(const QString &fileName)
776{
777 setDevice(new QFile(fileName));
778 d->deleteDevice = true;
779}
780
781/*!
782 If the currently assigned device is a QFile, or if setFileName()
783 has been called, this function returns the name of the file
784 QImageReader reads from. Otherwise (i.e., if no device has been
785 assigned or the device is not a QFile), an empty QString is
786 returned.
787
788 \sa setFileName(), setDevice()
789*/
790QString QImageReader::fileName() const
791{
792 QFile *file = qobject_cast<QFile *>(d->device);
793 return file ? file->fileName() : QString();
794}
795
796/*!
797 \since 4.2
798
799 This is an image format specific function that sets the quality
800 level of the image to \a quality. For image formats that do not
801 support setting the quality, this value is ignored.
802
803 The value range of \a quality depends on the image format. For
804 example, the "jpeg" format supports a quality range from 0 (low
805 quality, high compression) to 100 (high quality, low compression).
806
807 \sa quality()
808*/
809void QImageReader::setQuality(int quality)
810{
811 d->quality = quality;
812}
813
814/*!
815 \since 4.2
816
817 Returns the quality level of the image.
818
819 \sa setQuality()
820*/
821int QImageReader::quality() const
822{
823 return d->quality;
824}
825
826
827/*!
828 Returns the size of the image, without actually reading the image
829 contents.
830
831 If the image format does not support this feature, this function returns
832 an invalid size. Qt's built-in image handlers all support this feature,
833 but custom image format plugins are not required to do so.
834
835 \sa QImageIOHandler::ImageOption, QImageIOHandler::option(), QImageIOHandler::supportsOption()
836*/
837QSize QImageReader::size() const
838{
839 if (!d->initHandler())
840 return QSize();
841
842 if (d->handler->supportsOption(QImageIOHandler::Size))
843 return d->handler->option(QImageIOHandler::Size).toSize();
844
845 return QSize();
846}
847
848/*!
849 \since 4.5
850
851 Returns the format of the image, without actually reading the image
852 contents. The format describes the image format \l QImageReader::read()
853 returns, not the format of the actual image.
854
855 If the image format does not support this feature, this function returns
856 an invalid format.
857
858 \sa QImageIOHandler::ImageOption, QImageIOHandler::option(), QImageIOHandler::supportsOption()
859*/
860QImage::Format QImageReader::imageFormat() const
861{
862 if (!d->initHandler())
863 return QImage::Format_Invalid;
864
865 if (d->handler->supportsOption(QImageIOHandler::ImageFormat))
866 return (QImage::Format)d->handler->option(QImageIOHandler::ImageFormat).toInt();
867
868 return QImage::Format_Invalid;
869}
870
871/*!
872 \since 4.1
873
874 Returns the text keys for this image. You can use
875 these keys with text() to list the image text for
876 a certain key.
877
878 Support for this option is implemented through
879 QImageIOHandler::Description.
880
881 \sa text(), QImageWriter::setText(), QImage::textKeys()
882*/
883QStringList QImageReader::textKeys() const
884{
885 d->getText();
886 return d->text.keys();
887}
888
889/*!
890 \since 4.1
891
892 Returns the image text associated with \a key.
893
894 Support for this option is implemented through
895 QImageIOHandler::Description.
896
897 \sa textKeys(), QImageWriter::setText()
898*/
899QString QImageReader::text(const QString &key) const
900{
901 d->getText();
902 return d->text.value(key);
903}
904
905/*!
906 Sets the image clip rect (also known as the ROI, or Region Of
907 Interest) to \a rect. The coordinates of \a rect are relative to
908 the untransformed image size, as returned by size().
909
910 \sa clipRect(), setScaledSize(), setScaledClipRect()
911*/
912void QImageReader::setClipRect(const QRect &rect)
913{
914 d->clipRect = rect;
915}
916
917/*!
918 Returns the clip rect (also known as the ROI, or Region Of
919 Interest) of the image. If no clip rect has been set, an invalid
920 QRect is returned.
921
922 \sa setClipRect()
923*/
924QRect QImageReader::clipRect() const
925{
926 return d->clipRect;
927}
928
929/*!
930 Sets the scaled size of the image to \a size. The scaling is
931 performed after the initial clip rect, but before the scaled clip
932 rect is applied. The algorithm used for scaling depends on the
933 image format. By default (i.e., if the image format does not
934 support scaling), QImageReader will use QImage::scale() with
935 Qt::SmoothScaling.
936
937 \sa scaledSize(), setClipRect(), setScaledClipRect()
938*/
939void QImageReader::setScaledSize(const QSize &size)
940{
941 d->scaledSize = size;
942}
943
944/*!
945 Returns the scaled size of the image.
946
947 \sa setScaledSize()
948*/
949QSize QImageReader::scaledSize() const
950{
951 return d->scaledSize;
952}
953
954/*!
955 Sets the scaled clip rect to \a rect. The scaled clip rect is the
956 clip rect (also known as ROI, or Region Of Interest) that is
957 applied after the image has been scaled.
958
959 \sa scaledClipRect(), setScaledSize()
960*/
961void QImageReader::setScaledClipRect(const QRect &rect)
962{
963 d->scaledClipRect = rect;
964}
965
966/*!
967 Returns the scaled clip rect of the image.
968
969 \sa setScaledClipRect()
970*/
971QRect QImageReader::scaledClipRect() const
972{
973 return d->scaledClipRect;
974}
975
976/*!
977 \since 4.1
978
979 Sets the background color to \a color.
980 Image formats that support this operation are expected to
981 initialize the background to \a color before reading an image.
982
983 \sa backgroundColor(), read()
984*/
985void QImageReader::setBackgroundColor(const QColor &color)
986{
987 if (!d->initHandler())
988 return;
989 if (d->handler->supportsOption(QImageIOHandler::BackgroundColor))
990 d->handler->setOption(QImageIOHandler::BackgroundColor, color);
991}
992
993/*!
994 \since 4.1
995
996 Returns the background color that's used when reading an image.
997 If the image format does not support setting the background color
998 an invalid color is returned.
999
1000 \sa setBackgroundColor(), read()
1001*/
1002QColor QImageReader::backgroundColor() const
1003{
1004 if (!d->initHandler())
1005 return QColor();
1006 if (d->handler->supportsOption(QImageIOHandler::BackgroundColor))
1007 return qVariantValue<QColor>(d->handler->option(QImageIOHandler::BackgroundColor));
1008 return QColor();
1009}
1010
1011/*!
1012 \since 4.1
1013
1014 Returns true if the image format supports animation;
1015 otherwise, false is returned.
1016
1017 \sa QMovie::supportedFormats()
1018*/
1019bool QImageReader::supportsAnimation() const
1020{
1021 if (!d->initHandler())
1022 return false;
1023 if (d->handler->supportsOption(QImageIOHandler::Animation))
1024 return d->handler->option(QImageIOHandler::Animation).toBool();
1025 return false;
1026}
1027
1028/*!
1029 Returns true if an image can be read for the device (i.e., the
1030 image format is supported, and the device seems to contain valid
1031 data); otherwise returns false.
1032
1033 canRead() is a lightweight function that only does a quick test to
1034 see if the image data is valid. read() may still return false
1035 after canRead() returns true, if the image data is corrupt.
1036
1037 For images that support animation, canRead() returns false when
1038 all frames have been read.
1039
1040 \sa read(), supportedImageFormats()
1041*/
1042bool QImageReader::canRead() const
1043{
1044 if (!d->initHandler())
1045 return false;
1046
1047 return d->handler->canRead();
1048}
1049
1050/*!
1051 Reads an image from the device. On success, the image that was
1052 read is returned; otherwise, a null QImage is returned. You can
1053 then call error() to find the type of error that occurred, or
1054 errorString() to get a human readable description of the error.
1055
1056 For image formats that support animation, calling read()
1057 repeatedly will return the next frame. When all frames have been
1058 read, a null image will be returned.
1059
1060 \sa canRead(), supportedImageFormats(), supportsAnimation(), QMovie
1061*/
1062QImage QImageReader::read()
1063{
1064 // Because failed image reading might have side effects, we explicitly
1065 // return a null image instead of the image we've just created.
1066 QImage image;
1067 return read(&image) ? image : QImage();
1068}
1069
1070/*!
1071 \overload
1072
1073 Reads an image from the device into \a image, which must point to a
1074 QImage. Returns true on success; otherwise, returns false.
1075
1076 If \a image has same format and size as the image data that is about to be
1077 read, this function may not need to allocate a new image before
1078 reading. Because of this, it can be faster than the other read() overload,
1079 which always constructs a new image; especially when reading several
1080 images with the same format and size.
1081
1082 \snippet doc/src/snippets/code/src_gui_image_qimagereader.cpp 2
1083
1084 For image formats that support animation, calling read() repeatedly will
1085 return the next frame. When all frames have been read, a null image will
1086 be returned.
1087
1088 \sa canRead(), supportedImageFormats(), supportsAnimation(), QMovie
1089*/
1090bool QImageReader::read(QImage *image)
1091{
1092 if (!image) {
1093 qWarning("QImageReader::read: cannot read into null pointer");
1094 return false;
1095 }
1096
1097 if (!d->handler && !d->initHandler())
1098 return false;
1099
1100 // set the handler specific options.
1101 if (d->handler->supportsOption(QImageIOHandler::ScaledSize) && d->scaledSize.isValid()) {
1102 if ((d->handler->supportsOption(QImageIOHandler::ClipRect) && !d->clipRect.isNull())
1103 || d->clipRect.isNull()) {
1104 // Only enable the ScaledSize option if there is no clip rect, or
1105 // if the handler also supports ClipRect.
1106 d->handler->setOption(QImageIOHandler::ScaledSize, d->scaledSize);
1107 }
1108 }
1109 if (d->handler->supportsOption(QImageIOHandler::ClipRect) && !d->clipRect.isNull())
1110 d->handler->setOption(QImageIOHandler::ClipRect, d->clipRect);
1111 if (d->handler->supportsOption(QImageIOHandler::ScaledClipRect) && !d->scaledClipRect.isNull())
1112 d->handler->setOption(QImageIOHandler::ScaledClipRect, d->scaledClipRect);
1113 if (d->handler->supportsOption(QImageIOHandler::Quality))
1114 d->handler->setOption(QImageIOHandler::Quality, d->quality);
1115
1116 // read the image
1117 if (!d->handler->read(image)) {
1118 d->imageReaderError = InvalidDataError;
1119 d->errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Unable to read image data"));
1120 return false;
1121 }
1122
1123 // provide default implementations for any unsupported image
1124 // options
1125 if (d->handler->supportsOption(QImageIOHandler::ClipRect) && !d->clipRect.isNull()) {
1126 if (d->handler->supportsOption(QImageIOHandler::ScaledSize) && d->scaledSize.isValid()) {
1127 if (d->handler->supportsOption(QImageIOHandler::ScaledClipRect) && !d->scaledClipRect.isNull()) {
1128 // all features are supported by the handler; nothing to do.
1129 } else {
1130 // the image is already scaled, so apply scaled clipping.
1131 if (!d->scaledClipRect.isNull())
1132 *image = image->copy(d->scaledClipRect);
1133 }
1134 } else {
1135 if (d->handler->supportsOption(QImageIOHandler::ScaledClipRect) && !d->scaledClipRect.isNull()) {
1136 // supports scaled clipping but not scaling, most
1137 // likely a broken handler.
1138 } else {
1139 if (d->scaledSize.isValid()) {
1140 *image = image->scaled(d->scaledSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
1141 }
1142 if (d->scaledClipRect.isValid()) {
1143 *image = image->copy(d->scaledClipRect);
1144 }
1145 }
1146 }
1147 } else {
1148 if (d->handler->supportsOption(QImageIOHandler::ScaledSize) && d->scaledSize.isValid()) {
1149 // in this case, there's nothing we can do. if the
1150 // plugin supports scaled size but not ClipRect, then
1151 // we have to ignore ClipRect."
1152
1153 if (d->handler->supportsOption(QImageIOHandler::ScaledClipRect) && !d->scaledClipRect.isNull()) {
1154 // nothing to do (ClipRect is ignored!)
1155 } else {
1156 // provide all workarounds.
1157 if (d->scaledClipRect.isValid()) {
1158 *image = image->copy(d->scaledClipRect);
1159 }
1160 }
1161 } else {
1162 if (d->handler->supportsOption(QImageIOHandler::ScaledClipRect) && !d->scaledClipRect.isNull()) {
1163 // this makes no sense; a handler that supports
1164 // ScaledClipRect but not ScaledSize is broken, and we
1165 // can't work around it.
1166 } else {
1167 // provide all workarounds.
1168 if (d->clipRect.isValid())
1169 *image = image->copy(d->clipRect);
1170 if (d->scaledSize.isValid())
1171 *image = image->scaled(d->scaledSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
1172 if (d->scaledClipRect.isValid())
1173 *image = image->copy(d->scaledClipRect);
1174 }
1175 }
1176 }
1177
1178 return true;
1179}
1180
1181/*!
1182 For image formats that support animation, this function steps over the
1183 current image, returning true if successful or false if there is no
1184 following image in the animation.
1185
1186 The default implementation calls read(), then discards the resulting
1187 image, but the image handler may have a more efficient way of implementing
1188 this operation.
1189
1190 \sa jumpToImage(), QImageIOHandler::jumpToNextImage()
1191*/
1192bool QImageReader::jumpToNextImage()
1193{
1194 if (!d->initHandler())
1195 return false;
1196 return d->handler->jumpToNextImage();
1197}
1198
1199/*!
1200 For image formats that support animation, this function skips to the image
1201 whose sequence number is \a imageNumber, returning true if successful
1202 or false if the corresponding image cannot be found.
1203
1204 The next call to read() will attempt to read this image.
1205
1206 \sa jumpToNextImage(), QImageIOHandler::jumpToImage()
1207*/
1208bool QImageReader::jumpToImage(int imageNumber)
1209{
1210 if (!d->initHandler())
1211 return false;
1212 return d->handler->jumpToImage(imageNumber);
1213}
1214
1215/*!
1216 For image formats that support animation, this function returns the number
1217 of times the animation should loop. If this function returns -1, it can
1218 either mean the animation should loop forever, or that an error occurred.
1219 If an error occurred, canRead() will return false.
1220
1221 \sa supportsAnimation(), QImageIOHandler::loopCount(), canRead()
1222*/
1223int QImageReader::loopCount() const
1224{
1225 if (!d->initHandler())
1226 return -1;
1227 return d->handler->loopCount();
1228}
1229
1230/*!
1231 For image formats that support animation, this function returns the total
1232 number of images in the animation. If the format does not support
1233 animation, 0 is returned.
1234
1235 This function returns -1 if an error occurred.
1236
1237 \sa supportsAnimation(), QImageIOHandler::imageCount(), canRead()
1238*/
1239int QImageReader::imageCount() const
1240{
1241 if (!d->initHandler())
1242 return -1;
1243 return d->handler->imageCount();
1244}
1245
1246/*!
1247 For image formats that support animation, this function returns the number
1248 of milliseconds to wait until displaying the next frame in the animation.
1249 If the image format doesn't support animation, 0 is returned.
1250
1251 This function returns -1 if an error occurred.
1252
1253 \sa supportsAnimation(), QImageIOHandler::nextImageDelay(), canRead()
1254*/
1255int QImageReader::nextImageDelay() const
1256{
1257 if (!d->initHandler())
1258 return -1;
1259 return d->handler->nextImageDelay();
1260}
1261
1262/*!
1263 For image formats that support animation, this function returns the
1264 sequence number of the current frame. If the image format doesn't support
1265 animation, 0 is returned.
1266
1267 This function returns -1 if an error occurred.
1268
1269 \sa supportsAnimation(), QImageIOHandler::currentImageNumber(), canRead()
1270*/
1271int QImageReader::currentImageNumber() const
1272{
1273 if (!d->initHandler())
1274 return -1;
1275 return d->handler->currentImageNumber();
1276}
1277
1278/*!
1279 For image formats that support animation, this function returns
1280 the rect for the current frame. Otherwise, a null rect is returned.
1281
1282 \sa supportsAnimation(), QImageIOHandler::currentImageRect()
1283*/
1284QRect QImageReader::currentImageRect() const
1285{
1286 if (!d->initHandler())
1287 return QRect();
1288 return d->handler->currentImageRect();
1289}
1290
1291/*!
1292 Returns the type of error that occurred last.
1293
1294 \sa ImageReaderError, errorString()
1295*/
1296QImageReader::ImageReaderError QImageReader::error() const
1297{
1298 return d->imageReaderError;
1299}
1300
1301/*!
1302 Returns a human readable description of the last error that
1303 occurred.
1304
1305 \sa error()
1306*/
1307QString QImageReader::errorString() const
1308{
1309 if (d->errorString.isEmpty())
1310 return QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Unknown error"));
1311 return d->errorString;
1312}
1313
1314/*!
1315 \since 4.2
1316
1317 Returns true if the reader supports \a option; otherwise returns
1318 false.
1319
1320 Different image formats support different options. Call this function to
1321 determine whether a certain option is supported by the current format. For
1322 example, the PNG format allows you to embed text into the image's metadata
1323 (see text()), and the BMP format allows you to determine the image's size
1324 without loading the whole image into memory (see size()).
1325
1326 \snippet doc/src/snippets/code/src_gui_image_qimagereader.cpp 3
1327
1328 \sa QImageWriter::supportsOption()
1329*/
1330bool QImageReader::supportsOption(QImageIOHandler::ImageOption option) const
1331{
1332 if (!d->initHandler())
1333 return false;
1334 return d->handler->supportsOption(option);
1335}
1336
1337/*!
1338 If supported, this function returns the image format of the file
1339 \a fileName. Otherwise, an empty string is returned.
1340*/
1341QByteArray QImageReader::imageFormat(const QString &fileName)
1342{
1343 QFile file(fileName);
1344 if (!file.open(QFile::ReadOnly))
1345 return QByteArray();
1346
1347 return imageFormat(&file);
1348}
1349
1350/*!
1351 If supported, this function returns the image format of the device
1352 \a device. Otherwise, an empty string is returned.
1353
1354 \sa QImageReader::autoDetectImageFormat()
1355*/
1356QByteArray QImageReader::imageFormat(QIODevice *device)
1357{
1358 QByteArray format;
1359 QImageIOHandler *handler = createReadHandlerHelper(device, format, /* autoDetectImageFormat = */ true, false);
1360 if (handler) {
1361 if (handler->canRead())
1362 format = handler->format();
1363 delete handler;
1364 }
1365 return format;
1366}
1367
1368/*!
1369 Returns the list of image formats supported by QImageReader.
1370
1371 By default, Qt can read the following formats:
1372
1373 \table
1374 \header \o Format \o Description
1375 \row \o BMP \o Windows Bitmap
1376 \row \o GIF \o Graphic Interchange Format (optional)
1377 \row \o JPG \o Joint Photographic Experts Group
1378 \row \o JPEG \o Joint Photographic Experts Group
1379 \row \o MNG \o Multiple-image Network Graphics
1380 \row \o PNG \o Portable Network Graphics
1381 \row \o PBM \o Portable Bitmap
1382 \row \o PGM \o Portable Graymap
1383 \row \o PPM \o Portable Pixmap
1384 \row \o TIFF \o Tagged Image File Format
1385 \row \o XBM \o X11 Bitmap
1386 \row \o XPM \o X11 Pixmap
1387 \row \o SVG \o Scalable Vector Graphics
1388 \endtable
1389
1390 Reading and writing SVG files is supported through Qt's
1391 \l{QtSvg Module}{SVG Module}.
1392
1393 To configure Qt with GIF support, pass \c -qt-gif to the \c
1394 configure script or check the appropriate option in the graphical
1395 installer.
1396
1397 \sa setFormat(), QImageWriter::supportedImageFormats(), QImageIOPlugin
1398*/
1399QList<QByteArray> QImageReader::supportedImageFormats()
1400{
1401 QSet<QByteArray> formats;
1402 for (int i = 0; i < _qt_NumFormats; ++i)
1403 formats << _qt_BuiltInFormats[i].extension;
1404
1405#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
1406 QFactoryLoader *l = loader();
1407 QStringList keys = l->keys();
1408
1409 for (int i = 0; i < keys.count(); ++i) {
1410 QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(keys.at(i)));
1411 if (plugin && plugin->capabilities(0, keys.at(i).toLatin1()) & QImageIOPlugin::CanRead)
1412 formats << keys.at(i).toLatin1();
1413 }
1414#endif // QT_NO_LIBRARY
1415
1416 QList<QByteArray> sortedFormats;
1417 for (QSet<QByteArray>::ConstIterator it = formats.constBegin(); it != formats.constEnd(); ++it)
1418 sortedFormats << *it;
1419
1420 qSort(sortedFormats);
1421 return sortedFormats;
1422}
1423
1424QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.