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

source code of qtbase/src/gui/image/qimageiohandler.cpp