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
138/*! \enum QImageIOHandler::Transformation
139 \since 5.5
140
141 This enum describes the different transformations or orientations
142 supported by some image formats, usually through EXIF.
143
144 \value TransformationNone No transformation should be applied.
145
146 \value TransformationMirror Mirror the image horizontally.
147
148 \value TransformationFlip Mirror the image vertically.
149
150 \value TransformationRotate180 Rotate the image 180 degrees.
151 This is the same as mirroring it both horizontally and vertically.
152
153 \value TransformationRotate90 Rotate the image 90 degrees.
154
155 \value TransformationMirrorAndRotate90 Mirror the image horizontally
156 and then rotate it 90 degrees.
157
158 \value TransformationFlipAndRotate90 Mirror the image vertically
159 and then rotate it 90 degrees.
160
161 \value TransformationRotate270 Rotate the image 270 degrees.
162 This is the same as mirroring it both horizontally, vertically and
163 then rotating it 90 degrees.
164
165 \sa QImageReader::transformation(), QImageReader::setAutoTransform(), QImageWriter::setTransformation()
166*/
167
168/*!
169 \class QImageIOPlugin
170 \inmodule QtGui
171 \brief The QImageIOPlugin class defines an interface for writing
172 an image format plugin.
173 \reentrant
174
175 \ingroup plugins
176
177 QImageIOPlugin is a factory for creating QImageIOHandler objects,
178 which are used internally by QImageReader and QImageWriter to add
179 support for different image formats to Qt.
180
181 Writing an image I/O plugin is achieved by subclassing this
182 base class, reimplementing the pure virtual functions capabilities()
183 and create(), and exporting the class with the
184 Q_PLUGIN_METADATA() macro. See \l{How to Create Qt Plugins} for details.
185
186 An image format plugin can support three capabilities: reading (\l
187 CanRead), writing (\l CanWrite) and \e incremental reading (\l
188 CanReadIncremental). Reimplement capabilities() in your subclass to
189 expose the capabilities of your image format.
190
191 create() should create an instance of your QImageIOHandler
192 subclass, with the provided device and format properly set, and
193 return this handler.
194
195 The json metadata file for the plugin needs to contain information
196 about the image formats the plugins supports, together with the
197 corresponding MIME types (one for each format). For a jpeg plugin, this
198 could, for example, look as follows:
199
200 \code
201 {
202 "Keys": [ "jpg", "jpeg" ],
203 "MimeTypes": [ "image/jpeg", "image/jpeg" ]
204 }
205 \endcode
206
207 Different plugins can support different capabilities. For example,
208 you may have one plugin that supports reading the GIF format, and
209 another that supports writing. Qt will select the correct plugin
210 for the job, depending on the return value of capabilities(). If
211 several plugins support the same capability, Qt will select one
212 arbitrarily.
213
214 \sa QImageIOHandler, {How to Create Qt Plugins}
215*/
216
217/*!
218 \enum QImageIOPlugin::Capability
219
220 This enum describes the capabilities of a QImageIOPlugin.
221
222 \value CanRead The plugin can read images.
223 \value CanWrite The plugin can write images.
224 \value CanReadIncremental The plugin can read images incrementally.
225*/
226
227#include "qimageiohandler.h"
228#include "qimage_p.h"
229
230#include <qbytearray.h>
231#include <qimagereader.h>
232#include <qloggingcategory.h>
233#include <qvariant.h>
234
235QT_BEGIN_NAMESPACE
236
237Q_LOGGING_CATEGORY(lcImageIo, "qt.gui.imageio")
238
239class QIODevice;
240
241class QImageIOHandlerPrivate
242{
243 Q_DECLARE_PUBLIC(QImageIOHandler)
244public:
245 QImageIOHandlerPrivate(QImageIOHandler *q);
246 virtual ~QImageIOHandlerPrivate();
247
248 QIODevice *device;
249 mutable QByteArray format;
250
251 QImageIOHandler *q_ptr;
252};
253
254QImageIOHandlerPrivate::QImageIOHandlerPrivate(QImageIOHandler *q)
255{
256 device = nullptr;
257 q_ptr = q;
258}
259
260QImageIOHandlerPrivate::~QImageIOHandlerPrivate()
261{
262}
263
264/*!
265 Constructs a QImageIOHandler object.
266*/
267QImageIOHandler::QImageIOHandler()
268 : d_ptr(new QImageIOHandlerPrivate(this))
269{
270}
271
272/*! \internal
273
274 Constructs a QImageIOHandler object, using the private member \a
275 dd.
276*/
277QImageIOHandler::QImageIOHandler(QImageIOHandlerPrivate &dd)
278 : d_ptr(&dd)
279{
280}
281
282/*!
283 Destructs the QImageIOHandler object.
284*/
285QImageIOHandler::~QImageIOHandler()
286{
287}
288
289/*!
290 Sets the device of the QImageIOHandler to \a device. The image
291 handler will use this device when reading and writing images.
292
293 The device can only be set once and must be set before calling
294 canRead(), read(), write(), etc. If you need to read multiple
295 files, construct multiple instances of the appropriate
296 QImageIOHandler subclass.
297
298 \sa device()
299*/
300void QImageIOHandler::setDevice(QIODevice *device)
301{
302 Q_D(QImageIOHandler);
303 d->device = device;
304}
305
306/*!
307 Returns the device currently assigned to the QImageIOHandler. If
308 not device has been assigned, \nullptr is returned.
309*/
310QIODevice *QImageIOHandler::device() const
311{
312 Q_D(const QImageIOHandler);
313 return d->device;
314}
315
316/*!
317 Sets the format of the QImageIOHandler to \a format. The format is
318 most useful for handlers that support multiple image formats.
319
320 \sa format()
321*/
322void QImageIOHandler::setFormat(const QByteArray &format)
323{
324 Q_D(QImageIOHandler);
325 d->format = format;
326}
327
328/*!
329 Sets the format of the QImageIOHandler to \a format. The format is
330 most useful for handlers that support multiple image formats.
331
332 This function is declared const so that it can be called from canRead().
333
334 \sa format()
335*/
336void QImageIOHandler::setFormat(const QByteArray &format) const
337{
338 Q_D(const QImageIOHandler);
339 d->format = format;
340}
341
342/*!
343 Returns the format that is currently assigned to
344 QImageIOHandler. If no format has been assigned, an empty string
345 is returned.
346
347 \sa setFormat()
348*/
349QByteArray QImageIOHandler::format() const
350{
351 Q_D(const QImageIOHandler);
352 return d->format;
353}
354
355/*!
356 \fn bool QImageIOHandler::read(QImage *image)
357
358 Read an image from the device, and stores it in \a image.
359 Returns \c true if the image is successfully read; otherwise returns
360 false.
361
362 For image formats that support incremental loading, and for animation
363 formats, the image handler can assume that \a image points to the
364 previous frame.
365
366 \sa canRead()
367*/
368
369/*!
370 \fn bool QImageIOHandler::canRead() const
371
372 Returns \c true if an image can be read from the device (i.e., the
373 image format is supported, the device can be read from and the
374 initial header information suggests that the image can be read);
375 otherwise returns \c false.
376
377 When reimplementing canRead(), make sure that the I/O device
378 (device()) is left in its original state (e.g., by using peek()
379 rather than read()).
380
381 \sa read(), QIODevice::peek()
382*/
383
384/*!
385 Writes the image \a image to the assigned device. Returns \c true on
386 success; otherwise returns \c false.
387
388 The default implementation does nothing, and simply returns \c false.
389*/
390bool QImageIOHandler::write(const QImage &image)
391{
392 Q_UNUSED(image);
393 return false;
394}
395
396/*!
397 Sets the option \a option with the value \a value.
398
399 \sa option(), ImageOption
400*/
401void QImageIOHandler::setOption(ImageOption option, const QVariant &value)
402{
403 Q_UNUSED(option);
404 Q_UNUSED(value);
405}
406
407/*!
408 Returns the value assigned to \a option as a QVariant. The type of
409 the value depends on the option. For example, option(Size) returns
410 a QSize variant.
411
412 \sa setOption(), supportsOption()
413*/
414QVariant QImageIOHandler::option(ImageOption option) const
415{
416 Q_UNUSED(option);
417 return QVariant();
418}
419
420/*!
421 Returns \c true if the QImageIOHandler supports the option \a option;
422 otherwise returns \c false. For example, if the QImageIOHandler
423 supports the \l Size option, supportsOption(Size) must return
424 true.
425
426 \sa setOption(), option()
427*/
428bool QImageIOHandler::supportsOption(ImageOption option) const
429{
430 Q_UNUSED(option);
431 return false;
432}
433
434/*!
435 For image formats that support animation, this function returns
436 the sequence number of the current image in the animation. If
437 this function is called before any image is read(), -1 is
438 returned. The number of the first image in the sequence is 0.
439
440 If the image format does not support animation, 0 is returned.
441
442 \sa read()
443*/
444int QImageIOHandler::currentImageNumber() const
445{
446 return 0;
447}
448
449/*!
450 Returns the rect of the current image. If no rect is defined for the
451 image, and empty QRect() is returned.
452
453 This function is useful for animations, where only parts of the frame
454 may be updated at a time.
455*/
456QRect QImageIOHandler::currentImageRect() const
457{
458 return QRect();
459}
460
461/*!
462 For image formats that support animation, this function returns
463 the number of images in the animation. If the image format does
464 not support animation, or if it is unable to determine the number
465 of images, 0 is returned.
466
467 The default implementation returns 1 if canRead() returns \c true;
468 otherwise 0 is returned.
469*/
470int QImageIOHandler::imageCount() const
471{
472 return canRead() ? 1 : 0;
473}
474
475/*!
476 For image formats that support animation, this function jumps to the
477 next image.
478
479 The default implementation does nothing, and returns \c false.
480*/
481bool QImageIOHandler::jumpToNextImage()
482{
483 return false;
484}
485
486/*!
487 For image formats that support animation, this function jumps to the image
488 whose sequence number is \a imageNumber. The next call to read() will
489 attempt to read this image.
490
491 The default implementation does nothing, and returns \c false.
492*/
493bool QImageIOHandler::jumpToImage(int imageNumber)
494{
495 Q_UNUSED(imageNumber);
496 return false;
497}
498
499/*!
500 For image formats that support animation, this function returns
501 the number of times the animation should loop. If the image format
502 does not support animation, 0 is returned.
503*/
504int QImageIOHandler::loopCount() const
505{
506 return 0;
507}
508
509/*!
510 For image formats that support animation, this function returns
511 the number of milliseconds to wait until reading the next
512 image. If the image format does not support animation, 0 is
513 returned.
514*/
515int QImageIOHandler::nextImageDelay() const
516{
517 return 0;
518}
519
520/*!
521 \since 6.0
522
523 This is a convenience method for the reading function in subclasses. Image
524 format handlers must reject loading an image if the required allocation
525 would exceeed the current allocation limit. This function checks the
526 parameters and limit, and does the allocation if it is valid and required.
527 Upon successful return, \a image will be a valid, detached QImage of the
528 given \a size and \a format.
529
530 \sa QImageReader::allocationLimit()
531*/
532bool QImageIOHandler::allocateImage(QSize size, QImage::Format format, QImage *image)
533{
534 Q_ASSERT(image);
535 if (size.isEmpty() || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
536 return false;
537
538 if (image->size() == size && image->format() == format) {
539 image->detach();
540 } else {
541 if (const int mbLimit = QImageReader::allocationLimit()) {
542 qsizetype depth = qMax(a: qt_depthForFormat(format), b: 32); // Effective gui depth = 32
543 QImageData::ImageSizeParameters szp =
544 QImageData::calculateImageParameters(width: size.width(), height: size.height(), depth);
545 if (!szp.isValid())
546 return false;
547 const qsizetype mb = szp.totalSize >> 20;
548 if (mb > mbLimit || (mb == mbLimit && szp.totalSize % (1 << 20))) {
549 qCWarning(lcImageIo, "QImageIOHandler: Rejecting image as it exceeds the current "
550 "allocation limit of %i megabytes", mbLimit);
551 return false;
552 }
553 }
554 *image = QImage(size, format);
555 }
556 return !image->isNull();
557}
558
559#ifndef QT_NO_IMAGEFORMATPLUGIN
560
561/*!
562 Constructs an image plugin with the given \a parent. This is
563 invoked automatically by the moc generated code that exports the plugin.
564*/
565QImageIOPlugin::QImageIOPlugin(QObject *parent)
566 : QObject(parent)
567{
568}
569
570/*!
571 Destroys the picture format plugin.
572
573 You never have to call this explicitly. Qt destroys a plugin
574 automatically when it is no longer used.
575*/
576QImageIOPlugin::~QImageIOPlugin()
577{
578}
579
580/*! \fn QImageIOPlugin::capabilities(QIODevice *device, const QByteArray &format) const
581
582 Returns the capabilities of the plugin, based on the data in \a
583 device and the format \a format. If \a device is \c 0, it should
584 simply report whether the format can be read or written. Otherwise,
585 it should attempt to determine whether the given format (or any
586 format supported by the plugin if \a format is empty) can be read
587 from or written to \a device. It should do this without changing
588 the state of \a device (typically by using QIODevice::peek()).
589
590 For example, if the QImageIOPlugin supports the BMP format, \a format
591 is either empty or \c "bmp", and the data in the device starts with the
592 characters \c "BM", this function should return \l CanRead. If \a format
593 is \c "bmp", \a device is \c 0 and the handler supports both reading and
594 writing, this function should return \l CanRead | \l CanWrite.
595
596 Format names are always given in lower case.
597*/
598
599/*!
600 \fn QImageIOHandler *QImageIOPlugin::create(QIODevice *device, const QByteArray &format) const
601
602 Creates and returns a QImageIOHandler subclass, with \a device
603 and \a format set. The \a format must come from the values listed
604 in the \c "Keys" entry in the plugin metadata, or be empty. If it is
605 empty, the data in \a device must have been recognized by the
606 capabilities() method (with a likewise empty format).
607
608 Format names are always given in lower case.
609*/
610
611#endif // QT_NO_IMAGEFORMATPLUGIN
612
613QT_END_NAMESPACE
614
615#include "moc_qimageiohandler.cpp"
616

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