1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtGui module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40/*!
41 \class QImageIOHandler
42 \brief The QImageIOHandler class defines the common image I/O
43 interface for all image formats in Qt.
44 \reentrant
45 \inmodule QtGui
46
47 Qt uses QImageIOHandler for reading and writing images through
48 QImageReader and QImageWriter. You can also derive from this class
49 to write your own image format handler using Qt's plugin mechanism.
50
51 Call setDevice() to assign a device to the handler, and
52 setFormat() to assign a format to it. One QImageIOHandler may
53 support more than one image format. canRead() returns \c true if an
54 image can be read from the device, and read() and write() return
55 true if reading or writing an image was completed successfully.
56
57 QImageIOHandler also has support for animations formats, through
58 the functions loopCount(), imageCount(), nextImageDelay() and
59 currentImageNumber().
60
61 In order to determine what options an image handler supports, Qt
62 will call supportsOption() and setOption(). Make sure to
63 reimplement these functions if you can provide support for any of
64 the options in the ImageOption enum.
65
66 To write your own image handler, you must at least reimplement
67 canRead() and read(). Then create a QImageIOPlugin that
68 can create the handler. Finally, install your plugin, and
69 QImageReader and QImageWriter will then automatically load the
70 plugin, and start using it.
71
72 \sa QImageIOPlugin, QImageReader, QImageWriter
73*/
74
75/*! \enum QImageIOHandler::ImageOption
76
77 This enum describes the different options supported by
78 QImageIOHandler. Some options are used to query an image for
79 properties, and others are used to toggle the way in which an
80 image should be written.
81
82 \value Size The original size of an image. A handler that supports
83 this option is expected to read the size of the image from the
84 image metadata, and return this size from option() as a QSize.
85
86 \value ClipRect The clip rect, or ROI (Region Of Interest). A
87 handler that supports this option is expected to only read the
88 provided QRect area from the original image in read(), before any
89 other transformation is applied.
90
91 \value ScaledSize The scaled size of the image. A handler that
92 supports this option is expected to scale the image to the
93 provided size (a QSize), after applying any clip rect
94 transformation (ClipRect). If the handler does not support this
95 option, QImageReader will perform the scaling after the image has
96 been read.
97
98 \value ScaledClipRect The scaled clip rect (or ROI, Region Of
99 Interest) of the image. A handler that supports this option is
100 expected to apply the provided clip rect (a QRect), after applying
101 any scaling (ScaleSize) or regular clipping (ClipRect). If the
102 handler does not support this option, QImageReader will apply the
103 scaled clip rect after the image has been read.
104
105 \value Description The image description. Some image formats,
106 such as GIF and PNG, allow embedding of text
107 or comments into the image data (e.g., for storing copyright
108 information). It's common that the text is stored in key-value
109 pairs, but some formats store all text in one continuous block.
110 QImageIOHandler returns the text as one
111 QString, where keys and values are separated by a ':', and
112 keys-value pairs are separated by two newlines (\\n\\n). For example,
113 "Title: Sunset\\n\\nAuthor: Jim Smith\\nSarah Jones\\n\\n". Formats that
114 store text in a single block can use "Description" as the key.
115
116 \value CompressionRatio The compression ratio of the image data. A
117 handler that supports this option is expected to set its
118 compression rate depending on the value of this option (an int)
119 when writing.
120
121 \value Gamma The gamma level of the image. A handler that supports
122 this option is expected to set the image gamma level depending on
123 the value of this option (a float) when writing.
124
125 \value Quality The quality level of the image. A handler that
126 supports this option is expected to set the image quality level
127 depending on the value of this option (an int) when writing.
128
129 \value Name The name of the image. A handler that supports this
130 option is expected to read the name from the image metadata and
131 return this as a QString, or when writing an image it is expected
132 to store the name in the image metadata.
133
134 \value SubType The subtype of the image. A handler that supports
135 this option can use the subtype value to help when reading and
136 writing images. For example, a PPM handler may have a subtype
137 value of "ppm" or "ppmraw".
138
139 \value IncrementalReading A handler that supports this option is
140 expected to read the image in several passes, as if it was an
141 animation. QImageReader will treat the image as an animation.
142
143 \value Endianness The endianness of the image. Certain image
144 formats can be stored as BigEndian or LittleEndian. A handler that
145 supports Endianness uses the value of this option to determine how
146 the image should be stored.
147
148 \value Animation Image formats that support animation return
149 true for this value in supportsOption(); otherwise, false is returned.
150
151 \value BackgroundColor Certain image formats allow the
152 background color to be specified. A handler that supports
153 BackgroundColor initializes the background color to this option
154 (a QColor) when reading an image.
155
156 \value ImageFormat The image's data format returned by the handler.
157 This can be any of the formats listed in QImage::Format.
158
159 \value SupportedSubTypes Image formats that support different saving
160 variants should return a list of supported variant names
161 (QList<QByteArray>) in this option.
162
163 \value OptimizedWrite. A handler which supports this option
164 is expected to turn on optimization flags when writing.
165
166 \value ProgressiveScanWrite. A handler which supports
167 this option is expected to write the image as a progressive scan image.
168
169 \value ImageTransformation. A handler which supports this option can read
170 the transformation metadata of an image. A handler that supports this option
171 should not apply the transformation itself.
172
173\if !defined(qt6)
174 \value TransformedByDefault. A handler that reports support for this feature
175 will have image transformation metadata applied by default on read.
176\endif
177*/
178
179/*! \enum QImageIOHandler::Transformation
180 \since 5.5
181
182 This enum describes the different transformations or orientations
183 supported by some image formats, usually through EXIF.
184
185 \value TransformationNone No transformation should be applied.
186
187 \value TransformationMirror Mirror the image horizontally.
188
189 \value TransformationFlip Mirror the image vertically.
190
191 \value TransformationRotate180 Rotate the image 180 degrees.
192 This is the same as mirroring it both horizontally and vertically.
193
194 \value TransformationRotate90 Rotate the image 90 degrees.
195
196 \value TransformationMirrorAndRotate90 Mirror the image horizontally
197 and then rotate it 90 degrees.
198
199 \value TransformationFlipAndRotate90 Mirror the image vertically
200 and then rotate it 90 degrees.
201
202 \value TransformationRotate270 Rotate the image 270 degrees.
203 This is the same as mirroring it both horizontally, vertically and
204 then rotating it 90 degrees.
205
206 \sa QImageReader::transformation(), QImageReader::setAutoTransform(), QImageWriter::setTransformation()
207*/
208
209/*!
210 \class QImageIOPlugin
211 \inmodule QtGui
212 \brief The QImageIOPlugin class defines an interface for writing
213 an image format plugin.
214 \reentrant
215
216 \ingroup plugins
217
218 QImageIOPlugin is a factory for creating QImageIOHandler objects,
219 which are used internally by QImageReader and QImageWriter to add
220 support for different image formats to Qt.
221
222 Writing an image I/O plugin is achieved by subclassing this
223 base class, reimplementing the pure virtual functions capabilities()
224 and create(), and exporting the class with the
225 Q_PLUGIN_METADATA() macro. See \l{How to Create Qt Plugins} for details.
226
227 An image format plugin can support three capabilities: reading (\l
228 CanRead), writing (\l CanWrite) and \e incremental reading (\l
229 CanReadIncremental). Reimplement capabilities() in your subclass to
230 expose the capabilities of your image format.
231
232 create() should create an instance of your QImageIOHandler
233 subclass, with the provided device and format properly set, and
234 return this handler.
235
236 The json metadata file for the plugin needs to contain information
237 about the image formats the plugins supports, together with the
238 corresponding MIME types (one for each format). For a jpeg plugin, this
239 could, for example, look as follows:
240
241 \code
242 {
243 "Keys": [ "jpg", "jpeg" ],
244 "MimeTypes": [ "image/jpeg", "image/jpeg" ]
245 }
246 \endcode
247
248 Different plugins can support different capabilities. For example,
249 you may have one plugin that supports reading the GIF format, and
250 another that supports writing. Qt will select the correct plugin
251 for the job, depending on the return value of capabilities(). If
252 several plugins support the same capability, Qt will select one
253 arbitrarily.
254
255 \sa QImageIOHandler, {How to Create Qt Plugins}
256*/
257
258/*!
259 \enum QImageIOPlugin::Capability
260
261 This enum describes the capabilities of a QImageIOPlugin.
262
263 \value CanRead The plugin can read images.
264 \value CanWrite The plugin can write images.
265 \value CanReadIncremental The plugin can read images incrementally.
266*/
267
268#include "qimageiohandler.h"
269#include "qimage_p.h"
270
271#include <qbytearray.h>
272#include <qimagereader.h>
273#include <qloggingcategory.h>
274#include <qvariant.h>
275
276QT_BEGIN_NAMESPACE
277
278Q_LOGGING_CATEGORY(lcImageIo, "qt.gui.imageio")
279
280class QIODevice;
281
282class QImageIOHandlerPrivate
283{
284 Q_DECLARE_PUBLIC(QImageIOHandler)
285public:
286 QImageIOHandlerPrivate(QImageIOHandler *q);
287 virtual ~QImageIOHandlerPrivate();
288
289 QIODevice *device;
290 mutable QByteArray format;
291
292 QImageIOHandler *q_ptr;
293};
294
295QImageIOHandlerPrivate::QImageIOHandlerPrivate(QImageIOHandler *q)
296{
297 device = nullptr;
298 q_ptr = q;
299}
300
301QImageIOHandlerPrivate::~QImageIOHandlerPrivate()
302{
303}
304
305/*!
306 Constructs a QImageIOHandler object.
307*/
308QImageIOHandler::QImageIOHandler()
309 : d_ptr(new QImageIOHandlerPrivate(this))
310{
311}
312
313/*! \internal
314
315 Constructs a QImageIOHandler object, using the private member \a
316 dd.
317*/
318QImageIOHandler::QImageIOHandler(QImageIOHandlerPrivate &dd)
319 : d_ptr(&dd)
320{
321}
322
323/*!
324 Destructs the QImageIOHandler object.
325*/
326QImageIOHandler::~QImageIOHandler()
327{
328}
329
330/*!
331 Sets the device of the QImageIOHandler to \a device. The image
332 handler will use this device when reading and writing images.
333
334 The device can only be set once and must be set before calling
335 canRead(), read(), write(), etc. If you need to read multiple
336 files, construct multiple instances of the appropriate
337 QImageIOHandler subclass.
338
339 \sa device()
340*/
341void QImageIOHandler::setDevice(QIODevice *device)
342{
343 Q_D(QImageIOHandler);
344 d->device = device;
345}
346
347/*!
348 Returns the device currently assigned to the QImageIOHandler. If
349 not device has been assigned, \nullptr is returned.
350*/
351QIODevice *QImageIOHandler::device() const
352{
353 Q_D(const QImageIOHandler);
354 return d->device;
355}
356
357/*!
358 Sets the format of the QImageIOHandler to \a format. The format is
359 most useful for handlers that support multiple image formats.
360
361 \sa format()
362*/
363void QImageIOHandler::setFormat(const QByteArray &format)
364{
365 Q_D(QImageIOHandler);
366 d->format = format;
367}
368
369/*!
370 Sets the format of the QImageIOHandler to \a format. The format is
371 most useful for handlers that support multiple image formats.
372
373 This function is declared const so that it can be called from canRead().
374
375 \sa format()
376*/
377void QImageIOHandler::setFormat(const QByteArray &format) const
378{
379 Q_D(const QImageIOHandler);
380 d->format = format;
381}
382
383/*!
384 Returns the format that is currently assigned to
385 QImageIOHandler. If no format has been assigned, an empty string
386 is returned.
387
388 \sa setFormat()
389*/
390QByteArray QImageIOHandler::format() const
391{
392 Q_D(const QImageIOHandler);
393 return d->format;
394}
395
396/*!
397 \fn bool QImageIOHandler::read(QImage *image)
398
399 Read an image from the device, and stores it in \a image.
400 Returns \c true if the image is successfully read; otherwise returns
401 false.
402
403 For image formats that support incremental loading, and for animation
404 formats, the image handler can assume that \a image points to the
405 previous frame.
406
407 \sa canRead()
408*/
409
410/*!
411 \fn bool QImageIOHandler::canRead() const
412
413 Returns \c true if an image can be read from the device (i.e., the
414 image format is supported, the device can be read from and the
415 initial header information suggests that the image can be read);
416 otherwise returns \c false.
417
418 When reimplementing canRead(), make sure that the I/O device
419 (device()) is left in its original state (e.g., by using peek()
420 rather than read()).
421
422 \sa read(), QIODevice::peek()
423*/
424
425/*!
426 Writes the image \a image to the assigned device. Returns \c true on
427 success; otherwise returns \c false.
428
429 The default implementation does nothing, and simply returns \c false.
430*/
431bool QImageIOHandler::write(const QImage &image)
432{
433 Q_UNUSED(image);
434 return false;
435}
436
437/*!
438 Sets the option \a option with the value \a value.
439
440 \sa option(), ImageOption
441*/
442void QImageIOHandler::setOption(ImageOption option, const QVariant &value)
443{
444 Q_UNUSED(option);
445 Q_UNUSED(value);
446}
447
448/*!
449 Returns the value assigned to \a option as a QVariant. The type of
450 the value depends on the option. For example, option(Size) returns
451 a QSize variant.
452
453 \sa setOption(), supportsOption()
454*/
455QVariant QImageIOHandler::option(ImageOption option) const
456{
457 Q_UNUSED(option);
458 return QVariant();
459}
460
461/*!
462 Returns \c true if the QImageIOHandler supports the option \a option;
463 otherwise returns \c false. For example, if the QImageIOHandler
464 supports the \l Size option, supportsOption(Size) must return
465 true.
466
467 \sa setOption(), option()
468*/
469bool QImageIOHandler::supportsOption(ImageOption option) const
470{
471 Q_UNUSED(option);
472 return false;
473}
474
475/*!
476 For image formats that support animation, this function returns
477 the sequence number of the current image in the animation. If
478 this function is called before any image is read(), -1 is
479 returned. The number of the first image in the sequence is 0.
480
481 If the image format does not support animation, 0 is returned.
482
483 \sa read()
484*/
485int QImageIOHandler::currentImageNumber() const
486{
487 return 0;
488}
489
490/*!
491 Returns the rect of the current image. If no rect is defined for the
492 image, and empty QRect() is returned.
493
494 This function is useful for animations, where only parts of the frame
495 may be updated at a time.
496*/
497QRect QImageIOHandler::currentImageRect() const
498{
499 return QRect();
500}
501
502/*!
503 For image formats that support animation, this function returns
504 the number of images in the animation. If the image format does
505 not support animation, or if it is unable to determine the number
506 of images, 0 is returned.
507
508 The default implementation returns 1 if canRead() returns \c true;
509 otherwise 0 is returned.
510*/
511int QImageIOHandler::imageCount() const
512{
513 return canRead() ? 1 : 0;
514}
515
516/*!
517 For image formats that support animation, this function jumps to the
518 next image.
519
520 The default implementation does nothing, and returns \c false.
521*/
522bool QImageIOHandler::jumpToNextImage()
523{
524 return false;
525}
526
527/*!
528 For image formats that support animation, this function jumps to the image
529 whose sequence number is \a imageNumber. The next call to read() will
530 attempt to read this image.
531
532 The default implementation does nothing, and returns \c false.
533*/
534bool QImageIOHandler::jumpToImage(int imageNumber)
535{
536 Q_UNUSED(imageNumber);
537 return false;
538}
539
540/*!
541 For image formats that support animation, this function returns
542 the number of times the animation should loop. If the image format
543 does not support animation, 0 is returned.
544*/
545int QImageIOHandler::loopCount() const
546{
547 return 0;
548}
549
550/*!
551 For image formats that support animation, this function returns
552 the number of milliseconds to wait until reading the next
553 image. If the image format does not support animation, 0 is
554 returned.
555*/
556int QImageIOHandler::nextImageDelay() const
557{
558 return 0;
559}
560
561/*!
562 \since 6.0
563
564 This is a convenience method for the reading function in subclasses. Image
565 format handlers must reject loading an image if the required allocation
566 would exceeed the current allocation limit. This function checks the
567 parameters and limit, and does the allocation if it is valid and required.
568 Upon successful return, \a image will be a valid, detached QImage of the
569 given \a size and \a format.
570
571 \sa QImageReader::allocationLimit()
572*/
573bool QImageIOHandler::allocateImage(QSize size, QImage::Format format, QImage *image)
574{
575 Q_ASSERT(image);
576 if (size.isEmpty() || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
577 return false;
578
579 if (image->size() == size && image->format() == format) {
580 image->detach();
581 } else {
582 if (const int mbLimit = QImageReader::allocationLimit()) {
583 qsizetype depth = qt_depthForFormat(format);
584 QImageData::ImageSizeParameters szp =
585 QImageData::calculateImageParameters(size.width(), size.height(), depth);
586 if (!szp.isValid())
587 return false;
588 const qsizetype mb = szp.totalSize >> 20;
589 if (mb > mbLimit || (mb == mbLimit && szp.totalSize % (1 << 20))) {
590 qCWarning(lcImageIo, "QImageIOHandler: Rejecting image as it exceeds the current "
591 "allocation limit of %i megabytes", mbLimit);
592 return false;
593 }
594 }
595 *image = QImage(size, format);
596 }
597 return !image->isNull();
598}
599
600#ifndef QT_NO_IMAGEFORMATPLUGIN
601
602/*!
603 Constructs an image plugin with the given \a parent. This is
604 invoked automatically by the moc generated code that exports the plugin.
605*/
606QImageIOPlugin::QImageIOPlugin(QObject *parent)
607 : QObject(parent)
608{
609}
610
611/*!
612 Destroys the picture format plugin.
613
614 You never have to call this explicitly. Qt destroys a plugin
615 automatically when it is no longer used.
616*/
617QImageIOPlugin::~QImageIOPlugin()
618{
619}
620
621/*! \fn QImageIOPlugin::capabilities(QIODevice *device, const QByteArray &format) const
622
623 Returns the capabilities of the plugin, based on the data in \a
624 device and the format \a format. If \a device is \c 0, it should
625 simply report whether the format can be read or written. Otherwise,
626 it should attempt to determine whether the given format (or any
627 format supported by the plugin if \a format is empty) can be read
628 from or written to \a device. It should do this without changing
629 the state of \a device (typically by using QIODevice::peek()).
630
631 For example, if the QImageIOPlugin supports the BMP format, \a format
632 is either empty or \c "bmp", and the data in the device starts with the
633 characters \c "BM", this function should return \l CanRead. If \a format
634 is \c "bmp", \a device is \c 0 and the handler supports both reading and
635 writing, this function should return \l CanRead | \l CanWrite.
636
637 Format names are always given in lower case.
638*/
639
640/*!
641 \fn QImageIOHandler *QImageIOPlugin::create(QIODevice *device, const QByteArray &format) const
642
643 Creates and returns a QImageIOHandler subclass, with \a device
644 and \a format set. The \a format must come from the values listed
645 in the \c "Keys" entry in the plugin metadata, or be empty. If it is
646 empty, the data in \a device must have been recognized by the
647 capabilities() method (with a likewise empty format).
648
649 Format names are always given in lower case.
650*/
651
652#endif // QT_NO_IMAGEFORMATPLUGIN
653
654QT_END_NAMESPACE
655