Coverage Report

Created: 2026-06-07 08:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qtbase/src/gui/image/qimageiohandler.cpp
Line
Count
Source
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
// Qt-Security score:significant reason:default
227
228
#include "qimageiohandler.h"
229
#include "qimage_p.h"
230
231
#include <qbytearray.h>
232
#include <qimagereader.h>
233
#include <qloggingcategory.h>
234
#include <qvariant.h>
235
236
QT_BEGIN_NAMESPACE
237
238
Q_LOGGING_CATEGORY(lcImageIo, "qt.gui.imageio")
239
240
class QIODevice;
241
242
class QImageIOHandlerPrivate
243
{
244
0
    Q_DECLARE_PUBLIC(QImageIOHandler)
Unexecuted instantiation: QImageIOHandlerPrivate::q_func()
Unexecuted instantiation: QImageIOHandlerPrivate::q_func() const
245
0
public:
246
0
    QImageIOHandlerPrivate(QImageIOHandler *q);
247
0
    virtual ~QImageIOHandlerPrivate();
248
0
249
0
    QIODevice *device;
250
0
    mutable QByteArray format;
251
0
252
0
    QImageIOHandler *q_ptr;
253
0
};
254
0
255
0
QImageIOHandlerPrivate::QImageIOHandlerPrivate(QImageIOHandler *q)
256
0
{
257
0
    device = nullptr;
258
0
    q_ptr = q;
259
0
}
260
261
QImageIOHandlerPrivate::~QImageIOHandlerPrivate()
262
0
{
263
0
}
264
265
/*!
266
    Constructs a QImageIOHandler object.
267
*/
268
QImageIOHandler::QImageIOHandler()
269
0
    : d_ptr(new QImageIOHandlerPrivate(this))
270
0
{
271
0
}
272
273
/*! \internal
274
275
    Constructs a QImageIOHandler object, using the private member \a
276
    dd.
277
*/
278
QImageIOHandler::QImageIOHandler(QImageIOHandlerPrivate &dd)
279
0
    : d_ptr(&dd)
