Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qimagereader.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5/*!
6 \class QImageReader
7 \brief The QImageReader class provides a format independent interface
8 for reading images from files or other devices.
9
10 \inmodule QtGui
11 \reentrant
12 \ingroup painting
13
14 The most common way to read images is through QImage and QPixmap's
15 constructors, or by calling QImage::load() and
16 QPixmap::load(). QImageReader is a specialized class which gives
17 you more control when reading images. For example, you can read an
18 image into a specific size by calling setScaledSize(), and you can
19 select a clip rect, effectively loading only parts of an image, by
20 calling setClipRect(). Depending on the underlying support in the
21 image format, this can save memory and speed up loading of images.
22
23 To read an image, you start by constructing a QImageReader object.
24 Pass either a file name or a device pointer, and the image format
25 to QImageReader's constructor. You can then set several options,
26 such as the clip rect (by calling setClipRect()) and scaled size
27 (by calling setScaledSize()). canRead() returns the image if the
28 QImageReader can read the image (i.e., the image format is
29 supported and the device is open for reading). Call read() to read
30 the image.
31
32 If any error occurs when reading the image, read() will return a
33 null QImage. You can then call error() to find the type of error
34 that occurred, or errorString() to get a human readable
35 description of what went wrong.
36
37 \note QImageReader assumes exclusive control over the file or
38 device that is assigned. Any attempts to modify the assigned file
39 or device during the lifetime of the QImageReader object will
40 yield undefined results.
41
42 \section1 Formats
43
44 Call supportedImageFormats() for a list of formats that
45 QImageReader can read. QImageReader supports all built-in image
46 formats, in addition to any image format plugins that support
47 reading. Call supportedMimeTypes() to obtain a list of supported MIME
48 types, which for example can be passed to QFileDialog::setMimeTypeFilters().
49
50 QImageReader autodetects the image format by default, by looking at the file name suffix (if
51 any) and the data stream contents. Using setFormat(), you can bypass the detection. You can
52 enable or disable autodetection altogether by calling setAutoDetectImageFormat().
53
54 \section1 Security Considerations
55
56 To restrict decoding of untrusted data to one format handler, specify it explicitly with the \a
57 format argument of QImage's loading methods, or with QImageReader and setFormat(). Reading then
58 fails if the data is not in the specified format, or if no handler for it is available.
59
60 Note that, in contrast to the \a format argument, the file name extension does \e not restrict
61 the choice of handler. The extension is only used as an optimization: the handler for that
62 format is queried first. If it rejects the file, the other available handlers are queried in
63 turn.
64
65 By default, then, any image format plugin found at runtime may be employed to decode image
66 data. In particular, image format plugins that claim support for a format take precedence over
67 any Qt built-in handler for it. Hence, choosing the set of image plugins that are deployed
68 influences an application's attack surface.
69
70 See also setAllocationLimit().
71
72 \section1 High Resolution Versions of Images
73
74 It is possible to provide high resolution versions of images should a scaling
75 between \e{device pixels} and \e{device independent pixels} be in effect.
76
77 The high resolution version is marked by the suffix \c @2x on the base name.
78 The image read will have its \e{device pixel ratio} set to a value of 2.
79
80 This can be disabled by setting the environment variable
81 \c QT_HIGHDPI_DISABLE_2X_IMAGE_LOADING.
82
83 \sa QImageWriter, QImageIOHandler, QImageIOPlugin, QMimeDatabase, QColorSpace
84 \sa QImage::devicePixelRatio(), QPixmap::devicePixelRatio(), QIcon, QPainter::drawPixmap(), QPainter::drawImage()
85*/
86
87/*!
88 \enum QImageReader::ImageReaderError
89
90 This enum describes the different types of errors that can occur
91 when reading images with QImageReader.
92
93 \value FileNotFoundError QImageReader was used with a file name,
94 but not file was found with that name. This can also happen if the
95 file name contained no extension, and the file with the correct
96 extension is not supported by Qt.
97
98 \value DeviceError QImageReader encountered a device error when
99 reading the image. You can consult your particular device for more
100 details on what went wrong.
101
102 \value UnsupportedFormatError Qt does not support the requested
103 image format.
104
105 \value InvalidDataError The image data was invalid, and
106 QImageReader was unable to read an image from it. The can happen
107 if the image file is damaged.
108
109 \value UnknownError An unknown error occurred. If you get this
110 value after calling read(), it is most likely caused by a bug in
111 QImageReader.
112*/
113#include "qimagereader.h"
114
115#include <qbytearray.h>
116#include <qdebug.h>
117#include <qfile.h>
118#include <qfileinfo.h>
119#include <qimage.h>
120#include <qimageiohandler.h>
121#include <qlist.h>
122#include <qrect.h>
123#include <qsize.h>
124#include <qcolor.h>
125#include <qvariant.h>
126#include <qloggingcategory.h>
127
128// factory loader
129#include <qcoreapplication.h>
130#include <private/qfactoryloader_p.h>
131#include <QtCore/private/qlocking_p.h>
132
133// for qt_getImageText
134#include <private/qimage_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
145#include <private/qimagereaderwriterhelpers_p.h>
146#include <qtgui_tracepoints_p.h>
147
148#include <algorithm>
149
150QT_BEGIN_NAMESPACE
151
152Q_STATIC_LOGGING_CATEGORY(lcImageReader, "qt.gui.imageio.reader")
153
154using namespace QImageReaderWriterHelpers;
155using namespace Qt::StringLiterals;
156
157Q_TRACE_POINT(qtgui, QImageReader_read_before_reading, QImageReader *reader, const QString &filename);
158Q_TRACE_POINT(qtgui, QImageReader_read_after_reading, QImageReader *reader, bool result);
159
160static QImageIOHandler *createReadHandlerHelper(QIODevice *device,
161 const QByteArray &format,
162 bool autoDetectImageFormat,
163 bool ignoresFormatAndExtension)
164{
165 if (!autoDetectImageFormat && format.isEmpty())
166 return nullptr;
167
168 QByteArray form = format.toLower();
169 QImageIOHandler *handler = nullptr;
170 QByteArray suffix;
171
172 qCDebug(lcImageReader) << "Finding read handler for" << device << "and format" << format;
173
174#if QT_CONFIG(imageformatplugin)
175 Q_CONSTINIT static QBasicMutex mutex;
176 const auto locker = qt_scoped_lock(mutex);
177
178 typedef QMultiMap<int, QString> PluginKeyMap;
179
180 // check if we have plugins that support the image format
181 auto l = QImageReaderWriterHelpers::pluginLoader();
182 const PluginKeyMap keyMap = l->keyMap();
183
184 qCDebug(lcImageReader) << keyMap.uniqueKeys().size() << "plugins available:" << keyMap.values();
185
186 int testFormatPluginIndex = -1;
187#endif // QT_CONFIG(imageformatplugin)
188
189 if (device && format.isEmpty() && autoDetectImageFormat && !ignoresFormatAndExtension) {
190 // if there's no format, see if \a device is a file, and if so, find the file suffix
191 if (QFile *file = qobject_cast<QFile *>(device)) {
192 suffix = QFileInfo(file->fileName()).suffix().toLower().toLatin1();
193 qCDebug(lcImageReader) << "Resolved format" << suffix << "from file name suffix";
194 }
195 }
196
197 QByteArray testFormat = !form.isEmpty() ? form : suffix;
198 if (ignoresFormatAndExtension)
199 testFormat = QByteArray();
200
201#if QT_CONFIG(imageformatplugin)
202 if (!testFormat.isEmpty()) {
203 // Check first support for the given format name or suffix among our plugins' registered
204 // formats. This allows plugins to override our built-in handlers.
205 qCDebug(lcImageReader) << "Checking if any plugins have explicitly declared support"
206 << "for the format" << testFormat;
207 const qint64 pos = device ? device->pos() : 0;
208 const auto keyList = keyMap.keys(QLatin1StringView(testFormat));
209 for (int testIndex : keyList) {
210 QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(testIndex));
211 if (plugin && plugin->capabilities(device, testFormat) & QImageIOPlugin::CanRead) {
212 qCDebug(lcImageReader) << plugin << "can read the format" << testFormat;
213 handler = plugin->create(device, testFormat);
214 testFormatPluginIndex = testIndex;
215 break;
216 }
217 }
218 if (device && !device->isSequential())
219 device->seek(pos); // Should not have moved, but guard against buggy plugins
220 }
221#endif // QT_CONFIG(imageformatplugin)
222
223 // if we don't have a handler yet, check if we have built-in support for
224 // the format
225 if (!handler && !testFormat.isEmpty()) {
226 qCDebug(lcImageReader) << "Checking if any built in handlers recognize the format"
227 << testFormat;
228 if (false) {
229#ifndef QT_NO_IMAGEFORMAT_PNG
230 } else if (testFormat == "png") {
231 handler = new QPngHandler;
232#endif
233#ifndef QT_NO_IMAGEFORMAT_BMP
234 } else if (testFormat == "bmp") {
235 handler = new QBmpHandler;
236 } else if (testFormat == "dib") {
237 handler = new QBmpHandler(QBmpHandler::DibFormat);
238#endif
239#ifndef QT_NO_IMAGEFORMAT_XPM
240 } else if (testFormat == "xpm") {
241 handler = new QXpmHandler;
242#endif
243#ifndef QT_NO_IMAGEFORMAT_XBM
244 } else if (testFormat == "xbm") {
245 handler = new QXbmHandler;
246 handler->setOption(QImageIOHandler::SubType, testFormat);
247#endif
248#ifndef QT_NO_IMAGEFORMAT_PPM
249 } else if (testFormat == "pbm" || testFormat == "pbmraw" || testFormat == "pgm"
250 || testFormat == "pgmraw" || testFormat == "ppm" || testFormat == "ppmraw") {
251 handler = new QPpmHandler;
252 handler->setOption(QImageIOHandler::SubType, testFormat);
253#endif
254 }
255
256 if (handler)
257 qCDebug(lcImageReader) << "Using the built-in handler for format" << testFormat;
258 }
259
260#if QT_CONFIG(imageformatplugin)
261 if (!handler && !testFormat.isEmpty() && autoDetectImageFormat) {
262 // check if any other plugin supports the format name (they are not allowed to
263 // read from the device yet).
264 qCDebug(lcImageReader) << "Checking if any plugins recognize the format" << testFormat;
265
266 const qint64 pos = device ? device->pos() : 0;
267
268 const int keyCount = keyMap.size();
269 for (int i = 0; i < keyCount; ++i) {
270 if (i != testFormatPluginIndex) {
271 QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(i));
272 if (plugin && plugin->capabilities(device, testFormat) & QImageIOPlugin::CanRead) {
273 qCDebug(lcImageReader) << plugin << "can read the format" << testFormat;
274 handler = plugin->create(device, testFormat);
275 break;
276 }
277 }
278 }
279 if (device && !device->isSequential())
280 device->seek(pos); // Should not have moved, but guard against buggy plugins
281 }
282#endif // QT_CONFIG(imageformatplugin)
283
284 if (!handler && !form.isEmpty() && !ignoresFormatAndExtension) {
285 // Format to use was explicitly specified, but no plugins or builtins support it
286 qCDebug(lcImageReader) << "No handler found for explicitly requested format" << form;
287 return nullptr;
288 }
289
290 if (handler && device && !suffix.isEmpty()) {
291 Q_ASSERT(qobject_cast<QFile *>(device));
292 // We have a file claiming to be of a recognized format. Now confirm that
293 // the handler also recognizes the file contents.
294 const qint64 pos = device->pos();
295 handler->setDevice(device);
296 if (!form.isEmpty())
297 handler->setFormat(form);
298 bool canRead = handler->canRead();
299 device->seek(pos);
300 if (canRead) {
301 // ok, we're done.
302 return handler;
303 }
304 qCDebug(lcImageReader) << handler << "claimed support for" << suffix
305 << "but could not read the file";
306 // File may still be valid, just with wrong suffix, so fall back to
307 // finding a handler based on contents, below.
308 delete handler;
309 handler = nullptr;
310 }
311
312#if QT_CONFIG(imageformatplugin)
313 if (!handler && (autoDetectImageFormat || ignoresFormatAndExtension)) {
314 // check if any of our plugins recognize the file from its contents.
315 qCDebug(lcImageReader) << "Checking if any plugins recognize the format"
316 << "based on the contents in" << device;
317 const qint64 pos = device ? device->pos() : 0;
318 const int keyCount = keyMap.size();
319 for (int i = 0; i < keyCount; ++i) {
320 if (i != testFormatPluginIndex) {
321 QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(i));
322 if (plugin && plugin->capabilities(device, QByteArray()) & QImageIOPlugin::CanRead) {
323 handler = plugin->create(device, testFormat);
324 qCDebug(lcImageReader) << plugin << "can read the data in" << device;
325 break;
326 }
327 }
328 }
329 if (device && !device->isSequential())
330 device->seek(pos);
331 }
332#endif // QT_CONFIG(imageformatplugin)
333
334 if (!handler && (autoDetectImageFormat || ignoresFormatAndExtension)) {
335 // check if any of our built-in handlers recognize the file from its
336 // contents.
337 qCDebug(lcImageReader) << "Checking if any built in handlers recognize the format"
338 << "based on the contents in" << device;
339 int currentFormat = 0;
340 if (!suffix.isEmpty()) {
341 // If reading from a file with a suffix, start testing our
342 // built-in handler for that suffix first.
343 for (int i = 0; i < _qt_NumFormats; ++i) {
344 if (_qt_BuiltInFormats[i].extension == suffix) {
345 currentFormat = i;
346 break;
347 }
348 }
349 }
350
351 QByteArray subType;
352 int numFormats = _qt_NumFormats;
353 while (device && numFormats >= 0) {
354 const qint64 pos = device->pos();
355 switch (currentFormat) {
356#ifndef QT_NO_IMAGEFORMAT_PNG
357 case _qt_PngFormat:
358 if (QPngHandler::canRead(device))
359 handler = new QPngHandler;
360 break;
361#endif
362#ifndef QT_NO_IMAGEFORMAT_BMP
363 case _qt_BmpFormat:
364 if (QBmpHandler::canRead(device))
365 handler = new QBmpHandler;
366 break;
367#endif
368#ifndef QT_NO_IMAGEFORMAT_XPM
369 case _qt_XpmFormat:
370 if (QXpmHandler::canRead(device))
371 handler = new QXpmHandler;
372 break;
373#endif
374#ifndef QT_NO_IMAGEFORMAT_PPM
375 case _qt_PbmFormat:
376 case _qt_PgmFormat:
377 case _qt_PpmFormat:
378 if (QPpmHandler::canRead(device, &subType)) {
379 handler = new QPpmHandler;
380 handler->setOption(QImageIOHandler::SubType, subType);
381 }
382 break;
383#endif
384#ifndef QT_NO_IMAGEFORMAT_XBM
385 case _qt_XbmFormat:
386 if (QXbmHandler::canRead(device))
387 handler = new QXbmHandler;
388 break;
389#endif
390 default:
391 break;
392 }
393 if (!device->isSequential())
394 device->seek(pos);
395
396 if (handler) {
397 qCDebug(lcImageReader, "The %s built-in handler can read this data",
398 _qt_BuiltInFormats[currentFormat].extension);
399 break;
400 }
401
402 --numFormats;
403 ++currentFormat;
404 if (currentFormat >= _qt_NumFormats)
405 currentFormat = 0;
406 }
407 }
408
409 if (!handler) {
410 qCDebug(lcImageReader, "No handlers found. Giving up.");
411 // no handler: give up.
412 return nullptr;
413 }
414
415 handler->setDevice(device);
416 if (!form.isEmpty())
417 handler->setFormat(form);
418 return handler;
419}
420
457
458int QImageReaderPrivate::maxAlloc = 256; // 256 MB is enough for an 8K 64bpp image
459
460/*!
461 \internal
462*/
465{
466 device = nullptr;
467 deleteDevice = false;
468 handler = nullptr;
469 quality = -1;
470 imageReaderError = QImageReader::UnknownError;
471 autoTransform = UsePluginDefault;
472
473 q = qq;
474}
475
476/*!
477 \internal
478*/
480{
481 delete handler;
482 if (deleteDevice)
483 delete device;
484}
485
486/*!
487 \internal
488*/
490{
491 if (handler)
492 return true;
493
494 // check some preconditions
495 if (!device || (!deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly))) {
496 imageReaderError = QImageReader::DeviceError;
497 errorString = QImageReader::tr("Invalid device");
498 return false;
499 }
500
501 // probe the file extension
502 if (deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly)) {
503 Q_ASSERT(qobject_cast<QFile*>(device) != nullptr); // future-proofing; for now this should always be the case, so...
504 QFile *file = static_cast<QFile *>(device);
505
506 if (file->error() == QFileDevice::ResourceError) {
507 // this is bad. we should abort the open attempt and note the failure.
508 imageReaderError = QImageReader::DeviceError;
509 errorString = file->errorString();
510 return false;
511 }
512
513 QString fileName = file->fileName();
514 bool fileIsOpen = false;
515
517 QList<QByteArray> extensions = QImageReader::supportedImageFormats();
518 if (!format.isEmpty()) {
519 // Try the most probable extension first
520 int currentFormatIndex = extensions.indexOf(format.toLower());
521 if (currentFormatIndex > 0)
522 extensions.swapItemsAt(0, currentFormatIndex);
523 }
524
525 int currentExtension = 0;
526 do {
527 file->setFileName(fileName + u'.'
528 + QLatin1StringView(extensions.at(currentExtension++).constData()));
529 fileIsOpen = file->open(QIODevice::ReadOnly);
530 } while (!fileIsOpen && currentExtension < extensions.size());
531 }
532
533 if (!fileIsOpen) {
534 imageReaderError = QImageReader::FileNotFoundError;
535 errorString = QImageReader::tr("File not found");
536 file->setFileName(fileName); // restore the old file name
537 return false;
538 }
539 }
540
541 // assign a handler
542 if ((handler = createReadHandlerHelper(device, format, autoDetectImageFormat, ignoresFormatAndExtension)) == nullptr) {
543 imageReaderError = QImageReader::UnsupportedFormatError;
544 errorString = QImageReader::tr("Unsupported image format");
545 return false;
546 }
547 return true;
548}
549
550/*!
551 \internal
552*/
554{
555 if (text.isEmpty() && q->supportsOption(QImageIOHandler::Description))
556 text = qt_getImageTextFromDescription(handler->option(QImageIOHandler::Description).toString());
557}
558
559/*!
560 Constructs an empty QImageReader object. Before reading an image,
561 call setDevice() or setFileName().
562*/
563QImageReader::QImageReader()
564 : d(new QImageReaderPrivate(this))
565{
566}
567
568/*!
569 Constructs a QImageReader object with the device \a device and the
570 image format \a format. If \a format is empty, it will by
571 default be auto-detected.
572
573 \sa setAutoDetectImageFormat()
574*/
575QImageReader::QImageReader(QIODevice *device, const QByteArray &format)
576 : d(new QImageReaderPrivate(this))
577{
578 d->device = device;
579 d->format = format;
580}
581
582/*!
583 Constructs a QImageReader object with the file name \a fileName
584 and the image format \a format. If \a format is empty, it will by
585 default be auto-detected.
586
587 \sa setFileName(), setAutoDetectImageFormat()
588*/
589QImageReader::QImageReader(const QString &fileName, const QByteArray &format)
590 : QImageReader(new QFile(fileName), format)
591{
592 d->deleteDevice = true;
593}
594
595/*!
596 Destructs the QImageReader object.
597*/
598QImageReader::~QImageReader()
599{
600 delete d;
601}
602
603/*!
604 Sets the format QImageReader will use when reading images, to \a
605 format. \a format is a case insensitive text string. Example:
606
607 \snippet code/src_gui_image_qimagereader.cpp 0
608
609 You can call supportedImageFormats() for the full list of formats
610 QImageReader supports.
611
612 \sa format(), {QImageReader#Security Considerations}{Security Considerations}
613*/
614void QImageReader::setFormat(const QByteArray &format)
615{
616 d->format = format;
617}
618
619/*!
620 Returns the format QImageReader uses for reading images.
621
622 You can call this function after assigning a device to the
623 reader to determine the format of the device. For example:
624
625 \snippet code/src_gui_image_qimagereader.cpp 1
626
627 If the reader cannot read any image from the device (e.g., there is no
628 image there, or the image has already been read), or if the format is
629 unsupported, this function returns an empty QByteArray().
630
631 \sa setFormat(), supportedImageFormats()
632*/
633QByteArray QImageReader::format() const
634{
635 if (d->format.isEmpty()) {
636 if (!d->initHandler())
637 return QByteArray();
638 return d->handler->canRead() ? d->handler->format() : QByteArray();
639 }
640
641 return d->format;
642}
643
644/*!
645 If \a enabled is true, image format autodetection is enabled; otherwise,
646 it is disabled. By default, autodetection is enabled.
647
648 QImageReader uses an extensive approach to detecting the image format;
649 firstly, if you pass a file name to QImageReader, it will attempt to
650 detect the file extension if the given file name does not point to an
651 existing file, by appending supported default extensions to the given file
652 name, one at a time. It then uses the following approach to detect the
653 image format:
654
655 \list 1
656
657 \li Image plugins are queried first, based on either the optional format
658 string, or the file name suffix (if the source device is a file). No
659 content detection is done at this stage. QImageReader will choose the
660 first plugin that supports reading for this format.
661
662 \li If no plugin supports the image format, Qt's built-in handlers are
663 checked based on either the optional format string, or the file name
664 suffix.
665
666 \li If a format string was specified, but no plugin or built-in handler
667 supports that format, reading fails. No content detection is done in
668 this case.
669
670 \li If a plugin or built-in handler was found based on the file name
671 suffix, but it cannot read the file contents, it is discarded and
672 detection continues as follows, since the file may just have the wrong
673 suffix.
674
675 \li If no capable plugins or built-in handlers are found, each plugin is
676 tested by inspecting the content of the data stream.
677
678 \li If no plugins could detect the image format based on data contents,
679 each built-in image handler is tested by inspecting the contents.
680
681 \li Finally, if all above approaches fail, QImageReader will report failure
682 when trying to read the image.
683
684 \endlist
685
686 By disabling image format autodetection, QImageReader will only query the
687 plugins and built-in handlers based on the format string (i.e., no file
688 name extensions are tested).
689
690 \sa QImageIOHandler::canRead(), QImageIOPlugin::capabilities()
691*/
692void QImageReader::setAutoDetectImageFormat(bool enabled)
693{
694 d->autoDetectImageFormat = enabled;
695}
696
697/*!
698 Returns \c true if image format autodetection is enabled on this image
699 reader; otherwise returns \c false. By default, autodetection is enabled.
700
701 \sa setAutoDetectImageFormat()
702*/
703bool QImageReader::autoDetectImageFormat() const
704{
705 return d->autoDetectImageFormat;
706}
707
708
709/*!
710 If \a ignored is set to true, then the image reader will ignore
711 specified formats or file extensions and decide which plugin to
712 use only based on the contents in the datastream.
713
714 Setting this flag means that all image plugins gets loaded. Each
715 plugin will read the first bytes in the image data and decide if
716 the plugin is compatible or not.
717
718 Setting this disables the normal auto-detection of the image format,
719 skipping directly to format detection by content inspection. That is
720 then performed independently of the value of autoDetectImageFormat().
721
722 \sa decideFormatFromContent(), setAutoDetectImageFormat()
723*/
724
725void QImageReader::setDecideFormatFromContent(bool ignored)
726{
727 d->ignoresFormatAndExtension = ignored;
728}
729
730
731/*!
732 Returns whether the image reader should decide which plugin to use
733 only based on the contents of the datastream rather than on the file
734 extension.
735
736 \sa setDecideFormatFromContent()
737*/
738
739bool QImageReader::decideFormatFromContent() const
740{
741 return d->ignoresFormatAndExtension;
742}
743
744
745/*!
746 Sets QImageReader's device to \a device. If a device has already
747 been set, the old device is removed from QImageReader and is
748 otherwise left unchanged.
749
750 If the device is not already open, QImageReader will attempt to
751 open the device in \l {QIODeviceBase::}{ReadOnly} mode by calling
752 open(). Note that this does not work for certain devices, such as
753 QProcess, QTcpSocket and QUdpSocket, where more logic is required
754 to open the device.
755
756 \sa device(), setFileName()
757*/
758void QImageReader::setDevice(QIODevice *device)
759{
760 delete d->handler;
761 d->handler = nullptr;
762 if (d->device && d->deleteDevice)
763 delete d->device;
764 d->device = device;
765 d->deleteDevice = false;
766 d->text.clear();
767}
768
769/*!
770 Returns the device currently assigned to QImageReader, or \nullptr
771 if no device has been assigned.
772*/
773QIODevice *QImageReader::device() const
774{
775 return d->device;
776}
777
778/*!
779 Sets the file name of QImageReader to \a fileName. Internally,
780 QImageReader will create a QFile object and open it in \l
781 {QIODeviceBase::}{ReadOnly} mode, and use this when reading images.
782
783 If \a fileName does not include a file extension (e.g., .png or .bmp),
784 QImageReader will cycle through all supported extensions until it finds
785 a matching file.
786
787 \sa fileName(), setDevice(), supportedImageFormats()
788*/
789void QImageReader::setFileName(const QString &fileName)
790{
791 setDevice(new QFile(fileName));
792 d->deleteDevice = true;
793}
794
795/*!
796 If the currently assigned device is a QFile, or if setFileName()
797 has been called, this function returns the name of the file
798 QImageReader reads from. Otherwise (i.e., if no device has been
799 assigned or the device is not a QFile), an empty QString is
800 returned.
801
802 \sa setFileName(), setDevice()
803*/
804QString QImageReader::fileName() const
805{
806 QFile *file = qobject_cast<QFile *>(d->device);
807 return file ? file->fileName() : QString();
808}
809
810/*!
811 Sets the quality setting of the image format to \a quality.
812
813 Some image formats, in particular lossy ones, entail a tradeoff between a)
814 visual quality of the resulting image, and b) decoding execution time.
815 This function sets the level of that tradeoff for image formats that
816 support it.
817
818 In case of scaled image reading, the quality setting may also influence the
819 tradeoff level between visual quality and execution speed of the scaling
820 algorithm.
821
822 The value range of \a quality depends on the image format. For example,
823 the "jpeg" format supports a quality range from 0 (low visual quality) to
824 100 (high visual quality).
825
826 \sa quality(), setScaledSize()
827*/
828void QImageReader::setQuality(int quality)
829{
830 d->quality = quality;
831}
832
833/*!
834 Returns the quality setting of the image format.
835
836 \sa setQuality()
837*/
838int QImageReader::quality() const
839{
840 return d->quality;
841}
842
843
844/*!
845 Returns the size of the image, without actually reading the image
846 contents.
847
848 If the image format does not support this feature, this function returns
849 an invalid size. Qt's built-in image handlers all support this feature,
850 but custom image format plugins are not required to do so.
851
852 \sa effectiveSize(), QImageIOHandler::ImageOption, QImageIOHandler::option(), QImageIOHandler::supportsOption()
853*/
854QSize QImageReader::size() const
855{
856 if (supportsOption(QImageIOHandler::Size))
857 return d->handler->option(QImageIOHandler::Size).toSize();
858
859 return QSize();
860}
861
862/*!
863 * \since 6.12
864 * Returns the effective size of the image accounting for transformation,
865 * without actually reading the image contents.
866 *
867 * If the image format does not support this feature, this function returns
868 * an invalid size. Qt's built-in image handlers all support this feature,
869 * but custom image format plugins are not required to do so.
870 *
871 * \sa setAutoTransform(), size(), QImageIOHandler::ImageOption, QImageIOHandler::option(), QImageIOHandler::supportsOption()
872 */
873QSize QImageReader::effectiveSize() const
874{
875 // ### Qt 7: Consider deprecating and following this behaviour in QImageReader::size()
876
877 QSize size = QImageReader::size();
878
879 if (autoTransform() && transformation().testFlag(QImageIOHandler::TransformationRotate90))
880 size.transpose();
881
882 return size;
883}
884
885/*!
886 Returns the format of the image, without actually reading the image
887 contents. The format describes the image format \l QImageReader::read()
888 returns, not the format of the actual image.
889
890 If the image format does not support this feature, this function returns
891 an invalid format.
892
893 \sa QImageIOHandler::ImageOption, QImageIOHandler::option(), QImageIOHandler::supportsOption()
894*/
895QImage::Format QImageReader::imageFormat() const
896{
897 if (supportsOption(QImageIOHandler::ImageFormat))
898 return (QImage::Format)d->handler->option(QImageIOHandler::ImageFormat).toInt();
899
900 return QImage::Format_Invalid;
901}
902
903/*!
904 Returns the text keys for this image. You can use
905 these keys with text() to list the image text for
906 a certain key.
907
908 Support for this option is implemented through
909 QImageIOHandler::Description.
910
911 \sa text(), QImageWriter::setText(), QImage::textKeys()
912*/
913QStringList QImageReader::textKeys() const
914{
915 d->getText();
916 return d->text.keys();
917}
918
919/*!
920 Returns the image text associated with \a key.
921
922 Support for this option is implemented through
923 QImageIOHandler::Description.
924
925 \sa textKeys(), QImageWriter::setText()
926*/
927QString QImageReader::text(const QString &key) const
928{
929 d->getText();
930 return d->text.value(key);
931}
932
933/*!
934 Sets the image clip rect (also known as the ROI, or Region Of
935 Interest) to \a rect. The coordinates of \a rect are relative to
936 the untransformed image size, as returned by size().
937
938 \sa clipRect(), setScaledSize(), setScaledClipRect()
939*/
940void QImageReader::setClipRect(const QRect &rect)
941{
942 d->clipRect = rect;
943}
944
945/*!
946 Returns the clip rect (also known as the ROI, or Region Of
947 Interest) of the image. If no clip rect has been set, an invalid
948 QRect is returned.
949
950 \sa setClipRect()
951*/
952QRect QImageReader::clipRect() const
953{
954 return d->clipRect;
955}
956
957/*!
958 Sets the scaled size of the image to \a size. The scaling is
959 performed after the initial clip rect, but before the scaled clip
960 rect is applied. The algorithm used for scaling depends on the
961 image format. By default (i.e., if the image format does not
962 support scaling), QImageReader will use QImage::scale() with
963 Qt::SmoothScaling.
964
965 If only one dimension is set in \a size, the other one will be
966 computed from the image's \l {size()} {natural size} so as to
967 maintain the aspect ratio.
968
969 \sa scaledSize(), setClipRect(), setScaledClipRect()
970*/
971void QImageReader::setScaledSize(const QSize &size)
972{
973 d->scaledSize = size;
974}
975
976/*!
977 Returns the scaled size of the image.
978
979 \sa setScaledSize()
980*/
981QSize QImageReader::scaledSize() const
982{
983 return d->scaledSize;
984}
985
986/*!
987 Sets the scaled clip rect to \a rect. The scaled clip rect is the
988 clip rect (also known as ROI, or Region Of Interest) that is
989 applied after the image has been scaled.
990
991 \sa scaledClipRect(), setScaledSize()
992*/
993void QImageReader::setScaledClipRect(const QRect &rect)
994{
995 d->scaledClipRect = rect;
996}
997
998/*!
999 Returns the scaled clip rect of the image.
1000
1001 \sa setScaledClipRect()
1002*/
1003QRect QImageReader::scaledClipRect() const
1004{
1005 return d->scaledClipRect;
1006}
1007
1008/*!
1009 Sets the background color to \a color.
1010 Image formats that support this operation are expected to
1011 initialize the background to \a color before reading an image.
1012
1013 \sa backgroundColor(), read()
1014*/
1015void QImageReader::setBackgroundColor(const QColor &color)
1016{
1017 if (supportsOption(QImageIOHandler::BackgroundColor))
1018 d->handler->setOption(QImageIOHandler::BackgroundColor, color);
1019}
1020
1021/*!
1022 Returns the background color that's used when reading an image.
1023 If the image format does not support setting the background color
1024 an invalid color is returned.
1025
1026 \sa setBackgroundColor(), read()
1027*/
1028QColor QImageReader::backgroundColor() const
1029{
1030 if (supportsOption(QImageIOHandler::BackgroundColor))
1031 return qvariant_cast<QColor>(d->handler->option(QImageIOHandler::BackgroundColor));
1032 return QColor();
1033}
1034
1035/*!
1036 Returns \c true if the image format supports animation;
1037 otherwise, false is returned.
1038
1039 \sa QMovie::supportedFormats()
1040*/
1041bool QImageReader::supportsAnimation() const
1042{
1043 if (supportsOption(QImageIOHandler::Animation))
1044 return d->handler->option(QImageIOHandler::Animation).toBool();
1045 return false;
1046}
1047
1048/*!
1049 \since 5.4
1050
1051 Returns the subtype of the image.
1052*/
1053QByteArray QImageReader::subType() const
1054{
1055 if (supportsOption(QImageIOHandler::SubType))
1056 return d->handler->option(QImageIOHandler::SubType).toByteArray();
1057 return QByteArray();
1058}
1059
1060/*!
1061 \since 5.4
1062
1063 Returns the list of subtypes supported by an image.
1064*/
1065QList<QByteArray> QImageReader::supportedSubTypes() const
1066{
1067 if (supportsOption(QImageIOHandler::SupportedSubTypes))
1068 return qvariant_cast<QList<QByteArray> >(d->handler->option(QImageIOHandler::SupportedSubTypes));
1069 return QList<QByteArray>();
1070}
1071
1072/*!
1073 \since 5.5
1074
1075 Returns the transformation metadata of the image, including image orientation. If the format
1076 does not support transformation metadata, QImageIOHandler::TransformationNone is returned.
1077
1078 \sa setAutoTransform(), autoTransform()
1079*/
1080QImageIOHandler::Transformations QImageReader::transformation() const
1081{
1082 int option = QImageIOHandler::TransformationNone;
1083 if (supportsOption(QImageIOHandler::ImageTransformation))
1084 option = d->handler->option(QImageIOHandler::ImageTransformation).toInt();
1085 return QImageIOHandler::Transformations(option);
1086}
1087
1088/*!
1089 \since 5.5
1090
1091 Determines that images returned by read() and sizes by effectiveSize() should
1092 have transformation metadata automatically applied if \a enabled is \c true.
1093
1094 \sa autoTransform(), transformation(), read(), effectiveSize()
1095*/
1096void QImageReader::setAutoTransform(bool enabled)
1097{
1098 d->autoTransform = enabled ? QImageReaderPrivate::ApplyTransform
1099 : QImageReaderPrivate::DoNotApplyTransform;
1100}
1101
1102/*!
1103 \since 5.5
1104
1105 Returns \c true if the image handler will apply transformation
1106 metadata on read() and effectiveSize().
1107
1108 \sa setAutoTransform(), transformation(), read(), effectiveSize()
1109*/
1110bool QImageReader::autoTransform() const
1111{
1112 switch (d->autoTransform) {
1113 case QImageReaderPrivate::ApplyTransform:
1114 return true;
1115 case QImageReaderPrivate::DoNotApplyTransform:
1116 return false;
1117 case QImageReaderPrivate::UsePluginDefault:
1118 Q_FALLTHROUGH();
1119 default:
1120 break;
1121 }
1122 return false;
1123}
1124
1125/*!
1126 Returns \c true if an image can be read for the device (i.e., the
1127 image format is supported, and the device seems to contain valid
1128 data); otherwise returns \c false.
1129
1130 canRead() is a lightweight function that only does a quick test to
1131 see if the image data is valid. read() may still return false
1132 after canRead() returns \c true, if the image data is corrupt.
1133
1134 \note A QMimeDatabase lookup is normally a better approach than this
1135 function for identifying potentially non-image files or data.
1136
1137 For images that support animation, canRead() returns \c false when
1138 all frames have been read.
1139
1140 \sa read(), supportedImageFormats(), QMimeDatabase
1141*/
1142bool QImageReader::canRead() const
1143{
1144 if (!d->initHandler())
1145 return false;
1146
1147 return d->handler->canRead();
1148}
1149
1150/*!
1151 Reads an image from the device. On success, the image that was
1152 read is returned; otherwise, a null QImage is returned. You can
1153 then call error() to find the type of error that occurred, or
1154 errorString() to get a human readable description of the error.
1155
1156 For image formats that support animation, calling read()
1157 repeatedly will return the next frame. When all frames have been
1158 read, a null image will be returned.
1159
1160 \sa canRead(), supportedImageFormats(), supportsAnimation(), QMovie
1161*/
1162QImage QImageReader::read()
1163{
1164 // Because failed image reading might have side effects, we explicitly
1165 // return a null image instead of the image we've just created.
1166 QImage image;
1167 return read(&image) ? image : QImage();
1168}
1169
1170extern void qt_imageTransform(QImage &src, QImageIOHandler::Transformations orient);
1171
1172/*!
1173 \overload
1174
1175 Reads an image from the device into \a image, which must point to a
1176 QImage. Returns \c true on success; otherwise, returns \c false.
1177
1178 If \a image has same format and size as the image data that is about to be
1179 read, this function may not need to allocate a new image before
1180 reading. Because of this, it can be faster than the other read() overload,
1181 which always constructs a new image; especially when reading several
1182 images with the same format and size.
1183
1184 \snippet code/src_gui_image_qimagereader.cpp 2
1185
1186 For image formats that support animation, calling read() repeatedly will
1187 return the next frame. When all frames have been read, a null image will
1188 be returned.
1189
1190 \sa canRead(), supportedImageFormats(), supportsAnimation(), QMovie
1191*/
1192bool QImageReader::read(QImage *image)
1193{
1194 if (!image) {
1195 qWarning("QImageReader::read: cannot read into null pointer");
1196 return false;
1197 }
1198
1199 if (!d->initHandler())
1200 return false;
1201
1202 QSize scaledSize = d->scaledSize;
1203 if ((scaledSize.width() <= 0 && scaledSize.height() > 0) ||
1204 (scaledSize.height() <= 0 && scaledSize.width() > 0)) {
1205 // if only one dimension is given, let's try to calculate the second one
1206 // based on the original image size and maintaining the aspect ratio
1207 if (const QSize originalSize = size(); !originalSize.isEmpty()) {
1208 if (scaledSize.width() <= 0) {
1209 const auto ratio = qreal(scaledSize.height()) / originalSize.height();
1210 if (const qreal newWidth = originalSize.width() * ratio; newWidth < INT_MAX)
1211 scaledSize.setWidth(qMax(1, qRound(newWidth)));
1212 } else {
1213 const auto ratio = qreal(scaledSize.width()) / originalSize.width();
1214 if (const qreal newHeight = originalSize.height() * ratio; newHeight < INT_MAX)
1215 scaledSize.setHeight(qMax(1, qRound(newHeight)));
1216 }
1217
1218 if (scaledSize.isEmpty()) {
1219 d->imageReaderError = InvalidDataError;
1220 d->errorString = QImageReader::tr("Scaled size out of range");
1221 return false;
1222 }
1223 }
1224 }
1225
1226 const bool supportScaledSize = supportsOption(QImageIOHandler::ScaledSize) && scaledSize.isValid();
1227 const bool supportClipRect = supportsOption(QImageIOHandler::ClipRect) && !d->clipRect.isNull();
1228 const bool supportScaledClipRect = supportsOption(QImageIOHandler::ScaledClipRect) && !d->scaledClipRect.isNull();
1229
1230 // set the handler specific options.
1231 if (supportScaledSize) {
1232 if (supportClipRect || d->clipRect.isNull()) {
1233 // Only enable the ScaledSize option if there is no clip rect, or
1234 // if the handler also supports ClipRect.
1235 d->handler->setOption(QImageIOHandler::ScaledSize, scaledSize);
1236 }
1237 }
1238 if (supportClipRect)
1239 d->handler->setOption(QImageIOHandler::ClipRect, d->clipRect);
1240 if (supportScaledClipRect)
1241 d->handler->setOption(QImageIOHandler::ScaledClipRect, d->scaledClipRect);
1242 if (supportsOption(QImageIOHandler::Quality))
1243 d->handler->setOption(QImageIOHandler::Quality, d->quality);
1244
1245 // read the image
1246 QString filename = fileName();
1247 if (Q_TRACE_ENABLED(QImageReader_read_before_reading)) {
1248 Q_TRACE(QImageReader_read_before_reading, this, filename.isEmpty() ? u"unknown"_s : filename);
1249 }
1250
1251 const bool result = d->handler->read(image);
1252
1253 Q_TRACE(QImageReader_read_after_reading, this, result);
1254
1255 if (!result) {
1256 d->imageReaderError = InvalidDataError;
1257 d->errorString = QImageReader::tr("Unable to read image data");
1258 return false;
1259 }
1260
1261 // Fallback scaling is part of reading, so it must respect the allocation limit too
1262 const auto scaleImage = [&] {
1263 if (QImageData::isWithinIOAllocationLimit(scaledSize.width(), scaledSize.height(),
1264 image->format(), "QImageReader")) {
1265 *image = image->scaled(scaledSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
1266 if (!image->isNull())
1267 return true;
1268 }
1269 *image = QImage();
1270 d->imageReaderError = InvalidDataError;
1271 d->errorString = QImageReader::tr("Unable to scale image");
1272 return false;
1273 };
1274
1275 // provide default implementations for any unsupported image
1276 // options
1277 if (supportClipRect) {
1278 if (supportScaledSize) {
1279 if (supportScaledClipRect) {
1280 // all features are supported by the handler; nothing to do.
1281 } else {
1282 // the image is already scaled, so apply scaled clipping.
1283 if (!d->scaledClipRect.isNull())
1284 *image = image->copy(d->scaledClipRect);
1285 }
1286 } else {
1287 if (supportScaledClipRect) {
1288 // supports scaled clipping but not scaling, most
1289 // likely a broken handler.
1290 } else {
1291 if (scaledSize.isValid() && !scaleImage())
1292 return false;
1293 if (d->scaledClipRect.isValid()) {
1294 *image = image->copy(d->scaledClipRect);
1295 }
1296 }
1297 }
1298 } else {
1299 if (supportScaledSize && d->clipRect.isNull()) {
1300 if (supportScaledClipRect) {
1301 // nothing to do (ClipRect is ignored!)
1302 } else {
1303 // provide all workarounds.
1304 if (d->scaledClipRect.isValid()) {
1305 *image = image->copy(d->scaledClipRect);
1306 }
1307 }
1308 } else {
1309 if (supportScaledClipRect) {
1310 // this makes no sense; a handler that supports
1311 // ScaledClipRect but not ScaledSize is broken, and we
1312 // can't work around it.
1313 } else {
1314 // provide all workarounds.
1315 if (d->clipRect.isValid())
1316 *image = image->copy(d->clipRect);
1317 if (scaledSize.isValid() && !scaleImage())
1318 return false;
1319 if (d->scaledClipRect.isValid())
1320 *image = image->copy(d->scaledClipRect);
1321 }
1322 }
1323 }
1324
1325 // successful read; check for "@Nx" file name suffix and set device pixel ratio.
1326 static bool disableNxImageLoading = !qEnvironmentVariableIsEmpty("QT_HIGHDPI_DISABLE_2X_IMAGE_LOADING");
1327 if (!disableNxImageLoading) {
1328 const QByteArray suffix = QFileInfo(filename).baseName().right(3).toLatin1();
1329 if (suffix.size() == 3 && suffix[0] == '@' && suffix[1] >= '2' && suffix[1] <= '9' && suffix[2] == 'x')
1330 image->setDevicePixelRatio(suffix[1] - '0');
1331 }
1332 if (autoTransform())
1333 qt_imageTransform(*image, transformation());
1334
1335 return true;
1336}
1337
1338/*!
1339 For image formats that support animation, this function steps over the
1340 current image, returning true if successful or false if there is no
1341 following image in the animation.
1342
1343 The default implementation calls read(), then discards the resulting
1344 image, but the image handler may have a more efficient way of implementing
1345 this operation.
1346
1347 \sa jumpToImage(), QImageIOHandler::jumpToNextImage()
1348*/
1349bool QImageReader::jumpToNextImage()
1350{
1351 if (!d->initHandler())
1352 return false;
1353 return d->handler->jumpToNextImage();
1354}
1355
1356/*!
1357 For image formats that support animation, this function skips to the image
1358 whose sequence number is \a imageNumber, returning true if successful
1359 or false if the corresponding image cannot be found.
1360
1361 The next call to read() will attempt to read this image.
1362
1363 \sa jumpToNextImage(), QImageIOHandler::jumpToImage()
1364*/
1365bool QImageReader::jumpToImage(int imageNumber)
1366{
1367 if (!d->initHandler())
1368 return false;
1369 return d->handler->jumpToImage(imageNumber);
1370}
1371
1372/*!
1373 For image formats that support animation, this function returns the number
1374 of times the animation should loop. If this function returns -1, it can
1375 either mean the animation should loop forever, or that an error occurred.
1376 If an error occurred, canRead() will return false.
1377
1378 \sa supportsAnimation(), QImageIOHandler::loopCount(), canRead()
1379*/
1380int QImageReader::loopCount() const
1381{
1382 if (!d->initHandler())
1383 return -1;
1384 return d->handler->loopCount();
1385}
1386
1387/*!
1388 For image formats that support animation, this function returns the total
1389 number of images in the animation. If the format does not support
1390 animation, 0 is returned.
1391
1392 This function returns -1 if an error occurred.
1393
1394 \sa supportsAnimation(), QImageIOHandler::imageCount(), canRead()
1395*/
1396int QImageReader::imageCount() const
1397{
1398 if (!d->initHandler())
1399 return -1;
1400 return d->handler->imageCount();
1401}
1402
1403/*!
1404 For image formats that support animation, this function returns the number
1405 of milliseconds to wait until displaying the next frame in the animation.
1406 If the image format doesn't support animation, 0 is returned.
1407
1408 This function returns -1 if an error occurred.
1409
1410 \sa supportsAnimation(), QImageIOHandler::nextImageDelay(), canRead()
1411*/
1412int QImageReader::nextImageDelay() const
1413{
1414 if (!d->initHandler())
1415 return -1;
1416 return d->handler->nextImageDelay();
1417}
1418
1419/*!
1420 For image formats that support animation, this function returns the
1421 sequence number of the current frame. If the image format doesn't support
1422 animation, 0 is returned.
1423
1424 This function returns -1 if an error occurred.
1425
1426 \sa supportsAnimation(), QImageIOHandler::currentImageNumber(), canRead()
1427*/
1428int QImageReader::currentImageNumber() const
1429{
1430 if (!d->initHandler())
1431 return -1;
1432 return d->handler->currentImageNumber();
1433}
1434
1435/*!
1436 For image formats that support animation, this function returns
1437 the rect for the current frame. Otherwise, a null rect is returned.
1438
1439 \sa supportsAnimation(), QImageIOHandler::currentImageRect()
1440*/
1441QRect QImageReader::currentImageRect() const
1442{
1443 if (!d->initHandler())
1444 return QRect();
1445 return d->handler->currentImageRect();
1446}
1447
1448/*!
1449 Returns the type of error that occurred last.
1450
1451 \sa ImageReaderError, errorString()
1452*/
1453QImageReader::ImageReaderError QImageReader::error() const
1454{
1455 return d->imageReaderError;
1456}
1457
1458/*!
1459 Returns a human readable description of the last error that
1460 occurred.
1461
1462 \sa error()
1463*/
1464QString QImageReader::errorString() const
1465{
1466 if (d->errorString.isEmpty())
1467 return QImageReader::tr("Unknown error");
1468 return d->errorString;
1469}
1470
1471/*!
1472 Returns \c true if the reader supports \a option; otherwise returns
1473 false.
1474
1475 Different image formats support different options. Call this function to
1476 determine whether a certain option is supported by the current format. For
1477 example, the PNG format allows you to embed text into the image's metadata
1478 (see text()), and the BMP format allows you to determine the image's size
1479 without loading the whole image into memory (see size()).
1480
1481 \snippet code/src_gui_image_qimagereader.cpp 3
1482
1483 \sa QImageWriter::supportsOption()
1484*/
1485bool QImageReader::supportsOption(QImageIOHandler::ImageOption option) const
1486{
1487 if (!d->initHandler())
1488 return false;
1489 return d->handler->supportsOption(option);
1490}
1491
1492/*!
1493 If supported, this function returns the image format of the file
1494 \a fileName. Otherwise, an empty string is returned.
1495*/
1496QByteArray QImageReader::imageFormat(const QString &fileName)
1497{
1498 QFile file(fileName);
1499 if (!file.open(QFile::ReadOnly))
1500 return QByteArray();
1501
1502 return imageFormat(&file);
1503}
1504
1505/*!
1506 If supported, this function returns the image format of the device
1507 \a device. Otherwise, an empty string is returned.
1508
1509 \sa QImageReader::autoDetectImageFormat()
1510*/
1511QByteArray QImageReader::imageFormat(QIODevice *device)
1512{
1513 QByteArray format;
1514 QImageIOHandler *handler = createReadHandlerHelper(device, format, /* autoDetectImageFormat = */ true, false);
1515 if (handler) {
1516 if (handler->canRead())
1517 format = handler->format();
1518 delete handler;
1519 }
1520 return format;
1521}
1522
1523/*!
1524 Returns the list of image formats supported by QImageReader.
1525
1526 By default, Qt can read the following formats:
1527
1528 \table
1529 \header \li Format \li MIME type \li Description
1530 \row \li BMP \li image/bmp \li Windows Bitmap
1531 \row \li GIF \li image/gif \li Graphic Interchange Format (optional)
1532 \row \li JPG \li image/jpeg \li Joint Photographic Experts Group
1533 \row \li PNG \li image/png \li Portable Network Graphics
1534 \row \li PBM \li image/x-portable-bitmap \li Portable Bitmap
1535 \row \li PGM \li image/x-portable-graymap \li Portable Graymap
1536 \row \li PPM \li image/x-portable-pixmap \li Portable Pixmap
1537 \row \li XBM \li image/x-xbitmap \li X11 Bitmap
1538 \row \li XPM \li image/x-xpixmap \li X11 Pixmap
1539 \row \li SVG \li image/svg+xml \li Scalable Vector Graphics
1540 \endtable
1541
1542 Reading and writing SVG files is supported through the \l{Qt SVG} module.
1543 The \l{Qt Image Formats} module provides support for additional image formats.
1544
1545 Note that the QCoreApplication instance must be created before this function is
1546 called.
1547
1548 \sa setFormat(), QImageWriter::supportedImageFormats(), QImageIOPlugin
1549*/
1550
1551QList<QByteArray> QImageReader::supportedImageFormats()
1552{
1553 return QImageReaderWriterHelpers::supportedImageFormats(QImageReaderWriterHelpers::CanRead);
1554}
1555
1556/*!
1557 Returns the list of MIME types supported by QImageReader.
1558
1559 Note that the QApplication instance must be created before this function is
1560 called.
1561
1562 \sa supportedImageFormats(), QImageWriter::supportedMimeTypes()
1563*/
1564
1565QList<QByteArray> QImageReader::supportedMimeTypes()
1566{
1567 return QImageReaderWriterHelpers::supportedMimeTypes(QImageReaderWriterHelpers::CanRead);
1568}
1569
1570/*!
1571 \since 5.12
1572
1573 Returns the list of image formats corresponding to \a mimeType.
1574
1575 Note that the QGuiApplication instance must be created before this function is
1576 called.
1577
1578 \sa supportedImageFormats(), supportedMimeTypes()
1579*/
1580
1581QList<QByteArray> QImageReader::imageFormatsForMimeType(const QByteArray &mimeType)
1582{
1583 return QImageReaderWriterHelpers::imageFormatsForMimeType(mimeType,
1584 QImageReaderWriterHelpers::CanRead);
1585}
1586
1587/*!
1588 \since 6.0
1589
1590 Returns the current allocation limit, in megabytes.
1591
1592 \sa setAllocationLimit()
1593*/
1594int QImageReader::allocationLimit()
1595{
1596 static int envLimit = []() {
1597 bool ok = false;
1598 int res = qEnvironmentVariableIntValue("QT_IMAGEIO_MAXALLOC", &ok);
1599 return ok ? res : -1;
1600 }();
1601
1602 return envLimit >= 0 ? envLimit : QImageReaderPrivate::maxAlloc;
1603}
1604
1605/*!
1606 \since 6.0
1607
1608 Sets the allocation limit to \a mbLimit megabytes. Images that would
1609 require a QImage memory allocation above this limit will be rejected.
1610 If \a mbLimit is 0, the allocation size check will be disabled.
1611
1612 This limit helps applications avoid unexpectedly large memory usage from
1613 loading corrupt image files. It is normally not needed to change it. The
1614 default limit is large enough for all commonly used image sizes.
1615
1616 It should be noted that this is not an upper limit on other memory allocations during image
1617 reading, such as temporary decoding buffers. Such allocations are limited to a small multiple
1618 of this limit, depending on the handler.
1619
1620 At runtime, this value may be overridden by the environment variable \c QT_IMAGEIO_MAXALLOC.
1621
1622 \note The memory requirements are calculated for a minimum of 32 bits per pixel, since Qt will
1623 typically convert an image to that depth when it is used in GUI. This means that the effective
1624 allocation limit is significantly smaller than \a mbLimit when reading 1 bpp and 8 bpp images.
1625
1626 \sa allocationLimit()
1627*/
1628void QImageReader::setAllocationLimit(int mbLimit)
1629{
1630 if (mbLimit >= 0)
1631 QImageReaderPrivate::maxAlloc = mbLimit;
1632}
1633
1634QT_END_NAMESPACE
QImageIOHandler * handler
QMap< QString, QString > text
QImageReaderPrivate(QImageReader *qq)
Definition qcompare.h:111
Q_GUI_EXPORT void qt_imageTransform(QImage &src, QImageIOHandler::Transformations orient)
Definition qimage.cpp:6582
Q_TRACE_POINT(qtgui, QImageReader_read_before_reading, QImageReader *reader, const QString &filename)
static QImageIOHandler * createReadHandlerHelper(QIODevice *device, const QByteArray &format, bool autoDetectImageFormat, bool ignoresFormatAndExtension)
#define qCDebug(category,...)
#define Q_STATIC_LOGGING_CATEGORY(name,...)