280
0
{
281
0
}
282
283
/*!
284
    Destructs the QImageIOHandler object.
285
*/
286
QImageIOHandler::~QImageIOHandler()
287
0
{
288
0
}
289
290
/*!
291
    Sets the device of the QImageIOHandler to \a device. The image
292
    handler will use this device when reading and writing images.
293
294
    The device can only be set once and must be set before calling
295
    canRead(), read(), write(), etc. If you need to read multiple
296
    files, construct multiple instances of the appropriate
297
    QImageIOHandler subclass.
298
299
    \sa device()
300
*/
301
void QImageIOHandler::setDevice(QIODevice *device)
302
0
{
303
0
    Q_D(QImageIOHandler);
304
0
    d->device = device;
305
0
}
306
307
/*!
308
    Returns the device currently assigned to the QImageIOHandler. If
309
    not device has been assigned, \nullptr is returned.
310
*/
311
QIODevice *QImageIOHandler::device() const
312
0
{
313
0
    Q_D(const QImageIOHandler);
314
0
    return d->device;
315
0
}
316
317
/*!
318
    Sets the format of the QImageIOHandler to \a format. The format is
319
    most useful for handlers that support multiple image formats.
320
321
    \sa format()
322
*/
323
void QImageIOHandler::setFormat(const QByteArray &format)
324
0
{
325
0
    Q_D(QImageIOHandler);
326
0
    d->format = format;
327
0
}
328
329
/*!
330
    Sets the format of the QImageIOHandler to \a format. The format is
331
    most useful for handlers that support multiple image formats.
332
333
    This function is declared const so that it can be called from canRead().
334
335
    \sa format()
336
*/
337
void QImageIOHandler::setFormat(const QByteArray &format) const
338
0
{
339
0
    Q_D(const QImageIOHandler);
340
0
    d->format = format;
341
0
}
342
343
/*!
344
    Returns the format that is currently assigned to
345
    QImageIOHandler. If no format has been assigned, an empty string
346
    is returned.
347
348
    \sa setFormat()
349
*/
350
QByteArray QImageIOHandler::format() const
351
0
{
352
0
    Q_D(const QImageIOHandler);
353
0
    return d->format;
354
0
}
355
356
/*!
357
    \fn bool QImageIOHandler::read(QImage *image)
358
359
    Read an image from the device, and stores it in \a image.
360
    Returns \c true if the image is successfully read; otherwise returns
361
    false.
362
363
    For image formats that support incremental loading, and for animation
364
    formats, the image handler can assume that \a image points to the
365
    previous frame.
366
367
    \sa canRead()
368
*/
369
370
/*!
371
    \fn bool QImageIOHandler::canRead() const
372
373
    Returns \c true if an image can be read from the device (i.e., the
374
    image format is supported, the device can be read from and the
375
    initial header information suggests that the image can be read);
376
    otherwise returns \c false.
377
378
    When reimplementing canRead(), make sure that the I/O device
379
    (device()) is left in its original state (e.g., by using peek()
380
    rather than read()).
381
382
    \sa read(), QIODevice::peek()
383
*/
384
385
/*!
386
    Writes the image \a image to the assigned device. Returns \c true on
387
    success; otherwise returns \c false.
388
389
    The default implementation does nothing, and simply returns \c false.
390
*/
391
bool QImageIOHandler::write(const QImage &image)
392
0
{
393
0
    Q_UNUSED(image);
394
0
    return false;
395
0
}
396
397
/*!
398
    Sets the option \a option with the value \a value.
399
400
    \sa option(), ImageOption
401
*/
402
void QImageIOHandler::setOption(ImageOption option, const QVariant &value)
403
0
{
404
0
    Q_UNUSED(option);
405
0
    Q_UNUSED(value);
406
0
}
407
408
/*!
409
    Returns the value assigned to \a option as a QVariant. The type of
410
    the value depends on the option. For example, option(Size) returns
411
    a QSize variant.
412
413
    \sa setOption(), supportsOption()
414
*/
415
QVariant QImageIOHandler::option(ImageOption option) const
416
0
{
417
0
    Q_UNUSED(option);
418
0
    return QVariant();
419
0
}
420
421
/*!
422
    Returns \c true if the QImageIOHandler supports the option \a option;
423
    otherwise returns \c false. For example, if the QImageIOHandler
424
    supports the \l Size option, supportsOption(Size) must return
425
    true.
426
427
    \sa setOption(), option()
428
*/
429
bool QImageIOHandler::supportsOption(ImageOption option) const
430
0
{
431
0
    Q_UNUSED(option);
432
0
    return false;
433
0
}
434
435
/*!
436
    For image formats that support animation, this function returns
437
    the sequence number of the current image in the animation. If
438
    this function is called before any image is read(), -1 is
439
    returned. The number of the first image in the sequence is 0.
440
441
    If the image format does not support animation, 0 is returned.
442
443
    \sa read()
444
*/
445
int QImageIOHandler::currentImageNumber() const
446
0
{
447
0
    return 0;
448
0
}
449
450
/*!
451
    Returns the rect of the current image. If no rect is defined for the
452
    image, and empty QRect() is returned.
453
454
    This function is useful for animations, where only parts of the frame
455
    may be updated at a time.
456
*/
457
QRect QImageIOHandler::currentImageRect() const
458
0
{
459
0
    return QRect();
460
0
}
461
462
/*!
463
    For image formats that support animation, this function returns
464
    the number of images in the animation. If the image format does
465
    not support animation, or if it is unable to determine the number
466
    of images, 0 is returned.
467
468
    The default implementation returns 1 if canRead() returns \c true;
469
    otherwise 0 is returned.
470
*/
471
int QImageIOHandler::imageCount() const
472
0
{
473
0
    return canRead() ? 1 : 0;
474
0
}
475
476
/*!
477
   For image formats that support animation, this function jumps to the
478
   next image.
479
480
   The default implementation does nothing, and returns \c false.
481
*/
482
bool QImageIOHandler::jumpToNextImage()
483
0
{
484
0
    return false;
485
0
}
486
487
/*!
488
   For image formats that support animation, this function jumps to the image
489
   whose sequence number is \a imageNumber. The next call to read() will
490
   attempt to read this image.
491
492
   The default implementation does nothing, and returns \c false.
493
*/
494
bool QImageIOHandler::jumpToImage(int imageNumber)
495
0
{
496
0
    Q_UNUSED(imageNumber);
497
0
    return false;
498
0
}
499
500
/*!
501
    For image formats that support animation, this function returns
502
    the number of times the animation should loop. If the image format
503
    does not support animation, 0 is returned.
504
*/
505
int QImageIOHandler::loopCount() const
506
0
{
507
0
    return 0;
508
0
}
509
510
/*!
511
    For image formats that support animation, this function returns
512
    the number of milliseconds to wait until reading the next
513
    image. If the image format does not support animation, 0 is
514
    returned.
515
*/
516
int QImageIOHandler::nextImageDelay() const
517
0
{
518
0
    return 0;
519
0
}
520
521
/*!
522
    \since 6.0
523
524
    This is a convenience method for the reading function in subclasses. Image
525
    format handlers must reject loading an image if the required allocation
526
    would exceeed the current allocation limit. This function checks the
527
    parameters and limit, and does the allocation if it is valid and required.
528
    Upon successful return, \a image will be a valid, detached QImage of the
529
    given \a size and \a format.
530
531
    \sa QImageReader::allocationLimit()
532
*/
533
bool QImageIOHandler::allocateImage(QSize size, QImage::Format format, QImage *image)
534
0
{
535
0
    Q_ASSERT(image);
536
0
    if (size.isEmpty() || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
537
0
        return false;
538
539
0
    if (image->size() == size && image->format() == format) {
540
0
        image->detach();
541
0
    } else {
542
0
        if (const int mbLimit = QImageReader::allocationLimit()) {
543
0
            qsizetype depth = qMax(qt_depthForFormat(format), 32); // Effective gui depth = 32
544
0
            QImageData::ImageSizeParameters szp =
545
0
                    QImageData::calculateImageParameters(size.width(), size.height(), depth);
546
0
            if (!szp.isValid())
547
0
                return false;
548
0
            const qsizetype mb = szp.totalSize >> 20;
549
0
            if (mb > mbLimit || (mb == mbLimit && szp.totalSize % (1 << 20))) {
550
0
                qCWarning(lcImageIo, "QImageIOHandler: Rejecting image as it exceeds the current "
551
0
                                     "allocation limit of %i megabytes", mbLimit);
552
0
                return false;
553
0
            }
554
0
        }
555
0
        *image = QImage(size, format);
556
0
    }
557
0
    return !image->isNull();
558
0
}
559
560
#ifndef QT_NO_IMAGEFORMATPLUGIN
561
562
/*!
563
    Constructs an image plugin with the given \a parent. This is
564
    invoked automatically by the moc generated code that exports the plugin.
565
*/
566
QImageIOPlugin::QImageIOPlugin(QObject *parent)
567
0
    : QObject(parent)
568
0
{
569
0
}
570
571
/*!
572
    Destroys the picture format plugin.
573
574
    You never have to call this explicitly. Qt destroys a plugin
575
    automatically when it is no longer used.
576
*/
577
QImageIOPlugin::~QImageIOPlugin()
578
0
{
579
0
}
580
581
/*! \fn QImageIOPlugin::capabilities(QIODevice *device, const QByteArray &format) const
582
583
    Returns the capabilities of the plugin, based on the data in \a
584
    device and the format \a format.  If \a device is \c 0, it should
585
    simply report whether the format can be read or written.  Otherwise,
586
    it should attempt to determine whether the given format (or any
587
    format supported by the plugin if \a format is empty) can be read
588
    from or written to \a device.  It should do this without changing
589
    the state of \a device (typically by using QIODevice::peek()).
590
591
    For example, if the QImageIOPlugin supports the BMP format, \a format
592
    is either empty or \c "bmp", and the data in the device starts with the
593
    characters \c "BM", this function should return \l CanRead. If \a format
594
    is \c "bmp", \a device is \c 0 and the handler supports both reading and
595
    writing, this function should return \l CanRead | \l CanWrite.
596
597
    Format names are always given in lower case.
598
*/
599
600
/*!
601
    \fn QImageIOHandler *QImageIOPlugin::create(QIODevice *device, const QByteArray &format) const
602
603
    Creates and returns a QImageIOHandler subclass, with \a device
604
    and \a format set. The \a format must come from the values listed
605
    in the \c "Keys" entry in the plugin metadata, or be empty.  If it is
606
    empty, the data in \a device must have been recognized by the
607
    capabilities() method (with a likewise empty format).
608
609
    Format names are always given in lower case.
610
*/
611
612
#endif // QT_NO_IMAGEFORMATPLUGIN
613
614
QT_END_NAMESPACE
615
616
#include "moc_qimageiohandler.cpp"