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
qimage.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 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#include "qimage.h"
6
7#include "qbuffer.h"
8#include "qdatastream.h"
10#include "qfloat16.h"
11#include "qmap.h"
12#include "qtransform.h"
13#include "qimagereader.h"
14#include "qimagewriter.h"
15#include "qrgbafloat.h"
16#include "qstringlist.h"
17#include "qvariant.h"
19#include <qpa/qplatformintegration.h>
20#include <private/qguiapplication_p.h>
21#include <ctype.h>
22#include <stdlib.h>
23#include <limits.h>
24#include <qpa/qplatformpixmap.h>
25#include <qalloc.h>
26#include <private/qcolorspace_p.h>
27#include <private/qcolortransform_p.h>
28#include <private/qmemrotate_p.h>
29#include <private/qimagescale_p.h>
30#include <private/qpixellayout_p.h>
31#include <private/qsimd_p.h>
32
33#include <qhash.h>
34
35#include <private/qpaintengine_raster_p.h>
36
37#include <private/qimage_p.h>
38#include <private/qfont_p.h>
39
40#if QT_CONFIG(qtgui_threadpool)
41#include <private/qlatch_p.h>
42#include <qthreadpool.h>
43#include <private/qthreadpool_p.h>
44#endif
45
46#include <qtgui_tracepoints_p.h>
47
48#include <memory>
49
50#define QT_XFORM_TYPE_MSBFIRST 0
51#define QT_XFORM_TYPE_LSBFIRST 1
52
54class QCmyk32;
55
56using namespace Qt::StringLiterals;
57
58// MSVC 19.28 does show spurious warning "C4723: potential divide by 0" for code that divides
59// by height() in release builds. Anyhow, all the code paths in this file are only executed
60// for valid QImage's, where height() cannot be 0. Therefore disable the warning.
61QT_WARNING_DISABLE_MSVC(4723)
62
63#if defined(Q_CC_DEC) && defined(__alpha) && (__DECCXX_VER-0 >= 50190001)
64#pragma message disable narrowptr
65#endif
66
67
68#define QIMAGE_SANITYCHECK_MEMORY(image)
69 if ((image).isNull()) {
70 qWarning("QImage: out of memory, returning null image");
71 return QImage();
72 }
73
74Q_TRACE_PREFIX(qtgui,
75 "#include <qimagereader.h>"
76);
77
79"ENUM { } QImage::Format;" \
80"FLAGS { } Qt::ImageConversionFlags;"
81);
82
83Q_TRACE_PARAM_REPLACE(Qt::AspectRatioMode, int);
84Q_TRACE_PARAM_REPLACE(Qt::TransformationMode, int);
85
86static QImage rotated90(const QImage &src);
87static QImage rotated180(const QImage &src);
88static QImage rotated270(const QImage &src);
89
91{
92 Q_CONSTINIT static QBasicAtomicInt serial = Q_BASIC_ATOMIC_INITIALIZER(0);
93 return 1 + serial.fetchAndAddRelaxed(1);
94}
95
96QImageData::QImageData()
97 : ref(0), width(0), height(0), depth(0), nbytes(0), devicePixelRatio(1.0), data(nullptr),
98 format(QImage::Format_ARGB32), bytes_per_line(0),
99 ser_no(next_qimage_serial_number()),
100 detach_no(0),
101 offset(0, 0), own_data(true), ro_data(false), has_alpha_clut(false),
102 is_cached(false), cleanupFunction(nullptr), cleanupInfo(nullptr),
103 paintEngine(nullptr)
104{
105 QPoint dpis = qt_defaultDpis();
106 dpmx = dpis.x() * 100 / qreal(2.54);
107 dpmy = dpis.y() * 100 / qreal(2.54);
108}
109
110/*! \fn QImageData * QImageData::create(const QSize &size, QImage::Format format)
111
112 \internal
113
114 Creates a new image data.
115 Returns \nullptr if invalid parameters are give or anything else failed.
116*/
117QImageData * Q_TRACE_INSTRUMENT(qtgui) QImageData::create(const QSize &size, QImage::Format format)
118{
119 if (size.isEmpty() || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
120 return nullptr; // invalid parameter(s)
121
122 Q_TRACE_SCOPE(QImageData_create, size, format);
123
124 int width = size.width();
125 int height = size.height();
126 int depth = qt_depthForFormat(format);
127 auto params = calculateImageParameters(width, height, depth);
128 if (!params.isValid())
129 return nullptr;
130
131 auto d = std::make_unique<QImageData>();
132
133 switch (format) {
134 case QImage::Format_Mono:
135 case QImage::Format_MonoLSB:
136 d->colortable.resize(2);
137 d->colortable[0] = QColor(Qt::black).rgba();
138 d->colortable[1] = QColor(Qt::white).rgba();
139 break;
140 default:
141 break;
142 }
143
144 d->width = width;
145 d->height = height;
146 d->depth = depth;
147 d->format = format;
148 d->has_alpha_clut = false;
149 d->is_cached = false;
150
151 d->bytes_per_line = params.bytesPerLine;
152 d->nbytes = params.totalSize;
153 d->data = (uchar *)malloc(d->nbytes);
154
155 if (!d->data)
156 return nullptr;
157
158 d->ref.ref();
159 return d.release();
160}
161
162QImageData::~QImageData()
163{
164 if (cleanupFunction)
165 cleanupFunction(cleanupInfo);
166 if (is_cached)
167 QImagePixmapCleanupHooks::executeImageHooks((((qint64) ser_no) << 32) | ((qint64) detach_no));
168 delete paintEngine;
169 if (data && own_data)
170 QtPrivate::sizedFree(data, nbytes);
171 data = nullptr;
172}
173
174#if defined(_M_ARM) && defined(_MSC_VER)
175#pragma optimize("", off)
176#endif
177
178bool QImageData::checkForAlphaPixels() const
179{
180 bool has_alpha_pixels = false;
181
182 switch (format) {
183
184 case QImage::Format_Mono:
185 case QImage::Format_MonoLSB:
186 case QImage::Format_Indexed8:
187 has_alpha_pixels = has_alpha_clut;
188 break;
189 case QImage::Format_Alpha8:
190 has_alpha_pixels = true;
191 break;
192 case QImage::Format_ARGB32:
193 case QImage::Format_ARGB32_Premultiplied: {
194 const uchar *bits = data;
195 for (int y=0; y<height && !has_alpha_pixels; ++y) {
196 uint alphaAnd = 0xff000000;
197 for (int x=0; x<width; ++x)
198 alphaAnd &= reinterpret_cast<const uint*>(bits)[x];
199 has_alpha_pixels = (alphaAnd != 0xff000000);
200 bits += bytes_per_line;
201 }
202 } break;
203
204 case QImage::Format_RGBA8888:
205 case QImage::Format_RGBA8888_Premultiplied: {
206 const uchar *bits = data;
207 for (int y=0; y<height && !has_alpha_pixels; ++y) {
208 uchar alphaAnd = 0xff;
209 for (int x=0; x<width; ++x)
210 alphaAnd &= bits[x * 4+ 3];
211 has_alpha_pixels = (alphaAnd != 0xff);
212 bits += bytes_per_line;
213 }
214 } break;
215
216 case QImage::Format_A2BGR30_Premultiplied:
217 case QImage::Format_A2RGB30_Premultiplied: {
218 const uchar *bits = data;
219 for (int y=0; y<height && !has_alpha_pixels; ++y) {
220 uint alphaAnd = 0xc0000000;
221 for (int x=0; x<width; ++x)
222 alphaAnd &= reinterpret_cast<const uint*>(bits)[x];
223 has_alpha_pixels = (alphaAnd != 0xc0000000);
224 bits += bytes_per_line;
225 }
226 } break;
227
228 case QImage::Format_ARGB8555_Premultiplied:
229 case QImage::Format_ARGB8565_Premultiplied: {
230 const uchar *bits = data;
231 const uchar *end_bits = data + bytes_per_line;
232
233 for (int y=0; y<height && !has_alpha_pixels; ++y) {
234 uchar alphaAnd = 0xff;
235 while (bits < end_bits) {
236 alphaAnd &= bits[0];
237 bits += 3;
238 }
239 has_alpha_pixels = (alphaAnd != 0xff);
240 bits = end_bits;
241 end_bits += bytes_per_line;
242 }
243 } break;
244
245 case QImage::Format_ARGB6666_Premultiplied: {
246 const uchar *bits = data;
247 const uchar *end_bits = data + bytes_per_line;
248
249 for (int y=0; y<height && !has_alpha_pixels; ++y) {
250 uchar alphaAnd = 0xfc;
251 while (bits < end_bits) {
252 alphaAnd &= bits[0];
253 bits += 3;
254 }
255 has_alpha_pixels = (alphaAnd != 0xfc);
256 bits = end_bits;
257 end_bits += bytes_per_line;
258 }
259 } break;
260
261 case QImage::Format_ARGB4444_Premultiplied: {
262 const uchar *bits = data;
263 for (int y=0; y<height && !has_alpha_pixels; ++y) {
264 ushort alphaAnd = 0xf000;
265 for (int x=0; x<width; ++x)
266 alphaAnd &= reinterpret_cast<const ushort*>(bits)[x];
267 has_alpha_pixels = (alphaAnd != 0xf000);
268 bits += bytes_per_line;
269 }
270 } break;
271 case QImage::Format_RGBA64:
272 case QImage::Format_RGBA64_Premultiplied: {
273 uchar *bits = data;
274 for (int y=0; y<height && !has_alpha_pixels; ++y) {
275 for (int x=0; x<width; ++x) {
276 has_alpha_pixels |= !(((QRgba64 *)bits)[x].isOpaque());
277 }
278 bits += bytes_per_line;
279 }
280 } break;
281 case QImage::Format_RGBA16FPx4:
282 case QImage::Format_RGBA16FPx4_Premultiplied: {
283 uchar *bits = data;
284 for (int y = 0; y < height && !has_alpha_pixels; ++y) {
285 for (int x = 0; x < width; ++x)
286 has_alpha_pixels |= ((qfloat16 *)bits)[x * 4 + 3] < 1.0f;
287 bits += bytes_per_line;
288 }
289 } break;
290 case QImage::Format_RGBA32FPx4:
291 case QImage::Format_RGBA32FPx4_Premultiplied: {
292 uchar *bits = data;
293 for (int y = 0; y < height && !has_alpha_pixels; ++y) {
294 for (int x = 0; x < width; ++x)
295 has_alpha_pixels |= ((float *)bits)[x * 4 + 3] < 1.0f;
296 bits += bytes_per_line;
297 }
298 } break;
299
300 case QImage::Format_RGB32:
301 case QImage::Format_RGB16:
302 case QImage::Format_RGB444:
303 case QImage::Format_RGB555:
304 case QImage::Format_RGB666:
305 case QImage::Format_RGB888:
306 case QImage::Format_BGR888:
307 case QImage::Format_RGBX8888:
308 case QImage::Format_BGR30:
309 case QImage::Format_RGB30:
310 case QImage::Format_Grayscale8:
311 case QImage::Format_Grayscale16:
312 case QImage::Format_RGBX64:
313 case QImage::Format_RGBX16FPx4:
314 case QImage::Format_RGBX32FPx4:
315 case QImage::Format_CMYK8888:
316 break;
317 case QImage::Format_Invalid:
318 case QImage::NImageFormats:
319 Q_UNREACHABLE();
320 break;
321 }
322
323 return has_alpha_pixels;
324}
325#if defined(_M_ARM) && defined(_MSC_VER)
326#pragma optimize("", on)
327#endif
328
329/*!
330 \class QImage
331
332 \inmodule QtGui
333 \ingroup painting
334 \ingroup shared
335
336 \reentrant
337
338 \brief The QImage class provides a hardware-independent image
339 representation that allows direct access to the pixel data, and
340 can be used as a paint device.
341
342 Qt provides four classes for handling image data: QImage, QPixmap,
343 QBitmap and QPicture. QImage is designed and optimized for I/O,
344 and for direct pixel access and manipulation, while QPixmap is
345 designed and optimized for showing images on screen. QBitmap is
346 only a convenience class that inherits QPixmap, ensuring a
347 depth of 1. Finally, the QPicture class is a paint device that
348 records and replays QPainter commands.
349
350 Because QImage is a QPaintDevice subclass, QPainter can be used to
351 draw directly onto images. When using QPainter on a QImage, the
352 painting can be performed in another thread than the current GUI
353 thread.
354
355 The QImage class supports several image formats described by the
356 \l Format enum. These include monochrome, 8-bit, 32-bit and
357 alpha-blended images which are available in all versions of Qt
358 4.x.
359
360 QImage provides a collection of functions that can be used to
361 obtain a variety of information about the image. There are also
362 several functions that enables transformation of the image.
363
364 QImage objects can be passed around by value since the QImage
365 class uses \l{Implicit Data Sharing}{implicit data
366 sharing}. QImage objects can also be streamed and compared.
367
368 \note If you would like to load QImage objects in a static build of Qt,
369 refer to the \l{How to Create Qt Plugins}{Plugin HowTo}.
370
371 \warning Painting on a QImage with the format
372 QImage::Format_Indexed8 or QImage::Format_CMYK8888 is not supported.
373
374 \section1 Reading and Writing Image Files
375
376 QImage provides several ways of loading an image file: The file
377 can be loaded when constructing the QImage object, or by using the
378 load() or loadFromData() functions later on. QImage also provides
379 the static fromData() function, constructing a QImage from the
380 given data. When loading an image, the file name can either refer
381 to an actual file on disk or to one of the application's embedded
382 resources. See \l{The Qt Resource System} overview for details
383 on how to embed images and other resource files in the
384 application's executable.
385
386 Simply call the save() function to save a QImage object.
387
388 The complete list of supported file formats are available through
389 the QImageReader::supportedImageFormats() and
390 QImageWriter::supportedImageFormats() functions. New file formats
391 can be added as plugins. By default, Qt supports the following
392 formats:
393
394 \table
395 \header \li Format \li Description \li Qt's support
396 \row \li BMP \li Windows Bitmap \li Read/write
397 \row \li GIF \li Graphic Interchange Format (optional) \li Read
398 \row \li JPG \li Joint Photographic Experts Group \li Read/write
399 \row \li JPEG \li Joint Photographic Experts Group \li Read/write
400 \row \li PNG \li Portable Network Graphics \li Read/write
401 \row \li PBM \li Portable Bitmap \li Read
402 \row \li PGM \li Portable Graymap \li Read
403 \row \li PPM \li Portable Pixmap \li Read/write
404 \row \li XBM \li X11 Bitmap \li Read/write
405 \row \li XPM \li X11 Pixmap \li Read/write
406 \endtable
407
408 \section1 Image Information
409
410 QImage provides a collection of functions that can be used to
411 obtain a variety of information about the image:
412
413 \table
414 \header
415 \li \li Available Functions
416
417 \row
418 \li Geometry
419 \li
420
421 The size(), width(), height(), dotsPerMeterX(), and
422 dotsPerMeterY() functions provide information about the image size
423 and aspect ratio.
424
425 The rect() function returns the image's enclosing rectangle. The
426 valid() function tells if a given pair of coordinates is within
427 this rectangle. The offset() function returns the number of pixels
428 by which the image is intended to be offset by when positioned
429 relative to other images, which also can be manipulated using the
430 setOffset() function.
431
432 \row
433 \li Colors
434 \li
435
436 The color of a pixel can be retrieved by passing its coordinates
437 to the pixel() function. The pixel() function returns the color
438 as a QRgb value independent of the image's format.
439
440 In case of monochrome and 8-bit images, the colorCount() and
441 colorTable() functions provide information about the color
442 components used to store the image data: The colorTable() function
443 returns the image's entire color table. To obtain a single entry,
444 use the pixelIndex() function to retrieve the pixel index for a
445 given pair of coordinates, then use the color() function to
446 retrieve the color. Note that if you create an 8-bit image
447 manually, you have to set a valid color table on the image as
448 well.
449
450 The hasAlphaChannel() function tells if the image's format
451 respects the alpha channel, or not. The allGray() and
452 isGrayscale() functions tell whether an image's colors are all
453 shades of gray.
454
455 See also the \l {QImage#Pixel Manipulation}{Pixel Manipulation}
456 and \l {QImage#Image Transformations}{Image Transformations}
457 sections.
458
459 \row
460 \li Text
461 \li
462
463 The text() function returns the image text associated with the
464 given text key. An image's text keys can be retrieved using the
465 textKeys() function. Use the setText() function to alter an
466 image's text.
467
468 \row
469 \li Low-level information
470 \li
471
472 The depth() function returns the depth of the image. The supported
473 depths are 1 (monochrome), 8, 16, 24 and 32 bits. The
474 bitPlaneCount() function tells how many of those bits that are
475 used. For more information see the
476 \l {QImage#Image Formats}{Image Formats} section.
477
478 The format(), bytesPerLine(), and sizeInBytes() functions provide
479 low-level information about the data stored in the image.
480
481 The cacheKey() function returns a number that uniquely
482 identifies the contents of this QImage object.
483 \endtable
484
485 \section1 Pixel Manipulation
486
487 The functions used to manipulate an image's pixels depend on the
488 image format. The reason is that monochrome and 8-bit images are
489 index-based and use a color lookup table, while 32-bit images
490 store ARGB values directly. For more information on image formats,
491 see the \l {Image Formats} section.
492
493 In case of a 32-bit image, the setPixel() function can be used to
494 alter the color of the pixel at the given coordinates to any other
495 color specified as an ARGB quadruplet. To make a suitable QRgb
496 value, use the qRgb() (adding a default alpha component to the
497 given RGB values, i.e. creating an opaque color) or qRgba()
498 function. For example:
499
500 \table
501 \header
502 \li {2,1}32-bit
503 \row
504 \li \inlineimage qimage-32bit_scaled.png
505 {3x3 pixel grid with ARGB color values}
506 \li
507 \snippet code/src_gui_image_qimage.cpp 0
508 \endtable
509
510 In case of a 8-bit and monchrome images, the pixel value is only
511 an index from the image's color table. So the setPixel() function
512 can only be used to alter the color of the pixel at the given
513 coordinates to a predefined color from the image's color table,
514 i.e. it can only change the pixel's index value. To alter or add a
515 color to an image's color table, use the setColor() function.
516
517 An entry in the color table is an ARGB quadruplet encoded as an
518 QRgb value. Use the qRgb() and qRgba() functions to make a
519 suitable QRgb value for use with the setColor() function. For
520 example:
521
522 \table
523 \header
524 \li {2,1} 8-bit
525 \row
526 \li \inlineimage qimage-8bit_scaled.png
527 {3x3 pixel grid with indexed colors and color table}
528 \li
529 \snippet code/src_gui_image_qimage.cpp 1
530 \endtable
531
532 For images with more than 8-bit per color-channel. The methods
533 setPixelColor() and pixelColor() can be used to set and get
534 with QColor values.
535
536 QImage also provide the scanLine() function which returns a
537 pointer to the pixel data at the scanline with the given index,
538 and the bits() function which returns a pointer to the first pixel
539 data (this is equivalent to \c scanLine(0)).
540
541 \section1 Image Formats
542
543 Each pixel stored in a QImage is represented by an integer. The
544 size of the integer varies depending on the format. QImage
545 supports several image formats described by the \l Format
546 enum.
547
548 Monochrome images are stored using 1-bit indexes into a color table
549 with at most two colors. There are two different types of
550 monochrome images: big endian (MSB first) or little endian (LSB
551 first) bit order.
552
553 8-bit images are stored using 8-bit indexes into a color table,
554 i.e. they have a single byte per pixel. The color table is a
555 QList<QRgb>, and the QRgb typedef is equivalent to an unsigned
556 int containing an ARGB quadruplet on the format 0xAARRGGBB.
557
558 32-bit images have no color table; instead, each pixel contains an
559 QRgb value. There are three different types of 32-bit images
560 storing RGB (i.e. 0xffRRGGBB), ARGB and premultiplied ARGB
561 values respectively. In the premultiplied format the red, green,
562 and blue channels are multiplied by the alpha component divided by
563 255.
564
565 An image's format can be retrieved using the format()
566 function. Use the convertToFormat() functions to convert an image
567 into another format. The allGray() and isGrayscale() functions
568 tell whether a color image can safely be converted to a grayscale
569 image.
570
571 \section1 Image Transformations
572
573 QImage supports a number of functions for creating a new image
574 that is a transformed version of the original: The
575 createAlphaMask() function builds and returns a 1-bpp mask from
576 the alpha buffer in this image, and the createHeuristicMask()
577 function creates and returns a 1-bpp heuristic mask for this
578 image. The latter function works by selecting a color from one of
579 the corners, then chipping away pixels of that color starting at
580 all the edges.
581
582 The mirrored() function returns a mirror of the image in the
583 desired direction, the scaled() returns a copy of the image scaled
584 to a rectangle of the desired measures, and the rgbSwapped() function
585 constructs a BGR image from a RGB image.
586
587 The scaledToWidth() and scaledToHeight() functions return scaled
588 copies of the image.
589
590 The transformed() function returns a copy of the image that is
591 transformed with the given transformation matrix and
592 transformation mode: Internally, the transformation matrix is
593 adjusted to compensate for unwanted translation,
594 i.e. transformed() returns the smallest image containing all
595 transformed points of the original image. The static trueMatrix()
596 function returns the actual matrix used for transforming the
597 image.
598
599 There are also functions for changing attributes of an image
600 in-place:
601
602 \table
603 \header \li Function \li Description
604 \row
605 \li setDotsPerMeterX()
606 \li Defines the aspect ratio by setting the number of pixels that fit
607 horizontally in a physical meter.
608 \row
609 \li setDotsPerMeterY()
610 \li Defines the aspect ratio by setting the number of pixels that fit
611 vertically in a physical meter.
612 \row
613 \li fill()
614 \li Fills the entire image with the given pixel value.
615 \row
616 \li invertPixels()
617 \li Inverts all pixel values in the image using the given InvertMode value.
618 \row
619 \li setColorTable()
620 \li Sets the color table used to translate color indexes. Only
621 monochrome and 8-bit formats.
622 \row
623 \li setColorCount()
624 \li Resizes the color table. Only monochrome and 8-bit formats.
625
626 \endtable
627
628 \sa QImageReader, QImageWriter, QPixmap, QSvgRenderer,
629 {Image Composition Example}, {Scribble Example}
630*/
631
632/*!
633 \fn QImage::QImage(QImage &&other)
634
635 Move-constructs a QImage instance, making it point at the same
636 object that \a other was pointing to.
637
638 \since 5.2
639*/
640
641/*!
642 \fn QImage &QImage::operator=(QImage &&other)
643
644 Move-assigns \a other to this QImage instance.
645
646 \since 5.2
647*/
648
649/*!
650 \typedef QImageCleanupFunction
651 \relates QImage
652 \since 5.0
653
654 A function with the following signature that can be used to
655 implement basic image memory management:
656
657 \code
658 void myImageCleanupHandler(void *info);
659 \endcode
660*/
661
662/*!
663 \enum QImage::InvertMode
664
665 This enum type is used to describe how pixel values should be
666 inverted in the invertPixels() function.
667
668 \value InvertRgb Invert only the RGB values and leave the alpha
669 channel unchanged.
670
671 \value InvertRgba Invert all channels, including the alpha channel.
672
673 \sa invertPixels()
674*/
675
676/*!
677 \enum QImage::Format
678
679 The following image formats are available in Qt.
680 See the notes after the table.
681
682 \value Format_Invalid The image is invalid.
683 \value Format_Mono The image is stored using 1-bit per pixel. Bytes are
684 packed with the most significant bit (MSB) first.
685 \value Format_MonoLSB The image is stored using 1-bit per pixel. Bytes are
686 packed with the less significant bit (LSB) first.
687
688 \value Format_Indexed8 The image is stored using 8-bit indexes
689 into a colormap.
690
691 \value Format_RGB32 The image is stored using a 32-bit RGB format (0xffRRGGBB).
692
693 \value Format_ARGB32 The image is stored using a 32-bit ARGB
694 format (0xAARRGGBB).
695
696 \value Format_ARGB32_Premultiplied The image is stored using a premultiplied 32-bit
697 ARGB format (0xAARRGGBB), i.e. the red,
698 green, and blue channels are multiplied
699 by the alpha component divided by 255. (If RR, GG, or BB
700 has a higher value than the alpha channel, the results are
701 undefined.) Certain operations (such as image composition
702 using alpha blending) are faster using premultiplied ARGB32
703 than with plain ARGB32.
704
705 \value Format_RGB16 The image is stored using a 16-bit RGB format (5-6-5).
706
707 \value Format_ARGB8565_Premultiplied The image is stored using a
708 premultiplied 24-bit ARGB format (8-5-6-5).
709 \value Format_RGB666 The image is stored using a 24-bit RGB format (6-6-6).
710 The unused most significant bits is always zero.
711 \value Format_ARGB6666_Premultiplied The image is stored using a
712 premultiplied 24-bit ARGB format (6-6-6-6).
713 \value Format_RGB555 The image is stored using a 16-bit RGB format (5-5-5).
714 The unused most significant bit is always zero.
715 \value Format_ARGB8555_Premultiplied The image is stored using a
716 premultiplied 24-bit ARGB format (8-5-5-5).
717 \value Format_RGB888 The image is stored using a 24-bit RGB format (8-8-8).
718 \value Format_RGB444 The image is stored using a 16-bit RGB format (4-4-4).
719 The unused bits are always zero.
720 \value Format_ARGB4444_Premultiplied The image is stored using a
721 premultiplied 16-bit ARGB format (4-4-4-4).
722 \value [since 5.2]
723 Format_RGBX8888 The image is stored using a 32-bit byte-ordered RGB(x) format (8-8-8-8).
724 This is the same as the Format_RGBA8888 except alpha must always be 255.
725 \value [since 5.2]
726 Format_RGBA8888 The image is stored using a 32-bit byte-ordered RGBA format (8-8-8-8).
727 \value [since 5.2]
728 Format_RGBA8888_Premultiplied The image is stored using a
729 premultiplied 32-bit byte-ordered RGBA format (8-8-8-8).
730 \value [since 5.4]
731 Format_BGR30 The image is stored using a 32-bit BGR format (x-10-10-10).
732 \value [since 5.4]
733 Format_A2BGR30_Premultiplied The image is stored using a 32-bit premultiplied ABGR format (2-10-10-10).
734 \value [since 5.4]
735 Format_RGB30 The image is stored using a 32-bit RGB format (x-10-10-10).
736 \value [since 5.4]
737 Format_A2RGB30_Premultiplied The image is stored using a 32-bit premultiplied ARGB format (2-10-10-10).
738 \value [since 5.5]
739 Format_Alpha8 The image is stored using an 8-bit alpha only format.
740 \value [since 5.5]
741 Format_Grayscale8 The image is stored using an 8-bit grayscale format.
742 \value [since 5.13]
743 Format_Grayscale16 The image is stored using an 16-bit grayscale format.
744 \value [since 5.12]
745 Format_RGBX64 The image is stored using a 64-bit halfword-ordered RGB(x) format (16-16-16-16).
746 This is the same as the Format_RGBA64 except alpha must always be 65535.
747 \value [since 5.12]
748 Format_RGBA64 The image is stored using a 64-bit halfword-ordered RGBA format (16-16-16-16).
749 \value [since 5.12]
750 Format_RGBA64_Premultiplied The image is stored using a premultiplied 64-bit halfword-ordered
751 RGBA format (16-16-16-16).
752 \value [since 5.14]
753 Format_BGR888 The image is stored using a 24-bit BGR format.
754 \value [since 6.2]
755 Format_RGBX16FPx4 The image is stored using a four 16-bit halfword floating point RGBx format (16FP-16FP-16FP-16FP).
756 This is the same as the Format_RGBA16FPx4 except alpha must always be 1.0.
757 \value [since 6.2]
758 Format_RGBA16FPx4 The image is stored using a four 16-bit halfword floating point RGBA format (16FP-16FP-16FP-16FP).
759 \value [since 6.2]
760 Format_RGBA16FPx4_Premultiplied The image is stored using a premultiplied four 16-bit halfword floating point
761 RGBA format (16FP-16FP-16FP-16FP).
762 \value [since 6.2]
763 Format_RGBX32FPx4 The image is stored using a four 32-bit floating point RGBx format (32FP-32FP-32FP-32FP).
764 This is the same as the Format_RGBA32FPx4 except alpha must always be 1.0.
765 \value [since 6.2]
766 Format_RGBA32FPx4 The image is stored using a four 32-bit floating point RGBA format (32FP-32FP-32FP-32FP).
767 \value [since 6.2]
768 Format_RGBA32FPx4_Premultiplied The image is stored using a premultiplied four 32-bit floating point
769 RGBA format (32FP-32FP-32FP-32FP).
770 \value [since 6.8]
771 Format_CMYK8888 The image is stored using a 32-bit byte-ordered CMYK format.
772
773 Byte-ordered formats have a QPixelFormat::typeInterpretation() of
774 QPixelFormat::UnsignedByte, meaning the individual color components
775 are stored in memory in a fixed order, e.g 0xRR, 0xGG, 0xBB, 0xAA,
776 regardless of the endianness of the platform. These formats should be
777 read as individual bytes, or interpreted as QPixelFormat::BigEndian
778 if read in larger chunks.
779
780 \note Drawing into a QImage with format QImage::Format_Indexed8 or QImage::Format_CMYK8888 is not
781 supported.
782
783 \note Avoid most rendering directly to most of these formats using QPainter. Rendering
784 is best optimized to the \c Format_RGB32 and \c Format_ARGB32_Premultiplied formats, and secondarily for rendering to the
785 \c Format_RGB16, \c Format_RGBX8888, \c Format_RGBA8888_Premultiplied, \c Format_RGBX64 and \c Format_RGBA64_Premultiplied formats
786
787 \sa format(), convertToFormat()
788*/
789
790/*****************************************************************************
791 QImage member functions
792 *****************************************************************************/
793
794/*!
795 Constructs a null image.
796
797 \sa isNull()
798*/
799
800QImage::QImage() noexcept
801 : QPaintDevice()
802{
803 d = nullptr;
804}
805
806/*!
807 Constructs an image with the given \a width, \a height and \a
808 format.
809
810 A \l{isNull()}{null} image will be returned if memory cannot be allocated.
811
812 \warning This will create a QImage with uninitialized data. Call
813 fill() to fill the image with an appropriate pixel value before
814 drawing onto it with QPainter.
815*/
816QImage::QImage(int width, int height, Format format)
817 : QImage(QSize(width, height), format)
818{
819}
820
821/*!
822 Constructs an image with the given \a size and \a format.
823
824 A \l{isNull()}{null} image is returned if memory cannot be allocated.
825
826 \warning This will create a QImage with uninitialized data. Call
827 fill() to fill the image with an appropriate pixel value before
828 drawing onto it with QPainter.
829*/
830QImage::QImage(const QSize &size, Format format)
831 : QPaintDevice()
832{
833 d = QImageData::create(size, format);
834}
835
836
837
838QImageData *QImageData::create(uchar *data, int width, int height, qsizetype bpl, QImage::Format format, bool readOnly, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
839{
840 if (width <= 0 || height <= 0 || !data || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
841 return nullptr;
842
843 const int depth = qt_depthForFormat(format);
844 auto params = calculateImageParameters(width, height, depth);
845 if (!params.isValid())
846 return nullptr;
847
848 if (bpl > 0) {
849 // can't overflow, because has calculateImageParameters already done this multiplication
850 const qsizetype min_bytes_per_line = (qsizetype(width) * depth + 7)/8;
851 if (bpl < min_bytes_per_line)
852 return nullptr;
853
854 // recalculate the total with this value
855 params.bytesPerLine = bpl;
856 if (qMulOverflow<qsizetype>(bpl, height, &params.totalSize))
857 return nullptr;
858 }
859
860 QImageData *d = new QImageData;
861 d->ref.ref();
862
863 d->own_data = false;
864 d->ro_data = readOnly;
865 d->data = data;
866 d->width = width;
867 d->height = height;
868 d->depth = depth;
869 d->format = format;
870
871 d->bytes_per_line = params.bytesPerLine;
872 d->nbytes = params.totalSize;
873
874 d->cleanupFunction = cleanupFunction;
875 d->cleanupInfo = cleanupInfo;
876
877 return d;
878}
879
880/*!
881 Constructs an image with the given \a width, \a height and \a
882 format, that uses an existing memory buffer, \a data. The \a width
883 and \a height must be specified in pixels, \a data must be 32-bit aligned,
884 and each scanline of data in the image must also be 32-bit aligned.
885
886 The buffer must remain valid throughout the life of the QImage and
887 all copies that have not been modified or otherwise detached from
888 the original buffer. The image does not delete the buffer at destruction.
889 You can provide a function pointer \a cleanupFunction along with an
890 extra pointer \a cleanupInfo that will be called when the last copy
891 is destroyed.
892
893 If \a format is an indexed color format, the image color table is
894 initially empty and must be sufficiently expanded with
895 setColorCount() or setColorTable() before the image is used.
896*/
897QImage::QImage(uchar* data, int width, int height, Format format, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
898 : QPaintDevice()
899{
900 d = QImageData::create(data, width, height, 0, format, false, cleanupFunction, cleanupInfo);
901}
902
903/*!
904 Constructs an image with the given \a width, \a height and \a
905 format, that uses an existing read-only memory buffer, \a
906 data. The \a width and \a height must be specified in pixels, \a
907 data must be 32-bit aligned, and each scanline of data in the
908 image must also be 32-bit aligned.
909
910 The buffer must remain valid throughout the life of the QImage and
911 all copies that have not been modified or otherwise detached from
912 the original buffer. The image does not delete the buffer at destruction.
913 You can provide a function pointer \a cleanupFunction along with an
914 extra pointer \a cleanupInfo that will be called when the last copy
915 is destroyed.
916
917 If \a format is an indexed color format, the image color table is
918 initially empty and must be sufficiently expanded with
919 setColorCount() or setColorTable() before the image is used.
920
921 Unlike the similar QImage constructor that takes a non-const data buffer,
922 this version will never alter the contents of the buffer. For example,
923 calling QImage::bits() will return a deep copy of the image, rather than
924 the buffer passed to the constructor. This allows for the efficiency of
925 constructing a QImage from raw data, without the possibility of the raw
926 data being changed.
927*/
928QImage::QImage(const uchar* data, int width, int height, Format format, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
929 : QPaintDevice()
930{
931 d = QImageData::create(const_cast<uchar*>(data), width, height, 0, format, true, cleanupFunction, cleanupInfo);
932}
933
934/*!
935 Constructs an image with the given \a width, \a height and \a
936 format, that uses an existing memory buffer, \a data. The \a width
937 and \a height must be specified in pixels. \a bytesPerLine
938 specifies the number of bytes per line (stride).
939
940 The buffer must remain valid throughout the life of the QImage and
941 all copies that have not been modified or otherwise detached from
942 the original buffer. The image does not delete the buffer at destruction.
943 You can provide a function pointer \a cleanupFunction along with an
944 extra pointer \a cleanupInfo that will be called when the last copy
945 is destroyed.
946
947 If \a format is an indexed color format, the image color table is
948 initially empty and must be sufficiently expanded with
949 setColorCount() or setColorTable() before the image is used.
950*/
951
952QImage::QImage(uchar *data, int width, int height, qsizetype bytesPerLine, Format format, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
953 :QPaintDevice()
954{
955 d = QImageData::create(data, width, height, bytesPerLine, format, false, cleanupFunction, cleanupInfo);
956}
957
958/*!
959 Constructs an image with the given \a width, \a height and \a
960 format, that uses an existing memory buffer, \a data. The \a width
961 and \a height must be specified in pixels. \a bytesPerLine
962 specifies the number of bytes per line (stride).
963
964 The buffer must remain valid throughout the life of the QImage and
965 all copies that have not been modified or otherwise detached from
966 the original buffer. The image does not delete the buffer at destruction.
967 You can provide a function pointer \a cleanupFunction along with an
968 extra pointer \a cleanupInfo that will be called when the last copy
969 is destroyed.
970
971 If \a format is an indexed color format, the image color table is
972 initially empty and must be sufficiently expanded with
973 setColorCount() or setColorTable() before the image is used.
974
975 Unlike the similar QImage constructor that takes a non-const data buffer,
976 this version will never alter the contents of the buffer. For example,
977 calling QImage::bits() will return a deep copy of the image, rather than
978 the buffer passed to the constructor. This allows for the efficiency of
979 constructing a QImage from raw data, without the possibility of the raw
980 data being changed.
981*/
982
983QImage::QImage(const uchar *data, int width, int height, qsizetype bytesPerLine, Format format, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
984 :QPaintDevice()
985{
986 d = QImageData::create(const_cast<uchar*>(data), width, height, bytesPerLine, format, true, cleanupFunction, cleanupInfo);
987}
988
989/*!
990 Constructs an image and tries to load the image from the file with
991 the given \a fileName.
992
993 The loader attempts to read the image using the specified \a
994 format. If the \a format is not specified (which is the default),
995 it is auto-detected based on the file's suffix and header. For
996 details, see QImageReader::setAutoDetectImageFormat() and
997 \l{QImageReader#Security Considerations}{Security Considerations}.
998
999 If the loading of the image failed, this object is a null image.
1000
1001 The file name can either refer to an actual file on disk or to one
1002 of the application's embedded resources. See the
1003 \l{resources.html}{Resource System} overview for details on how to
1004 embed images and other resource files in the application's
1005 executable.
1006
1007 \sa isNull(), {QImage#Reading and Writing Image Files}{Reading and Writing Image Files}
1008*/
1009
1010QImage::QImage(const QString &fileName, const char *format)
1011 : QPaintDevice()
1012{
1013 d = nullptr;
1014 load(fileName, format);
1015}
1016
1017#ifndef QT_NO_IMAGEFORMAT_XPM
1018extern bool qt_read_xpm_image_or_array(QIODevice *device, const char * const *source, QImage &image);
1019
1020/*!
1021 Constructs an image from the given \a xpm image.
1022
1023 Make sure that the image is a valid XPM image. Errors are silently
1024 ignored and can cause undefined behavior.
1025
1026 Note that it's possible to squeeze the XPM variable a little bit
1027 by using an unusual declaration:
1028
1029 \snippet code/src_gui_image_qimage.cpp 2
1030
1031 The extra \c const makes the entire definition read-only, which is
1032 slightly more efficient (e.g., when the code is in a shared
1033 library) and able to be stored in ROM with the application.
1034*/
1035
1036QImage::QImage(const char * const xpm[])
1037 : QPaintDevice()
1038{
1039 d = nullptr;
1040 if (!xpm)
1041 return;
1042 if (!qt_read_xpm_image_or_array(nullptr, xpm, *this))
1043 // Issue: Warning because the constructor may be ambiguous
1044 qWarning("QImage::QImage(), XPM is not supported");
1045}
1046#endif // QT_NO_IMAGEFORMAT_XPM
1047
1048/*!
1049 Constructs a shallow copy of the given \a image.
1050
1051 For more information about shallow copies, see the \l {Implicit
1052 Data Sharing} documentation.
1053
1054 \sa copy()
1055*/
1056
1057QImage::QImage(const QImage &image)
1058 : QPaintDevice()
1059{
1060 if (image.paintingActive()) {
1061 d = nullptr;
1062 image.copy().swap(*this);
1063 } else {
1064 d = image.d;
1065 if (d)
1066 d->ref.ref();
1067 }
1068}
1069
1070/*!
1071 Destroys the image and cleans up.
1072*/
1073
1074QImage::~QImage()
1075{
1076 if (d && !d->ref.deref())
1077 delete d;
1078}
1079
1080/*!
1081 Assigns a shallow copy of the given \a image to this image and
1082 returns a reference to this image.
1083
1084 For more information about shallow copies, see the \l {Implicit
1085 Data Sharing} documentation.
1086
1087 \sa copy(), QImage()
1088*/
1089
1090QImage &QImage::operator=(const QImage &image)
1091{
1092 if (image.paintingActive()) {
1093 operator=(image.copy());
1094 } else {
1095 if (image.d)
1096 image.d->ref.ref();
1097 if (d && !d->ref.deref())
1098 delete d;
1099 d = image.d;
1100 }
1101 return *this;
1102}
1103
1104/*!
1105 \fn void QImage::swap(QImage &other)
1106 \memberswap{image}
1107*/
1108
1109/*!
1110 \internal
1111*/
1112int QImage::devType() const
1113{
1114 return QInternal::Image;
1115}
1116
1117/*!
1118 Returns the image as a QVariant.
1119*/
1120QImage::operator QVariant() const
1121{
1122 return QVariant::fromValue(*this);
1123}
1124
1125/*!
1126 \internal
1127
1128 If multiple images share common data, this image makes a copy of
1129 the data and detaches itself from the sharing mechanism, making
1130 sure that this image is the only one referring to the data.
1131
1132 Nothing is done if there is just a single reference.
1133
1134 \sa copy(), {QImage::isDetached()}{isDetached()}, {Implicit Data Sharing}
1135*/
1136void QImage::detach()
1137{
1138 if (d) {
1139 if (d->is_cached && d->ref.loadRelaxed() == 1)
1140 QImagePixmapCleanupHooks::executeImageHooks(cacheKey());
1141
1142 if (d->ref.loadRelaxed() != 1 || d->ro_data)
1143 *this = copy();
1144
1145 if (d)
1146 ++d->detach_no;
1147 }
1148}
1149
1150
1151/*!
1152 \internal
1153
1154 A variant for metadata-only detach, which will not detach readonly image data,
1155 and only invalidate caches of the image data if asked to.
1156
1157 \sa detach(), isDetached()
1158*/
1159void QImage::detachMetadata(bool invalidateCache)
1160{
1161 if (d) {
1162 if (d->is_cached && d->ref.loadRelaxed() == 1)
1163 QImagePixmapCleanupHooks::executeImageHooks(cacheKey());
1164
1165 if (d->ref.loadRelaxed() != 1)
1166 *this = copy();
1167
1168 if (d && invalidateCache)
1169 ++d->detach_no;
1170 }
1171}
1172
1173static void copyPhysicalMetadata(QImageData *dst, const QImageData *src)
1174{
1175 dst->dpmx = src->dpmx;
1176 dst->dpmy = src->dpmy;
1177 dst->devicePixelRatio = src->devicePixelRatio;
1178}
1179
1180static void copyMetadata(QImageData *dst, const QImageData *src)
1181{
1182 // Doesn't copy colortable and alpha_clut.
1184 dst->text = src->text;
1185 dst->offset = src->offset;
1186 dst->colorSpace = src->colorSpace;
1187}
1188
1189static void copyMetadata(QImage *dst, const QImage &src)
1190{
1191 dst->setDotsPerMeterX(src.dotsPerMeterX());
1192 dst->setDotsPerMeterY(src.dotsPerMeterY());
1193 dst->setDevicePixelRatio(src.devicePixelRatio());
1194 const auto textKeys = src.textKeys();
1195 for (const auto &key: textKeys)
1196 dst->setText(key, src.text(key));
1197
1198}
1199
1200/*!
1201 \fn QImage QImage::copy(int x, int y, int width, int height) const
1202 \overload
1203
1204 The returned image is copied from the position (\a x, \a y) in
1205 this image, and has the given \a width and \a height. In areas
1206 beyond this image, pixels are set to 0.
1207
1208 Returns a null image if this image is null, if the rectangle
1209 described by \a x, \a y, \a width, and \a height is empty but
1210 not null, or if the image can't be allocated.
1211*/
1212
1213/*!
1214 \fn QImage QImage::copy(const QRect& rectangle) const
1215
1216 Returns a sub-area of the image as a new image.
1217
1218 The returned image is copied from the position (\a
1219 {rectangle}.x(), \a{rectangle}.y()) in this image, and has the
1220 size of the given \a rectangle.
1221
1222 In areas beyond this image, pixels are set to 0. For 32-bit RGB
1223 images, this means black; for 32-bit ARGB images, this means
1224 transparent black; for 8-bit images, this means the color with
1225 index 0 in the color table which can be anything; for 1-bit
1226 images, this means Qt::color0.
1227
1228 If the given \a rectangle is a null rectangle the entire image is
1229 copied.
1230
1231 Returns a null image if this image is null, if \a rectangle is
1232 empty but not null, or if the image can't be allocated.
1233
1234 \sa QImage(), QRect::isNull(), QRect::isEmpty()
1235*/
1236QImage Q_TRACE_INSTRUMENT(qtgui) QImage::copy(const QRect& r) const
1237{
1238 Q_TRACE_SCOPE(QImage_copy, r);
1239 if (!d)
1240 return QImage();
1241
1242 if (r.isNull()) {
1243 QImage image(d->width, d->height, d->format);
1244 if (image.isNull())
1245 return image;
1246
1247 // Qt for Embedded Linux can create images with non-default bpl
1248 // make sure we don't crash.
1249 if (image.d->nbytes != d->nbytes) {
1250 qsizetype bpl = qMin(bytesPerLine(), image.bytesPerLine());
1251 for (int i = 0; i < height(); i++)
1252 memcpy(image.scanLine(i), scanLine(i), bpl);
1253 } else
1254 memcpy(image.bits(), bits(), d->nbytes);
1255 image.d->colortable = d->colortable;
1256 image.d->has_alpha_clut = d->has_alpha_clut;
1257 copyMetadata(image.d, d);
1258 return image;
1259 }
1260
1261 int x = r.x();
1262 int y = r.y();
1263 int w = r.width();
1264 int h = r.height();
1265
1266 int dx = 0;
1267 int dy = 0;
1268 if (w <= 0 || h <= 0)
1269 return QImage();
1270
1271 QImage image(w, h, d->format);
1272 if (image.isNull())
1273 return image;
1274
1275 if (x < 0 || y < 0 || x + w > d->width || y + h > d->height) {
1276 // bitBlt will not cover entire image - clear it.
1277 image.fill(0);
1278 if (x < 0) {
1279 dx = -x;
1280 x = 0;
1281 }
1282 if (y < 0) {
1283 dy = -y;
1284 y = 0;
1285 }
1286 }
1287
1288 image.d->colortable = d->colortable;
1289
1290 int pixels_to_copy = qMax(w - dx, 0);
1291 if (x > d->width)
1292 pixels_to_copy = 0;
1293 else if (pixels_to_copy > d->width - x)
1294 pixels_to_copy = d->width - x;
1295 int lines_to_copy = qMax(h - dy, 0);
1296 if (y > d->height)
1297 lines_to_copy = 0;
1298 else if (lines_to_copy > d->height - y)
1299 lines_to_copy = d->height - y;
1300
1301 bool byteAligned = true;
1302 if (d->format == Format_Mono || d->format == Format_MonoLSB)
1303 byteAligned = !(dx & 7) && !(x & 7) && !(pixels_to_copy & 7);
1304
1305 if (byteAligned) {
1306 const uchar *src = d->data + ((x * d->depth) >> 3) + y * d->bytes_per_line;
1307 uchar *dest = image.d->data + ((dx * d->depth) >> 3) + dy * image.d->bytes_per_line;
1308 const qsizetype bytes_to_copy = (qsizetype(pixels_to_copy) * d->depth) >> 3;
1309 for (int i = 0; i < lines_to_copy; ++i) {
1310 memcpy(dest, src, bytes_to_copy);
1311 src += d->bytes_per_line;
1312 dest += image.d->bytes_per_line;
1313 }
1314 } else if (d->format == Format_Mono) {
1315 const uchar *src = d->data + y * d->bytes_per_line;
1316 uchar *dest = image.d->data + dy * image.d->bytes_per_line;
1317 for (int i = 0; i < lines_to_copy; ++i) {
1318 for (int j = 0; j < pixels_to_copy; ++j) {
1319 if (src[(x + j) >> 3] & (0x80 >> ((x + j) & 7)))
1320 dest[(dx + j) >> 3] |= (0x80 >> ((dx + j) & 7));
1321 else
1322 dest[(dx + j) >> 3] &= ~(0x80 >> ((dx + j) & 7));
1323 }
1324 src += d->bytes_per_line;
1325 dest += image.d->bytes_per_line;
1326 }
1327 } else { // Format_MonoLSB
1328 Q_ASSERT(d->format == Format_MonoLSB);
1329 const uchar *src = d->data + y * d->bytes_per_line;
1330 uchar *dest = image.d->data + dy * image.d->bytes_per_line;
1331 for (int i = 0; i < lines_to_copy; ++i) {
1332 for (int j = 0; j < pixels_to_copy; ++j) {
1333 if (src[(x + j) >> 3] & (0x1 << ((x + j) & 7)))
1334 dest[(dx + j) >> 3] |= (0x1 << ((dx + j) & 7));
1335 else
1336 dest[(dx + j) >> 3] &= ~(0x1 << ((dx + j) & 7));
1337 }
1338 src += d->bytes_per_line;
1339 dest += image.d->bytes_per_line;
1340 }
1341 }
1342
1343 copyMetadata(image.d, d);
1344 image.d->has_alpha_clut = d->has_alpha_clut;
1345 return image;
1346}
1347
1348
1349/*!
1350 \fn bool QImage::isNull() const
1351
1352 Returns \c true if it is a null image, otherwise returns \c false.
1353
1354 A null image has all parameters set to zero and no allocated data.
1355*/
1356bool QImage::isNull() const
1357{
1358 return !d;
1359}
1360
1361/*!
1362 \fn int QImage::width() const
1363
1364 Returns the width of the image.
1365
1366 \sa {QImage#Image Information}{Image Information}
1367*/
1368int QImage::width() const
1369{
1370 return d ? d->width : 0;
1371}
1372
1373/*!
1374 \fn int QImage::height() const
1375
1376 Returns the height of the image.
1377
1378 \sa {QImage#Image Information}{Image Information}
1379*/
1380int QImage::height() const
1381{
1382 return d ? d->height : 0;
1383}
1384
1385/*!
1386 \fn QSize QImage::size() const
1387
1388 Returns the size of the image, i.e. its width() and height().
1389
1390 \sa {QImage#Image Information}{Image Information}, deviceIndependentSize()
1391*/
1392QSize QImage::size() const
1393{
1394 return d ? QSize(d->width, d->height) : QSize(0, 0);
1395}
1396
1397/*!
1398 \fn QRect QImage::rect() const
1399
1400 Returns the enclosing rectangle (0, 0, width(), height()) of the
1401 image.
1402
1403 \sa {QImage#Image Information}{Image Information}
1404*/
1405QRect QImage::rect() const
1406{
1407 return d ? QRect(0, 0, d->width, d->height) : QRect();
1408}
1409
1410/*!
1411 Returns the depth of the image.
1412
1413 The image depth is the number of bits used to store a single
1414 pixel, also called bits per pixel (bpp).
1415
1416 The supported depths are 1, 8, 16, 24, 32 and 64.
1417
1418 \sa bitPlaneCount(), convertToFormat(), {QImage#Image Formats}{Image Formats},
1419 {QImage#Image Information}{Image Information}
1420
1421*/
1422int QImage::depth() const
1423{
1424 return d ? d->depth : 0;
1425}
1426
1427/*!
1428 \fn int QImage::colorCount() const
1429
1430 Returns the size of the color table for the image.
1431
1432 Notice that colorCount() returns 0 for 32-bpp images because these
1433 images do not use color tables, but instead encode pixel values as
1434 ARGB quadruplets.
1435
1436 \sa setColorCount(), {QImage#Image Information}{Image Information}
1437*/
1438int QImage::colorCount() const
1439{
1440 return d ? d->colortable.size() : 0;
1441}
1442
1443/*!
1444 Sets the color table used to translate color indexes to QRgb
1445 values, to the specified \a colors.
1446
1447 When the image is used, the color table must be large enough to
1448 have entries for all the pixel/index values present in the image,
1449 otherwise the results are undefined.
1450
1451 \sa colorTable(), setColor(), {QImage#Image Transformations}{Image
1452 Transformations}
1453*/
1454void QImage::setColorTable(const QList<QRgb> &colors)
1455{
1456 if (!d)
1457 return;
1458 detachMetadata(true);
1459
1460 // In case detach() ran out of memory
1461 if (!d)
1462 return;
1463
1464 d->colortable = colors;
1465 d->has_alpha_clut = false;
1466 for (int i = 0; i < d->colortable.size(); ++i) {
1467 if (qAlpha(d->colortable.at(i)) != 255) {
1468 d->has_alpha_clut = true;
1469 break;
1470 }
1471 }
1472}
1473
1474/*!
1475 Returns a list of the colors contained in the image's color table,
1476 or an empty list if the image does not have a color table
1477
1478 \sa setColorTable(), colorCount(), color()
1479*/
1480QList<QRgb> QImage::colorTable() const
1481{
1482 return d ? d->colortable : QList<QRgb>();
1483}
1484
1485/*!
1486 Returns the device pixel ratio for the image. This is the
1487 ratio between \e{device pixels} and \e{device independent pixels}.
1488
1489 Use this function when calculating layout geometry based on
1490 the image size: QSize layoutSize = image.size() / image.devicePixelRatio()
1491
1492 The default value is 1.0.
1493
1494 \sa setDevicePixelRatio(), QImageReader
1495*/
1496qreal QImage::devicePixelRatio() const
1497{
1498 if (!d)
1499 return 1.0;
1500 return d->devicePixelRatio;
1501}
1502
1503/*!
1504 Sets the device pixel ratio for the image. This is the
1505 ratio between image pixels and device-independent pixels.
1506
1507 The default \a scaleFactor is 1.0. Setting it to something else has
1508 two effects:
1509
1510 QPainters that are opened on the image will be scaled. For
1511 example, painting on a 200x200 image if with a ratio of 2.0
1512 will result in effective (device-independent) painting bounds
1513 of 100x100.
1514
1515 Code paths in Qt that calculate layout geometry based on the
1516 image size will take the ratio into account:
1517 QSize layoutSize = image.size() / image.devicePixelRatio()
1518 The net effect of this is that the image is displayed as
1519 high-DPI image rather than a large image
1520 (see \l{Drawing High Resolution Versions of Pixmaps and Images}).
1521
1522 \sa devicePixelRatio(), deviceIndependentSize()
1523*/
1524void QImage::setDevicePixelRatio(qreal scaleFactor)
1525{
1526 if (!d)
1527 return;
1528
1529 if (scaleFactor == d->devicePixelRatio)
1530 return;
1531
1532 detachMetadata();
1533 if (d)
1534 d->devicePixelRatio = scaleFactor;
1535}
1536
1537/*!
1538 Returns the size of the image in device independent pixels.
1539
1540 This value should be used when using the image size in user interface
1541 size calculations.
1542
1543 The return value is equivalent to image.size() / image.devicePixelRatio().
1544
1545 \since 6.2
1546*/
1547QSizeF QImage::deviceIndependentSize() const
1548{
1549 if (!d)
1550 return QSizeF(0, 0);
1551 return QSizeF(d->width, d->height) / d->devicePixelRatio;
1552}
1553
1554
1555/*!
1556 \since 5.10
1557 Returns the image data size in bytes.
1558
1559 \sa bytesPerLine(), bits(), {QImage#Image Information}{Image
1560 Information}
1561*/
1562qsizetype QImage::sizeInBytes() const
1563{
1564 return d ? d->nbytes : 0;
1565}
1566
1567/*!
1568 Returns the number of bytes per image scanline.
1569
1570 This is equivalent to sizeInBytes() / height() if height() is non-zero.
1571
1572 \sa scanLine()
1573*/
1574qsizetype QImage::bytesPerLine() const
1575{
1576 return d ? d->bytes_per_line : 0;
1577}
1578
1579
1580/*!
1581 Returns the color in the color table at index \a i. The first
1582 color is at index 0.
1583
1584 The colors in an image's color table are specified as ARGB
1585 quadruplets (QRgb). Use the qAlpha(), qRed(), qGreen(), and
1586 qBlue() functions to get the color value components.
1587
1588 \sa setColor(), pixelIndex(), {QImage#Pixel Manipulation}{Pixel
1589 Manipulation}
1590*/
1591QRgb QImage::color(int i) const
1592{
1593 Q_ASSERT(i < colorCount());
1594 return d ? d->colortable.at(i) : QRgb(uint(-1));
1595}
1596
1597/*!
1598 \fn void QImage::setColor(int index, QRgb colorValue)
1599
1600 Sets the color at the given \a index in the color table, to the
1601 given to \a colorValue. The color value is an ARGB quadruplet.
1602
1603 If \a index is outside the current size of the color table, it is
1604 expanded with setColorCount().
1605
1606 \sa color(), colorCount(), setColorTable(), {QImage#Pixel Manipulation}{Pixel
1607 Manipulation}
1608*/
1609void QImage::setColor(int i, QRgb c)
1610{
1611 if (!d)
1612 return;
1613 if (i < 0 || d->depth > 8 || i >= 1<<d->depth) {
1614 qWarning("QImage::setColor: Index out of bound %d", i);
1615 return;
1616 }
1617 detachMetadata(true);
1618
1619 // In case detach() run out of memory
1620 if (!d)
1621 return;
1622
1623 if (i >= d->colortable.size())
1624 setColorCount(i+1);
1625 d->colortable[i] = c;
1626 d->has_alpha_clut |= (qAlpha(c) != 255);
1627}
1628
1629/*!
1630 Returns a pointer to the pixel data at the scanline with index \a
1631 i. The first scanline is at index 0.
1632
1633 The scanline data is as minimum 32-bit aligned. For 64-bit formats
1634 it follows the native alignment of 64-bit integers (64-bit for most
1635 platforms, but notably 32-bit on i386).
1636
1637 For example, to remove the green component of each pixel in an image:
1638
1639 \snippet code/src_gui_image_qimage.cpp scanLine
1640
1641 \warning If you are accessing 32-bpp image data, cast the returned
1642 pointer to \c{QRgb*} (QRgb has a 32-bit size) and use it to
1643 read/write the pixel value. You cannot use the \c{uchar*} pointer
1644 directly, because the pixel format depends on the byte order on
1645 the underlying platform. Use qRed(), qGreen(), qBlue(), and
1646 qAlpha() to access the pixels.
1647
1648 \sa bytesPerLine(), bits(), {QImage#Pixel Manipulation}{Pixel
1649 Manipulation}, constScanLine()
1650*/
1651uchar *QImage::scanLine(int i)
1652{
1653 if (!d)
1654 return nullptr;
1655
1656 detach();
1657
1658 // In case detach() ran out of memory
1659 if (!d)
1660 return nullptr;
1661
1662 return d->data + i * d->bytes_per_line;
1663}
1664
1665/*!
1666 \overload
1667*/
1668const uchar *QImage::scanLine(int i) const
1669{
1670 if (!d)
1671 return nullptr;
1672
1673 Q_ASSERT(i >= 0 && i < height());
1674 return d->data + i * d->bytes_per_line;
1675}
1676
1677
1678/*!
1679 Returns a pointer to the pixel data at the scanline with index \a
1680 i. The first scanline is at index 0.
1681
1682 The scanline data is as minimum 32-bit aligned. For 64-bit formats
1683 it follows the native alignment of 64-bit integers (64-bit for most
1684 platforms, but notably 32-bit on i386).
1685
1686 Note that QImage uses \l{Implicit Data Sharing} {implicit data
1687 sharing}, but this function does \e not perform a deep copy of the
1688 shared pixel data, because the returned data is const.
1689
1690 \sa scanLine(), constBits()
1691*/
1692const uchar *QImage::constScanLine(int i) const
1693{
1694 if (!d)
1695 return nullptr;
1696
1697 Q_ASSERT(i >= 0 && i < height());
1698 return d->data + i * d->bytes_per_line;
1699}
1700
1701/*!
1702 Returns a pointer to the first pixel data. This is equivalent to
1703 scanLine(0).
1704
1705 Note that QImage uses \l{Implicit Data Sharing} {implicit data
1706 sharing}. This function performs a deep copy of the shared pixel
1707 data, thus ensuring that this QImage is the only one using the
1708 current return value.
1709
1710 \sa scanLine(), sizeInBytes(), constBits()
1711*/
1712uchar *QImage::bits()
1713{
1714 if (!d)
1715 return nullptr;
1716 detach();
1717
1718 // In case detach ran out of memory...
1719 if (!d)
1720 return nullptr;
1721
1722 return d->data;
1723}
1724
1725/*!
1726 \overload
1727
1728 Note that QImage uses \l{Implicit Data Sharing} {implicit data
1729 sharing}, but this function does \e not perform a deep copy of the
1730 shared pixel data, because the returned data is const.
1731*/
1732const uchar *QImage::bits() const
1733{
1734 return d ? d->data : nullptr;
1735}
1736
1737
1738/*!
1739 Returns a pointer to the first pixel data.
1740
1741 Note that QImage uses \l{Implicit Data Sharing} {implicit data
1742 sharing}, but this function does \e not perform a deep copy of the
1743 shared pixel data, because the returned data is const.
1744
1745 \sa bits(), constScanLine()
1746*/
1747const uchar *QImage::constBits() const
1748{
1749 return d ? d->data : nullptr;
1750}
1751
1752/*!
1753 \fn void QImage::fill(uint pixelValue)
1754
1755 Fills the entire image with the given \a pixelValue.
1756
1757 If the depth of this image is 1, only the lowest bit is used. If
1758 you say fill(0), fill(2), etc., the image is filled with 0s. If
1759 you say fill(1), fill(3), etc., the image is filled with 1s. If
1760 the depth is 8, the lowest 8 bits are used and if the depth is 16
1761 the lowest 16 bits are used.
1762
1763 If the image depth is higher than 32bit the result is undefined.
1764
1765 \note There are no corresponding value getter, though QImage::pixelIndex()
1766 will return the same value for indexed formats, and QImage::pixel() for
1767 RGB32, ARGB32, and ARGB32PM formats.
1768
1769 \sa depth(), {QImage#Image Transformations}{Image Transformations}
1770*/
1771
1772void QImage::fill(uint pixel)
1773{
1774 if (!d)
1775 return;
1776
1777 detach();
1778
1779 // In case detach() ran out of memory
1780 if (!d)
1781 return;
1782
1783 if (d->depth == 1 || d->depth == 8) {
1784 int w = d->width;
1785 if (d->depth == 1) {
1786 if (pixel & 1)
1787 pixel = 0xffffffff;
1788 else
1789 pixel = 0;
1790 w = (w + 7) / 8;
1791 } else {
1792 pixel &= 0xff;
1793 }
1794 qt_rectfill<quint8>(d->data, pixel, 0, 0,
1795 w, d->height, d->bytes_per_line);
1796 return;
1797 } else if (d->depth == 16) {
1798 if (d->format == Format_RGB444)
1799 pixel |= 0xf000;
1800 qt_rectfill<quint16>(reinterpret_cast<quint16*>(d->data), pixel,
1801 0, 0, d->width, d->height, d->bytes_per_line);
1802 return;
1803 } else if (d->depth == 24) {
1804 if (d->format == Format_RGB666)
1805 pixel |= 0xfc0000;
1806 qt_rectfill<quint24>(reinterpret_cast<quint24*>(d->data), pixel,
1807 0, 0, d->width, d->height, d->bytes_per_line);
1808 return;
1809 } else if (d->format >= QImage::Format_RGBX64 && d->format <= QImage::Format_RGBA64_Premultiplied) {
1810 qt_rectfill<quint64>(reinterpret_cast<quint64*>(d->data), QRgba64::fromArgb32(pixel),
1811 0, 0, d->width, d->height, d->bytes_per_line);
1812 return;
1813 } else if (d->format >= QImage::Format_RGBX16FPx4 && d->format <= QImage::Format_RGBA16FPx4_Premultiplied) {
1814 quint64 cu;
1815 QRgbaFloat16 cf = QRgbaFloat16::fromArgb32(pixel);
1816 ::memcpy(&cu, &cf, sizeof(quint64));
1817 qt_rectfill<quint64>(reinterpret_cast<quint64*>(d->data), cu,
1818 0, 0, d->width, d->height, d->bytes_per_line);
1819 return;
1820 } else if (d->format >= QImage::Format_RGBX32FPx4 && d->format <= QImage::Format_RGBA32FPx4_Premultiplied) {
1821 QRgbaFloat32 cf = QRgbaFloat32::fromArgb32(pixel);
1822 uchar *data = d->data;
1823 for (int y = 0; y < d->height; ++y) {
1824 QRgbaFloat32 *line = reinterpret_cast<QRgbaFloat32 *>(data);
1825 for (int x = 0; x < d->width; ++x)
1826 line[x] = cf;
1827 data += d->bytes_per_line;
1828 }
1829 return;
1830 }
1831 Q_ASSERT(d->depth == 32);
1832
1833 if (d->format == Format_RGB32)
1834 pixel |= 0xff000000;
1835 if (d->format == Format_RGBX8888)
1836#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
1837 pixel |= 0xff000000;
1838#else
1839 pixel |= 0x000000ff;
1840#endif
1841 if (d->format == Format_BGR30 || d->format == Format_RGB30)
1842 pixel |= 0xc0000000;
1843
1844 qt_rectfill<uint>(reinterpret_cast<uint*>(d->data), pixel,
1845 0, 0, d->width, d->height, d->bytes_per_line);
1846}
1847
1848
1849/*!
1850 \fn void QImage::fill(Qt::GlobalColor color)
1851 \overload
1852
1853 Fills the image with the given \a color, described as a standard global
1854 color.
1855 */
1856
1857void QImage::fill(Qt::GlobalColor color)
1858{
1859 fill(QColor(color));
1860}
1861
1862
1863
1864/*!
1865 \fn void QImage::fill(const QColor &color)
1866
1867 \overload
1868
1869 Fills the entire image with the given \a color.
1870
1871 If the depth of the image is 1, the image will be filled with 1 if
1872 \a color equals Qt::color1; it will otherwise be filled with 0.
1873
1874 If the depth of the image is 8, the image will be filled with the
1875 index corresponding the \a color in the color table if present; it
1876 will otherwise be filled with 0.
1877*/
1878
1879void QImage::fill(const QColor &color)
1880{
1881 if (!d)
1882 return;
1883 detach();
1884
1885 // In case we run out of memory
1886 if (!d)
1887 return;
1888
1889 QRgba64 opaque = color.rgba64();
1890 opaque.setAlpha(65535);
1891 switch (d->format) {
1892 case QImage::Format_RGB32:
1893 case QImage::Format_ARGB32:
1894 fill(color.rgba());
1895 break;
1896 case QImage::Format_ARGB32_Premultiplied:
1897 fill(qPremultiply(color.rgba()));
1898 break;
1899 case QImage::Format_RGBX8888:
1900 fill(ARGB2RGBA(color.rgba() | 0xff000000));
1901 break;
1902 case QImage::Format_RGBA8888:
1903 fill(ARGB2RGBA(color.rgba()));
1904 break;
1905 case QImage::Format_RGBA8888_Premultiplied:
1906 fill(ARGB2RGBA(qPremultiply(color.rgba())));
1907 break;
1908 case QImage::Format_BGR30:
1909 fill(qConvertRgb64ToRgb30<PixelOrderBGR>(opaque));
1910 break;
1911 case QImage::Format_RGB30:
1912 fill(qConvertRgb64ToRgb30<PixelOrderRGB>(opaque));
1913 break;
1914 case QImage::Format_RGB16:
1915 fill((uint) qConvertRgb32To16(color.rgba()));
1916 break;
1917 case QImage::Format_Indexed8: {
1918 uint pixel = 0;
1919 for (int i=0; i<d->colortable.size(); ++i) {
1920 if (color.rgba() == d->colortable.at(i)) {
1921 pixel = i;
1922 break;
1923 }
1924 }
1925 fill(pixel);
1926 break;
1927 }
1928 case QImage::Format_Mono:
1929 case QImage::Format_MonoLSB:
1930 if (color == Qt::color1)
1931 fill((uint) 1);
1932 else
1933 fill((uint) 0);
1934 break;
1935 case QImage::Format_RGBX64:
1936 qt_rectfill<quint64>(reinterpret_cast<quint64*>(d->data), opaque,
1937 0, 0, d->width, d->height, d->bytes_per_line);
1938 break;
1939 case QImage::Format_RGBA64:
1940 qt_rectfill<quint64>(reinterpret_cast<quint64*>(d->data), color.rgba64(),
1941 0, 0, d->width, d->height, d->bytes_per_line);
1942 break;
1943 case QImage::Format_RGBA64_Premultiplied:
1944 qt_rectfill<quint64>(reinterpret_cast<quint64 *>(d->data), color.rgba64().premultiplied(),
1945 0, 0, d->width, d->height, d->bytes_per_line);
1946 break;
1947 case QImage::Format_RGBX16FPx4:
1948 case QImage::Format_RGBA16FPx4:
1949 case QImage::Format_RGBA16FPx4_Premultiplied:
1950 case QImage::Format_RGBX32FPx4:
1951 case QImage::Format_RGBA32FPx4:
1952 case QImage::Format_RGBA32FPx4_Premultiplied:{
1953 float r, g, b, a;
1954 color.getRgbF(&r, &g, &b, &a);
1955 if (!hasAlphaChannel())
1956 a = 1.0f;
1957 if (depth() == 64) {
1958 QRgbaFloat16 c16{qfloat16(r), qfloat16(g), qfloat16(b), qfloat16(a)};
1959 if (d->format == Format_RGBA16FPx4_Premultiplied)
1960 c16 = c16.premultiplied();
1961 qt_rectfill<QRgbaFloat16>(reinterpret_cast<QRgbaFloat16 *>(d->data), c16,
1962 0, 0, d->width, d->height, d->bytes_per_line);
1963 } else {
1964 QRgbaFloat32 c32{r, g, b, a};
1965 if (d->format == Format_RGBA32FPx4_Premultiplied)
1966 c32 = c32.premultiplied();
1967 qt_rectfill<QRgbaFloat32>(reinterpret_cast<QRgbaFloat32 *>(d->data), c32,
1968 0, 0, d->width, d->height, d->bytes_per_line);
1969 }
1970 break;
1971 }
1972 default: {
1973 QPainter p(this);
1974 p.setCompositionMode(QPainter::CompositionMode_Source);
1975 p.fillRect(rect(), color);
1976 }}
1977}
1978
1979
1980
1981/*!
1982 Inverts all pixel values in the image.
1983
1984 The given invert \a mode only have a meaning when the image's
1985 depth is 32. The default \a mode is InvertRgb, which leaves the
1986 alpha channel unchanged. If the \a mode is InvertRgba, the alpha
1987 bits are also inverted.
1988
1989 Inverting an 8-bit image means to replace all pixels using color
1990 index \e i with a pixel using color index 255 minus \e i. The same
1991 is the case for a 1-bit image. Note that the color table is \e not
1992 changed.
1993
1994 If the image has a premultiplied alpha channel, the image is first
1995 converted to an unpremultiplied image format to be inverted and
1996 then converted back.
1997
1998 \sa {QImage#Image Transformations}{Image Transformations}
1999*/
2000
2001void QImage::invertPixels(InvertMode mode)
2002{
2003 if (!d)
2004 return;
2005
2006 detach();
2007
2008 // In case detach() ran out of memory
2009 if (!d)
2010 return;
2011
2012 QImage::Format originalFormat = d->format;
2013 // Inverting premultiplied pixels would produce invalid image data.
2014 if (hasAlphaChannel() && qPixelLayouts[d->format].premultiplied) {
2015 if (d->format == QImage::Format_RGBA16FPx4_Premultiplied) {
2016 if (!d->convertInPlace(QImage::Format_RGBA16FPx4, { }))
2017 *this = convertToFormat(QImage::Format_RGBA16FPx4);
2018 } else if (d->format == QImage::Format_RGBA32FPx4_Premultiplied) {
2019 if (!d->convertInPlace(QImage::Format_RGBA32FPx4, { }))
2020 *this = convertToFormat(QImage::Format_RGBA32FPx4);
2021 } else if (depth() > 32) {
2022 if (!d->convertInPlace(QImage::Format_RGBA64, { }))
2023 *this = convertToFormat(QImage::Format_RGBA64);
2024 } else {
2025 if (!d->convertInPlace(QImage::Format_ARGB32, { }))
2026 *this = convertToFormat(QImage::Format_ARGB32);
2027 }
2028 }
2029
2030 if (depth() < 32) {
2031 // This assumes no alpha-channel as the only formats with non-premultipled alpha are 32bit.
2032 qsizetype bpl = (qsizetype(d->width) * d->depth + 7) / 8;
2033 int pad = d->bytes_per_line - bpl;
2034 uchar *sl = d->data;
2035 for (int y=0; y<d->height; ++y) {
2036 for (qsizetype x=0; x<bpl; ++x)
2037 *sl++ ^= 0xff;
2038 sl += pad;
2039 }
2040 } else if (format() >= QImage::Format_RGBX16FPx4 && format() <= QImage::Format_RGBA16FPx4_Premultiplied) {
2041 qfloat16 *p = reinterpret_cast<qfloat16 *>(d->data);
2042 qfloat16 *end = reinterpret_cast<qfloat16 *>(d->data + d->nbytes);
2043 while (p < end) {
2044 p[0] = qfloat16(1) - p[0];
2045 p[1] = qfloat16(1) - p[1];
2046 p[2] = qfloat16(1) - p[2];
2047 if (mode == InvertRgba)
2048 p[3] = qfloat16(1) - p[3];
2049 p += 4;
2050 }
2051 } else if (format() >= QImage::Format_RGBX32FPx4 && format() <= QImage::Format_RGBA32FPx4_Premultiplied) {
2052 uchar *data = d->data;
2053 for (int y = 0; y < d->height; ++y) {
2054 float *p = reinterpret_cast<float *>(data);
2055 for (int x = 0; x < d->width; ++x) {
2056 p[0] = 1.0f - p[0];
2057 p[1] = 1.0f - p[1];
2058 p[2] = 1.0f - p[2];
2059 if (mode == InvertRgba)
2060 p[3] = 1.0f - p[3];
2061 p += 4;
2062 }
2063 data += d->bytes_per_line;
2064 }
2065 } else if (depth() == 64) {
2066 quint16 *p = (quint16*)d->data;
2067 quint16 *end = (quint16*)(d->data + d->nbytes);
2068 quint16 xorbits = 0xffff;
2069 while (p < end) {
2070 *p++ ^= xorbits;
2071 *p++ ^= xorbits;
2072 *p++ ^= xorbits;
2073 if (mode == InvertRgba)
2074 *p++ ^= xorbits;
2075 else
2076 p++;
2077 }
2078 } else {
2079 quint32 *p = (quint32*)d->data;
2080 quint32 *end = (quint32*)(d->data + d->nbytes);
2081 quint32 xorbits = 0xffffffff;
2082 switch (d->format) {
2083 case QImage::Format_RGBA8888:
2084 if (mode == InvertRgba)
2085 break;
2086 Q_FALLTHROUGH();
2087 case QImage::Format_RGBX8888:
2088#if Q_BYTE_ORDER == Q_BIG_ENDIAN
2089 xorbits = 0xffffff00;
2090 break;
2091#else
2092 xorbits = 0x00ffffff;
2093 break;
2094#endif
2095 case QImage::Format_ARGB32:
2096 if (mode == InvertRgba)
2097 break;
2098 Q_FALLTHROUGH();
2099 case QImage::Format_RGB32:
2100 xorbits = 0x00ffffff;
2101 break;
2102 case QImage::Format_BGR30:
2103 case QImage::Format_RGB30:
2104 xorbits = 0x3fffffff;
2105 break;
2106 default:
2107 Q_UNREACHABLE();
2108 xorbits = 0;
2109 break;
2110 }
2111 while (p < end)
2112 *p++ ^= xorbits;
2113 }
2114
2115 if (originalFormat != d->format) {
2116 if (!d->convertInPlace(originalFormat, { }))
2117 *this = convertToFormat(originalFormat);
2118 }
2119}
2120
2121// Windows defines these
2122#if defined(write)
2123# undef write
2124#endif
2125#if defined(close)
2126# undef close
2127#endif
2128#if defined(read)
2129# undef read
2130#endif
2131
2132/*!
2133 Resizes the color table to contain \a colorCount entries.
2134
2135 If the color table is expanded, all the extra colors will be set to
2136 transparent (i.e qRgba(0, 0, 0, 0)).
2137
2138 When the image is used, the color table must be large enough to
2139 have entries for all the pixel/index values present in the image,
2140 otherwise the results are undefined.
2141
2142 \sa colorCount(), colorTable(), setColor(), {QImage#Image
2143 Transformations}{Image Transformations}
2144*/
2145
2146void QImage::setColorCount(int colorCount)
2147{
2148 if (!d) {
2149 qWarning("QImage::setColorCount: null image");
2150 return;
2151 }
2152
2153 detachMetadata(true);
2154
2155 // In case detach() ran out of memory
2156 if (!d)
2157 return;
2158
2159 if (colorCount == d->colortable.size())
2160 return;
2161 if (colorCount <= 0) { // use no color table
2162 d->colortable.clear();
2163 return;
2164 }
2165 int nc = d->colortable.size();
2166 d->colortable.resize(colorCount);
2167 for (int i = nc; i < colorCount; ++i)
2168 d->colortable[i] = 0;
2169}
2170
2171/*!
2172 Returns the format of the image.
2173
2174 \sa {QImage#Image Formats}{Image Formats}
2175*/
2176QImage::Format QImage::format() const
2177{
2178 if (d) {
2179 // Class Invariant Check
2180 Q_ASSERT(d->format < NImageFormats);
2181 Q_ASSERT(d->format > Format_Invalid);
2182 }
2183 return d ? d->format : Format_Invalid;
2184}
2185
2186/*!
2187 \fn QImage QImage::convertToFormat(Format format, Qt::ImageConversionFlags flags) const &
2188 \fn QImage QImage::convertToFormat(Format format, Qt::ImageConversionFlags flags) &&
2189
2190 Returns a copy of the image in the given \a format.
2191
2192 The specified image conversion \a flags control how the image data
2193 is handled during the conversion process.
2194
2195 \sa convertTo(), {Image Formats}
2196*/
2197
2198/*!
2199 \fn QImage QImage::convertedTo(Format format, Qt::ImageConversionFlags flags) const &
2200 \fn QImage QImage::convertedTo(Format format, Qt::ImageConversionFlags flags) &&
2201 \since 6.0
2202
2203 Returns a copy of the image in the given \a format.
2204
2205 The specified image conversion \a flags control how the image data
2206 is handled during the conversion process.
2207
2208 \sa convertTo(), {Image Formats}
2209*/
2210
2211/*!
2212 \internal
2213*/
2214QImage QImage::convertToFormat_helper(Format format, Qt::ImageConversionFlags flags) const
2215{
2216 if (!d || d->format == format)
2217 return *this;
2218
2219 if (d->format == Format_Invalid || format <= Format_Invalid || format >= NImageFormats)
2220 return QImage();
2221
2222 const QPixelLayout *destLayout = &qPixelLayouts[format];
2223 Image_Converter converter = qimage_converter_map[d->format][format];
2224 if (!converter && format > QImage::Format_Indexed8 && d->format > QImage::Format_Indexed8) {
2225 if (qt_highColorPrecision(d->format, !destLayout->hasAlphaChannel)
2226 && qt_highColorPrecision(format, !hasAlphaChannel())) {
2227#if QT_CONFIG(raster_fp)
2228 if (qt_fpColorPrecision(d->format) && qt_fpColorPrecision(format))
2229 converter = convert_generic_over_rgba32f;
2230 else
2231#endif
2232 converter = convert_generic_over_rgb64;
2233 } else
2234 converter = convert_generic;
2235 }
2236 if (converter) {
2237 QImage image(d->width, d->height, format);
2238
2240
2241 copyMetadata(image.d, d);
2242
2243 converter(image.d, d, flags);
2244 return image;
2245 }
2246
2247 // Convert indexed formats over ARGB32 or RGB32 to the final format.
2248 Q_ASSERT(format != QImage::Format_ARGB32 && format != QImage::Format_RGB32);
2249 Q_ASSERT(d->format != QImage::Format_ARGB32 && d->format != QImage::Format_RGB32);
2250
2251 if (!hasAlphaChannel())
2252 return convertToFormat(Format_RGB32, flags).convertToFormat(format, flags);
2253
2254 return convertToFormat(Format_ARGB32, flags).convertToFormat(format, flags);
2255}
2256
2257/*!
2258 \internal
2259*/
2260bool QImage::convertToFormat_inplace(Format format, Qt::ImageConversionFlags flags)
2261{
2262 return d && d->convertInPlace(format, flags);
2263}
2264
2265static inline int pixel_distance(QRgb p1, QRgb p2) {
2266 int r1 = qRed(p1);
2267 int g1 = qGreen(p1);
2268 int b1 = qBlue(p1);
2269 int a1 = qAlpha(p1);
2270
2271 int r2 = qRed(p2);
2272 int g2 = qGreen(p2);
2273 int b2 = qBlue(p2);
2274 int a2 = qAlpha(p2);
2275
2276 return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2) + abs(a1 - a2);
2277}
2278
2279static inline int closestMatch(QRgb pixel, const QList<QRgb> &clut) {
2280 int idx = 0;
2281 int current_distance = INT_MAX;
2282 for (int i=0; i<clut.size(); ++i) {
2283 int dist = pixel_distance(pixel, clut.at(i));
2284 if (dist < current_distance) {
2285 current_distance = dist;
2286 idx = i;
2287 }
2288 }
2289 return idx;
2290}
2291
2292static QImage convertWithPalette(const QImage &src, QImage::Format format,
2293 const QList<QRgb> &clut) {
2294 QImage dest(src.size(), format);
2295 dest.setColorTable(clut);
2296
2297 copyMetadata(QImageData::get(dest), QImageData::get(src));
2298
2299 int h = src.height();
2300 int w = src.width();
2301
2302 QHash<QRgb, int> cache;
2303
2304 if (format == QImage::Format_Indexed8) {
2305 for (int y=0; y<h; ++y) {
2306 const QRgb *src_pixels = (const QRgb *) src.scanLine(y);
2307 uchar *dest_pixels = (uchar *) dest.scanLine(y);
2308 for (int x=0; x<w; ++x) {
2309 int src_pixel = src_pixels[x];
2310 int value = cache.value(src_pixel, -1);
2311 if (value == -1) {
2312 value = closestMatch(src_pixel, clut);
2313 cache.insert(src_pixel, value);
2314 }
2315 dest_pixels[x] = (uchar) value;
2316 }
2317 }
2318 } else {
2319 QList<QRgb> table = clut;
2320 table.resize(2);
2321 for (int y=0; y<h; ++y) {
2322 const QRgb *src_pixels = (const QRgb *) src.scanLine(y);
2323 for (int x=0; x<w; ++x) {
2324 int src_pixel = src_pixels[x];
2325 int value = cache.value(src_pixel, -1);
2326 if (value == -1) {
2327 value = closestMatch(src_pixel, table);
2328 cache.insert(src_pixel, value);
2329 }
2330 dest.setPixel(x, y, value);
2331 }
2332 }
2333 }
2334
2335 return dest;
2336}
2337
2338/*!
2339 \overload
2340
2341 Returns a copy of the image converted to the given \a format,
2342 using the specified \a colorTable.
2343
2344 Conversion from RGB formats to indexed formats is a slow operation
2345 and will use a straightforward nearest color approach, with no
2346 dithering.
2347*/
2348QImage QImage::convertToFormat(Format format, const QList<QRgb> &colorTable, Qt::ImageConversionFlags flags) const
2349{
2350 if (!d || d->format == format)
2351 return *this;
2352
2353 if (format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
2354 return QImage();
2355 if (format <= QImage::Format_Indexed8)
2356 return convertWithPalette(convertToFormat(QImage::Format_ARGB32, flags), format, colorTable);
2357
2358 return convertToFormat(format, flags);
2359}
2360
2361/*!
2362 \since 5.9
2363
2364 Changes the format of the image to \a format without changing the
2365 data. Only works between formats of the same depth.
2366
2367 Returns \c true if successful.
2368
2369 This function can be used to change images with alpha-channels to
2370 their corresponding opaque formats if the data is known to be opaque-only,
2371 or to change the format of a given image buffer before overwriting
2372 it with new data.
2373
2374 \warning The function does not check if the image data is valid in the
2375 new format and will still return \c true if the depths are compatible.
2376 Operations on an image with invalid data are undefined.
2377
2378 \warning If the image is not detached, this will cause the data to be
2379 copied.
2380
2381 \sa hasAlphaChannel(), convertToFormat()
2382*/
2383
2384bool QImage::reinterpretAsFormat(Format format)
2385{
2386 if (format <= Format_Invalid || format >= NImageFormats)
2387 return false;
2388 if (!d)
2389 return false;
2390 if (d->format == format)
2391 return true;
2392 if (qt_depthForFormat(format) != qt_depthForFormat(d->format))
2393 return false;
2394 if (!isDetached()) { // Detach only if shared, not for read-only data.
2395 QImageData *oldD = d;
2396 detach();
2397 // In case detach() ran out of memory
2398 if (!d) {
2399 d = oldD;
2400 d->ref.ref();
2401 return false;
2402 }
2403 }
2404
2405 d->format = format;
2406 return true;
2407}
2408
2409/*!
2410 \since 5.13
2411
2412 Converts the image to the given \a format in place, detaching if necessary.
2413
2414 The specified image conversion \a flags control how the image data
2415 is handled during the conversion process.
2416
2417 \sa convertedTo()
2418*/
2419
2420void QImage::convertTo(Format format, Qt::ImageConversionFlags flags)
2421{
2422 if (!d || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
2423 return;
2424
2425 if (d->format == format)
2426 return;
2427
2428 detach();
2429 if (convertToFormat_inplace(format, flags))
2430 return;
2431
2432 *this = convertToFormat_helper(format, flags);
2433}
2434
2435/*!
2436 \fn bool QImage::valid(const QPoint &pos) const
2437
2438 Returns \c true if \a pos is a valid coordinate pair within the
2439 image; otherwise returns \c false.
2440
2441 \sa rect(), QRect::contains()
2442*/
2443
2444/*!
2445 \overload
2446
2447 Returns \c true if QPoint(\a x, \a y) is a valid coordinate pair
2448 within the image; otherwise returns \c false.
2449*/
2450bool QImage::valid(int x, int y) const
2451{
2452 return d
2453 && x >= 0 && x < d->width
2454 && y >= 0 && y < d->height;
2455}
2456
2457/*!
2458 \fn int QImage::pixelIndex(const QPoint &position) const
2459
2460 Returns the pixel index at the given \a position.
2461
2462 If \a position is not valid, or if the image is not a paletted
2463 image (depth() > 8), the results are undefined.
2464
2465 \sa valid(), depth(), {QImage#Pixel Manipulation}{Pixel Manipulation}
2466*/
2467
2468/*!
2469 \overload
2470
2471 Returns the pixel index at (\a x, \a y).
2472*/
2473int QImage::pixelIndex(int x, int y) const
2474{
2475 if (!d || x < 0 || x >= d->width || y < 0 || y >= height()) {
2476 qWarning("QImage::pixelIndex: coordinate (%d,%d) out of range", x, y);
2477 return -12345;
2478 }
2479 const uchar * s = scanLine(y);
2480 switch(d->format) {
2481 case Format_Mono:
2482 return (*(s + (x >> 3)) >> (7- (x & 7))) & 1;
2483 case Format_MonoLSB:
2484 return (*(s + (x >> 3)) >> (x & 7)) & 1;
2485 case Format_Indexed8:
2486 return (int)s[x];
2487 default:
2488 qWarning("QImage::pixelIndex: Not applicable for %d-bpp images (no palette)", d->depth);
2489 }
2490 return 0;
2491}
2492
2493
2494/*!
2495 \fn QRgb QImage::pixel(const QPoint &position) const
2496
2497 Returns the color of the pixel at the given \a position.
2498
2499 If the \a position is not valid, the results are undefined.
2500
2501 \warning This function is expensive when used for massive pixel
2502 manipulations. Use constBits() or constScanLine() when many
2503 pixels needs to be read.
2504
2505 \sa setPixel(), valid(), constBits(), constScanLine(), {QImage#Pixel Manipulation}{Pixel
2506 Manipulation}
2507*/
2508
2509/*!
2510 \overload
2511
2512 Returns the color of the pixel at coordinates (\a x, \a y).
2513*/
2514QRgb QImage::pixel(int x, int y) const
2515{
2516 if (!d || x < 0 || x >= d->width || y < 0 || y >= d->height) {
2517 qWarning("QImage::pixel: coordinate (%d,%d) out of range", x, y);
2518 return 12345;
2519 }
2520
2521 const uchar *s = d->data + y * d->bytes_per_line;
2522
2523 int index = -1;
2524 switch (d->format) {
2525 case Format_Mono:
2526 index = (*(s + (x >> 3)) >> (~x & 7)) & 1;
2527 break;
2528 case Format_MonoLSB:
2529 index = (*(s + (x >> 3)) >> (x & 7)) & 1;
2530 break;
2531 case Format_Indexed8:
2532 index = s[x];
2533 break;
2534 default:
2535 break;
2536 }
2537 if (index >= 0) { // Indexed format
2538 if (index >= d->colortable.size()) {
2539 qWarning("QImage::pixel: color table index %d out of range.", index);
2540 return 0;
2541 }
2542 return d->colortable.at(index);
2543 }
2544 std::optional<QRgb> out;
2545 switch (d->format) {
2546 case Format_RGB32:
2547 case Format_ARGB32: // Keep old behaviour.
2548 case Format_ARGB32_Premultiplied:
2549 out = reinterpret_cast<const QRgb *>(s)[x];
2550 break;
2551 case Format_RGBX8888:
2552 case Format_RGBA8888: // Match ARGB32 behavior.
2553 case Format_RGBA8888_Premultiplied:
2554 out = RGBA2ARGB(reinterpret_cast<const quint32 *>(s)[x]);
2555 break;
2556 case Format_BGR30:
2557 case Format_A2BGR30_Premultiplied:
2558 out = qConvertA2rgb30ToArgb32<PixelOrderBGR>(reinterpret_cast<const quint32 *>(s)[x]);
2559 break;
2560 case Format_RGB30:
2561 case Format_A2RGB30_Premultiplied:
2562 out = qConvertA2rgb30ToArgb32<PixelOrderRGB>(reinterpret_cast<const quint32 *>(s)[x]);
2563 break;
2564 case Format_RGB16:
2565 return qConvertRgb16To32(reinterpret_cast<const quint16 *>(s)[x]);
2566 case Format_RGBX64:
2567 case Format_RGBA64: // Match ARGB32 behavior.
2568 case Format_RGBA64_Premultiplied:
2569 out = reinterpret_cast<const QRgba64 *>(s)[x].toArgb32();
2570 break;
2571 case Format_RGBX16FPx4:
2572 case Format_RGBA16FPx4: // Match ARGB32 behavior.
2573 case Format_RGBA16FPx4_Premultiplied:
2574 out = reinterpret_cast<const QRgbaFloat16 *>(s)[x].toArgb32();
2575 break;
2576 case Format_RGBX32FPx4:
2577 case Format_RGBA32FPx4: // Match ARGB32 behavior.
2578 case Format_RGBA32FPx4_Premultiplied:
2579 out = reinterpret_cast<const QRgbaFloat32 *>(s)[x].toArgb32();
2580 default:
2581 break;
2582 }
2583 const QPixelLayout *layout = &qPixelLayouts[d->format];
2584 if (out) {
2585 // Fix up alpha
2586 if (!layout->hasAlphaChannel)
2587 *out |= 0xff000000;
2588 return *out;
2589 }
2590 uint result;
2591 return *layout->fetchToARGB32PM(&result, s, x, 1, nullptr, nullptr);
2592}
2593
2594/*!
2595 \fn void QImage::setPixel(const QPoint &position, uint index_or_rgb)
2596
2597 Sets the pixel index or color at the given \a position to \a
2598 index_or_rgb.
2599
2600 If the image's format is either monochrome or paletted, the given \a
2601 index_or_rgb value must be an index in the image's color table,
2602 otherwise the parameter must be a QRgb value.
2603
2604 If \a position is not a valid coordinate pair in the image, or if
2605 \a index_or_rgb >= colorCount() in the case of monochrome and
2606 paletted images, the result is undefined.
2607
2608 \warning This function is expensive due to the call of the internal
2609 \c{detach()} function called within; if performance is a concern, we
2610 recommend the use of scanLine() or bits() to access pixel data directly.
2611
2612 \sa pixel(), {QImage#Pixel Manipulation}{Pixel Manipulation}
2613*/
2614
2615/*!
2616 \overload
2617
2618 Sets the pixel index or color at (\a x, \a y) to \a index_or_rgb.
2619*/
2620void QImage::setPixel(int x, int y, uint index_or_rgb)
2621{
2622 if (!d || x < 0 || x >= width() || y < 0 || y >= height()) {
2623 qWarning("QImage::setPixel: coordinate (%d,%d) out of range", x, y);
2624 return;
2625 }
2626 // detach is called from within scanLine
2627 uchar * s = scanLine(y);
2628 switch(d->format) {
2629 case Format_Mono:
2630 case Format_MonoLSB:
2631 if (index_or_rgb > 1) {
2632 qWarning("QImage::setPixel: Index %d out of range", index_or_rgb);
2633 } else if (format() == Format_MonoLSB) {
2634 if (index_or_rgb==0)
2635 *(s + (x >> 3)) &= ~(1 << (x & 7));
2636 else
2637 *(s + (x >> 3)) |= (1 << (x & 7));
2638 } else {
2639 if (index_or_rgb==0)
2640 *(s + (x >> 3)) &= ~(1 << (7-(x & 7)));
2641 else
2642 *(s + (x >> 3)) |= (1 << (7-(x & 7)));
2643 }
2644 return;
2645 case Format_Indexed8:
2646 if (index_or_rgb >= (uint)d->colortable.size()) {
2647 qWarning("QImage::setPixel: Index %d out of range", index_or_rgb);
2648 return;
2649 }
2650 s[x] = index_or_rgb;
2651 return;
2652 case Format_RGB32:
2653 //make sure alpha is 255, we depend on it in qdrawhelper for cases
2654 // when image is set as a texture pattern on a qbrush
2655 ((uint *)s)[x] = 0xff000000 | index_or_rgb;
2656 return;
2657 case Format_ARGB32:
2658 case Format_ARGB32_Premultiplied:
2659 ((uint *)s)[x] = index_or_rgb;
2660 return;
2661 case Format_RGB16:
2662 ((quint16 *)s)[x] = qConvertRgb32To16(index_or_rgb);
2663 return;
2664 case Format_RGBX8888:
2665 ((uint *)s)[x] = ARGB2RGBA(0xff000000 | index_or_rgb);
2666 return;
2667 case Format_RGBA8888:
2668 case Format_RGBA8888_Premultiplied:
2669 ((uint *)s)[x] = ARGB2RGBA(index_or_rgb);
2670 return;
2671 case Format_BGR30:
2672 ((uint *)s)[x] = qConvertRgb32ToRgb30<PixelOrderBGR>(index_or_rgb);
2673 return;
2674 case Format_A2BGR30_Premultiplied:
2675 ((uint *)s)[x] = qConvertArgb32ToA2rgb30<PixelOrderBGR>(index_or_rgb);
2676 return;
2677 case Format_RGB30:
2678 ((uint *)s)[x] = qConvertRgb32ToRgb30<PixelOrderRGB>(index_or_rgb);
2679 return;
2680 case Format_A2RGB30_Premultiplied:
2681 ((uint *)s)[x] = qConvertArgb32ToA2rgb30<PixelOrderRGB>(index_or_rgb);
2682 return;
2683 case Format_RGBX64:
2684 ((QRgba64 *)s)[x] = QRgba64::fromArgb32(index_or_rgb | 0xff000000);
2685 return;
2686 case Format_RGBA64:
2687 case Format_RGBA64_Premultiplied:
2688 ((QRgba64 *)s)[x] = QRgba64::fromArgb32(index_or_rgb);
2689 return;
2690 case Format_RGBX16FPx4:
2691 ((QRgbaFloat16 *)s)[x] = QRgbaFloat16::fromArgb32(index_or_rgb | 0xff000000);
2692 return;
2693 case Format_RGBA16FPx4:
2694 case Format_RGBA16FPx4_Premultiplied:
2695 ((QRgbaFloat16 *)s)[x] = QRgbaFloat16::fromArgb32(index_or_rgb);
2696 return;
2697 case Format_RGBX32FPx4:
2698 ((QRgbaFloat32 *)s)[x] = QRgbaFloat32::fromArgb32(index_or_rgb | 0xff000000);
2699 return;
2700 case Format_RGBA32FPx4:
2701 case Format_RGBA32FPx4_Premultiplied:
2702 ((QRgbaFloat32 *)s)[x] = QRgbaFloat32::fromArgb32(index_or_rgb);
2703 return;
2704 case Format_Invalid:
2705 case NImageFormats:
2706 Q_ASSERT(false);
2707 return;
2708 default:
2709 break;
2710 }
2711
2712 const QPixelLayout *layout = &qPixelLayouts[d->format];
2713 if (!hasAlphaChannel())
2714 layout->storeFromRGB32(s, &index_or_rgb, x, 1, nullptr, nullptr);
2715 else
2716 layout->storeFromARGB32PM(s, &index_or_rgb, x, 1, nullptr, nullptr);
2717}
2718
2719/*!
2720 \fn QColor QImage::pixelColor(const QPoint &position) const
2721 \since 5.6
2722
2723 Returns the color of the pixel at the given \a position as a QColor.
2724
2725 If the \a position is not valid, an invalid QColor is returned.
2726
2727 \warning This function is expensive when used for massive pixel
2728 manipulations. Use constBits() or constScanLine() when many
2729 pixels needs to be read.
2730
2731 \sa setPixel(), valid(), constBits(), constScanLine(), {QImage#Pixel Manipulation}{Pixel
2732 Manipulation}
2733*/
2734
2735/*!
2736 \overload
2737 \since 5.6
2738
2739 Returns the color of the pixel at coordinates (\a x, \a y) as a QColor.
2740*/
2741QColor QImage::pixelColor(int x, int y) const
2742{
2743 if (!d || x < 0 || x >= d->width || y < 0 || y >= height()) {
2744 qWarning("QImage::pixelColor: coordinate (%d,%d) out of range", x, y);
2745 return QColor();
2746 }
2747
2748 QRgba64 c;
2749 const uchar * s = constScanLine(y);
2750 switch (d->format) {
2751 case Format_BGR30:
2752 case Format_A2BGR30_Premultiplied:
2753 c = qConvertA2rgb30ToRgb64<PixelOrderBGR>(reinterpret_cast<const quint32 *>(s)[x]);
2754 break;
2755 case Format_RGB30:
2756 case Format_A2RGB30_Premultiplied:
2757 c = qConvertA2rgb30ToRgb64<PixelOrderRGB>(reinterpret_cast<const quint32 *>(s)[x]);
2758 break;
2759 case Format_RGBX64:
2760 case Format_RGBA64:
2761 case Format_RGBA64_Premultiplied:
2762 c = reinterpret_cast<const QRgba64 *>(s)[x];
2763 break;
2764 case Format_Grayscale16: {
2765 quint16 v = reinterpret_cast<const quint16 *>(s)[x];
2766 return QColor(qRgba64(v, v, v, 0xffff));
2767 }
2768 case Format_RGBX16FPx4:
2769 case Format_RGBA16FPx4:
2770 case Format_RGBA16FPx4_Premultiplied: {
2771 QRgbaFloat16 p = reinterpret_cast<const QRgbaFloat16 *>(s)[x];
2772 if (d->format == Format_RGBA16FPx4_Premultiplied)
2773 p = p.unpremultiplied();
2774 else if (d->format == Format_RGBX16FPx4)
2775 p.setAlpha(1.0f);
2776 QColor color;
2777 color.setRgbF(p.red(), p.green(), p.blue(), p.alpha());
2778 return color;
2779 }
2780 case Format_RGBX32FPx4:
2781 case Format_RGBA32FPx4:
2782 case Format_RGBA32FPx4_Premultiplied: {
2783 QRgbaFloat32 p = reinterpret_cast<const QRgbaFloat32 *>(s)[x];
2784 if (d->format == Format_RGBA32FPx4_Premultiplied)
2785 p = p.unpremultiplied();
2786 else if (d->format == Format_RGBX32FPx4)
2787 p.setAlpha(1.0f);
2788 QColor color;
2789 color.setRgbF(p.red(), p.green(), p.blue(), p.alpha());
2790 return color;
2791 }
2792 default:
2793 c = QRgba64::fromArgb32(pixel(x, y));
2794 break;
2795 }
2796 // Alpha fix up
2797 switch (d->format) {
2798 case Format_BGR30:
2799 case Format_RGB30:
2800 case Format_RGBX64:
2801 c.setAlpha(65535);
2802 break;
2803 default:
2804 break;
2805 }
2806 // QColor is always unpremultiplied
2807 if (hasAlphaChannel() && qPixelLayouts[d->format].premultiplied)
2808 c = c.unpremultiplied();
2809 return QColor(c);
2810}
2811
2812/*!
2813 \fn void QImage::setPixelColor(const QPoint &position, const QColor &color)
2814 \since 5.6
2815
2816 Sets the color at the given \a position to \a color.
2817
2818 If \a position is not a valid coordinate pair in the image, or
2819 the image's format is either monochrome or paletted, the result is undefined.
2820
2821 \warning This function is expensive due to the call of the internal
2822 \c{detach()} function called within; if performance is a concern, we
2823 recommend the use of scanLine() or bits() to access pixel data directly.
2824
2825 \sa pixel(), bits(), scanLine(), {QImage#Pixel Manipulation}{Pixel Manipulation}
2826*/
2827
2828/*!
2829 \overload
2830 \since 5.6
2831
2832 Sets the pixel color at (\a x, \a y) to \a color.
2833*/
2834void QImage::setPixelColor(int x, int y, const QColor &color)
2835{
2836 if (!d || x < 0 || x >= width() || y < 0 || y >= height()) {
2837 qWarning("QImage::setPixelColor: coordinate (%d,%d) out of range", x, y);
2838 return;
2839 }
2840
2841 if (!color.isValid()) {
2842 qWarning("QImage::setPixelColor: color is invalid");
2843 return;
2844 }
2845
2846 // QColor is always unpremultiplied
2847 QRgba64 c = color.rgba64();
2848 if (!hasAlphaChannel())
2849 c.setAlpha(65535);
2850 else if (qPixelLayouts[d->format].premultiplied)
2851 c = c.premultiplied();
2852 // detach is called from within scanLine
2853 uchar * s = scanLine(y);
2854 switch (d->format) {
2855 case Format_Mono:
2856 case Format_MonoLSB:
2857 case Format_Indexed8:
2858 qWarning("QImage::setPixelColor: called on monochrome or indexed format");
2859 return;
2860 case Format_BGR30:
2861 ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderBGR>(c) | 0xc0000000;
2862 return;
2863 case Format_A2BGR30_Premultiplied:
2864 ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderBGR>(c);
2865 return;
2866 case Format_RGB30:
2867 ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderRGB>(c) | 0xc0000000;
2868 return;
2869 case Format_A2RGB30_Premultiplied:
2870 ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderRGB>(c);
2871 return;
2872 case Format_RGBX64:
2873 case Format_RGBA64:
2874 case Format_RGBA64_Premultiplied:
2875 ((QRgba64 *)s)[x] = c;
2876 return;
2877 case Format_RGBX16FPx4:
2878 case Format_RGBA16FPx4:
2879 case Format_RGBA16FPx4_Premultiplied: {
2880 float r, g, b, a;
2881 color.getRgbF(&r, &g, &b, &a);
2882 if (d->format == Format_RGBX16FPx4)
2883 a = 1.0f;
2884 QRgbaFloat16 c16f{qfloat16(r), qfloat16(g), qfloat16(b), qfloat16(a)};
2885 if (d->format == Format_RGBA16FPx4_Premultiplied)
2886 c16f = c16f.premultiplied();
2887 ((QRgbaFloat16 *)s)[x] = c16f;
2888 return;
2889 }
2890 case Format_RGBX32FPx4:
2891 case Format_RGBA32FPx4:
2892 case Format_RGBA32FPx4_Premultiplied: {
2893 float r, g, b, a;
2894 color.getRgbF(&r, &g, &b, &a);
2895 if (d->format == Format_RGBX32FPx4)
2896 a = 1.0f;
2897 QRgbaFloat32 c32f{r, g, b, a};
2898 if (d->format == Format_RGBA32FPx4_Premultiplied)
2899 c32f = c32f.premultiplied();
2900 ((QRgbaFloat32 *)s)[x] = c32f;
2901 return;
2902 }
2903 default:
2904 setPixel(x, y, c.toArgb32());
2905 return;
2906 }
2907}
2908
2909/*!
2910 Returns \c true if all the colors in the image are shades of gray
2911 (i.e. their red, green and blue components are equal); otherwise
2912 false.
2913
2914 Note that this function is slow for images without color table.
2915
2916 \sa isGrayscale()
2917*/
2918bool QImage::allGray() const
2919{
2920 if (!d)
2921 return true;
2922
2923 switch (d->format) {
2924 case Format_Mono:
2925 case Format_MonoLSB:
2926 case Format_Indexed8:
2927 for (int i = 0; i < d->colortable.size(); ++i) {
2928 if (!qIsGray(d->colortable.at(i)))
2929 return false;
2930 }
2931 return true;
2932 case Format_Alpha8:
2933 return false;
2934 case Format_Grayscale8:
2935 case Format_Grayscale16:
2936 return true;
2937 case Format_RGB32:
2938 case Format_ARGB32:
2939 case Format_ARGB32_Premultiplied:
2940#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
2941 case Format_RGBX8888:
2942 case Format_RGBA8888:
2943 case Format_RGBA8888_Premultiplied:
2944#endif
2945 for (int j = 0; j < d->height; ++j) {
2946 const QRgb *b = (const QRgb *)constScanLine(j);
2947 for (int i = 0; i < d->width; ++i) {
2948 if (!qIsGray(b[i]))
2949 return false;
2950 }
2951 }
2952 return true;
2953 case Format_RGB16:
2954 for (int j = 0; j < d->height; ++j) {
2955 const quint16 *b = (const quint16 *)constScanLine(j);
2956 for (int i = 0; i < d->width; ++i) {
2957 if (!qIsGray(qConvertRgb16To32(b[i])))
2958 return false;
2959 }
2960 }
2961 return true;
2962 default:
2963 break;
2964 }
2965
2966 Q_DECL_UNINITIALIZED uint buffer[BufferSize];
2967 const QPixelLayout *layout = &qPixelLayouts[d->format];
2968 const auto fetch = layout->fetchToARGB32PM;
2969 for (int j = 0; j < d->height; ++j) {
2970 const uchar *b = constScanLine(j);
2971 int x = 0;
2972 while (x < d->width) {
2973 int l = qMin(d->width - x, BufferSize);
2974 const uint *ptr = fetch(buffer, b, x, l, nullptr, nullptr);
2975 for (int i = 0; i < l; ++i) {
2976 if (!qIsGray(ptr[i]))
2977 return false;
2978 }
2979 x += l;
2980 }
2981 }
2982 return true;
2983}
2984
2985/*!
2986 For 32-bit images, this function is equivalent to allGray().
2987
2988 For color indexed images, this function returns \c true if
2989 color(i) is QRgb(i, i, i) for all indexes of the color table;
2990 otherwise returns \c false.
2991
2992 \sa allGray(), {QImage#Image Formats}{Image Formats}
2993*/
2994bool QImage::isGrayscale() const
2995{
2996 if (!d)
2997 return false;
2998
2999 if (d->format == QImage::Format_Alpha8)
3000 return false;
3001
3002 if (d->format == QImage::Format_Grayscale8 || d->format == QImage::Format_Grayscale16)
3003 return true;
3004
3005 switch (depth()) {
3006 case 32:
3007 case 24:
3008 case 16:
3009 return allGray();
3010 case 8: {
3011 Q_ASSERT(d->format == QImage::Format_Indexed8);
3012 for (int i = 0; i < colorCount(); i++)
3013 if (d->colortable.at(i) != qRgb(i,i,i))
3014 return false;
3015 return true;
3016 }
3017 }
3018 return false;
3019}
3020
3021/*!
3022 \fn QImage QImage::scaled(int width, int height, Qt::AspectRatioMode aspectRatioMode,
3023 Qt::TransformationMode transformMode) const
3024 \overload
3025
3026 Returns a copy of the image scaled to a rectangle with the given
3027 \a width and \a height according to the given \a aspectRatioMode
3028 and \a transformMode.
3029
3030 If either the \a width or the \a height is zero or negative, this
3031 function returns a null image.
3032*/
3033
3034/*!
3035 \fn QImage QImage::scaled(const QSize &size, Qt::AspectRatioMode aspectRatioMode,
3036 Qt::TransformationMode transformMode) const
3037
3038 Returns a copy of the image scaled to a rectangle defined by the
3039 given \a size according to the given \a aspectRatioMode and \a
3040 transformMode.
3041
3042 \image qimage-scaling.png {Illustration showing three different
3043 ways to scale images with Aspect Ratio Mode}
3044
3045 \list
3046 \li If \a aspectRatioMode is Qt::IgnoreAspectRatio, the image
3047 is scaled to \a size.
3048 \li If \a aspectRatioMode is Qt::KeepAspectRatio, the image is
3049 scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
3050 \li If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
3051 the image is scaled to a rectangle as small as possible
3052 outside \a size, preserving the aspect ratio.
3053 \endlist
3054
3055 \warning Care should be taken if using Qt::KeepAspectRatioByExpanding mode on untrusted images.
3056 For an input with extreme aspect ratio, it can easily result in a huge output image, causing
3057 memory exhaustion.
3058
3059 If the given \a size is empty, this function returns a null image.
3060
3061 \sa isNull(), {QImage#Image Transformations}{Image
3062 Transformations}
3063*/
3064QImage Q_TRACE_INSTRUMENT(qtgui) QImage::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
3065{
3066 if (!d) {
3067 qWarning("QImage::scaled: Image is a null image");
3068 return QImage();
3069 }
3070 if (s.isEmpty())
3071 return QImage();
3072
3073 QSize newSize = size();
3074 if (aspectMode == Qt::KeepAspectRatioByExpanding) {
3075 const QSizeF fs = QSizeF(newSize).scaled(s, aspectMode);
3076 if (std::max(fs.width(), fs.height()) > INT_MAX)
3077 return QImage();
3078 }
3079 newSize.scale(s, aspectMode);
3080 newSize.rwidth() = qMax(newSize.width(), 1);
3081 newSize.rheight() = qMax(newSize.height(), 1);
3082 if (newSize == size())
3083 return *this;
3084
3085 Q_TRACE_SCOPE(QImage_scaled, s, aspectMode, mode);
3086
3087 QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(), (qreal)newSize.height() / height());
3088 QImage img = transformed(wm, mode);
3089 return img;
3090}
3091
3092/*!
3093 \fn QImage QImage::scaledToWidth(int width, Qt::TransformationMode mode) const
3094
3095 Returns a scaled copy of the image. The returned image is scaled
3096 to the given \a width using the specified transformation \a
3097 mode.
3098
3099 This function automatically calculates the height of the image so
3100 that its aspect ratio is preserved.
3101
3102 \warning Care should be taken if using this function on untrusted images. For an input with
3103 extreme aspect ratio, it can easily result in a huge output image, causing memory exhaustion.
3104
3105 If the given \a width is 0 or negative, a null image is returned.
3106
3107 \sa {QImage#Image Transformations}{Image Transformations}
3108*/
3109QImage Q_TRACE_INSTRUMENT(qtgui) QImage::scaledToWidth(int w, Qt::TransformationMode mode) const
3110{
3111 if (!d) {
3112 qWarning("QImage::scaleWidth: Image is a null image");
3113 return QImage();
3114 }
3115 if (w <= 0)
3116 return QImage();
3117
3118 Q_TRACE_SCOPE(QImage_scaledToWidth, w, mode);
3119
3120 qreal factor = (qreal) w / width();
3121 QTransform wm = QTransform::fromScale(factor, factor);
3122 return transformed(wm, mode);
3123}
3124
3125/*!
3126 \fn QImage QImage::scaledToHeight(int height, Qt::TransformationMode mode) const
3127
3128 Returns a scaled copy of the image. The returned image is scaled
3129 to the given \a height using the specified transformation \a
3130 mode.
3131
3132 This function automatically calculates the width of the image so that
3133 the ratio of the image is preserved.
3134
3135 \warning Care should be taken if using this function on untrusted images. For an input with
3136 extreme aspect ratio, it can easily result in a huge output image, causing memory exhaustion.
3137
3138 If the given \a height is 0 or negative, a null image is returned.
3139
3140 \sa {QImage#Image Transformations}{Image Transformations}
3141*/
3142QImage Q_TRACE_INSTRUMENT(qtgui) QImage::scaledToHeight(int h, Qt::TransformationMode mode) const
3143{
3144 if (!d) {
3145 qWarning("QImage::scaleHeight: Image is a null image");
3146 return QImage();
3147 }
3148 if (h <= 0)
3149 return QImage();
3150
3151 Q_TRACE_SCOPE(QImage_scaledToHeight, h, mode);
3152
3153 qreal factor = (qreal) h / height();
3154 QTransform wm = QTransform::fromScale(factor, factor);
3155 return transformed(wm, mode);
3156}
3157
3158/*!
3159 Builds and returns a 1-bpp mask from the alpha buffer in this
3160 image. Returns a null image if the image's format is
3161 QImage::Format_RGB32.
3162
3163 The \a flags argument is a bitwise-OR of the
3164 Qt::ImageConversionFlags, and controls the conversion
3165 process. Passing 0 for flags sets all the default options.
3166
3167 The returned image has little-endian bit order (i.e. the image's
3168 format is QImage::Format_MonoLSB), which you can convert to
3169 big-endian (QImage::Format_Mono) using the convertToFormat()
3170 function.
3171
3172 \sa createHeuristicMask(), {QImage#Image Transformations}{Image
3173 Transformations}
3174*/
3175QImage Q_TRACE_INSTRUMENT(qtgui) QImage::createAlphaMask(Qt::ImageConversionFlags flags) const
3176{
3177 if (!d || d->format == QImage::Format_RGB32)
3178 return QImage();
3179
3180 if (d->depth == 1) {
3181 // A monochrome pixmap, with alpha channels on those two colors.
3182 // Pretty unlikely, so use less efficient solution.
3183 return convertToFormat(Format_Indexed8, flags).createAlphaMask(flags);
3184 }
3185
3186 if (d->format != Format_Indexed8 && d->format != Format_ARGB32
3187 && d->format != Format_ARGB32_Premultiplied) {
3188 // dither_to_Mono() only reads alpha from a color table or from ARGB32 pixels.
3189 return convertToFormat(Format_ARGB32_Premultiplied, flags).createAlphaMask(flags);
3190 }
3191
3192 QImage mask(d->width, d->height, Format_MonoLSB);
3193 if (!mask.isNull()) {
3194 dither_to_Mono(mask.d, d, flags, true);
3195 copyPhysicalMetadata(mask.d, d);
3196 }
3197 return mask;
3198}
3199
3200#ifndef QT_NO_IMAGE_HEURISTIC_MASK
3201/*!
3202 Creates and returns a 1-bpp heuristic mask for this image.
3203
3204 The function works by selecting a color from one of the corners,
3205 then chipping away pixels of that color starting at all the edges.
3206 The four corners vote for which color is to be masked away. In
3207 case of a draw (this generally means that this function is not
3208 applicable to the image), the result is arbitrary.
3209
3210 The returned image has little-endian bit order (i.e. the image's
3211 format is QImage::Format_MonoLSB), which you can convert to
3212 big-endian (QImage::Format_Mono) using the convertToFormat()
3213 function.
3214
3215 If \a clipTight is true (the default) the mask is just large
3216 enough to cover the pixels; otherwise, the mask is larger than the
3217 data pixels.
3218
3219 Note that this function disregards the alpha buffer.
3220
3221 \sa createAlphaMask(), {QImage#Image Transformations}{Image
3222 Transformations}
3223*/
3224
3225QImage QImage::createHeuristicMask(bool clipTight) const
3226{
3227 if (!d)
3228 return QImage();
3229
3230 if (d->depth != 32) {
3231 QImage img32 = convertToFormat(Format_RGB32);
3232 return img32.createHeuristicMask(clipTight);
3233 }
3234
3235#define PIX(x,y) (*((const QRgb*)scanLine(y)+x) & 0x00ffffff)
3236
3237 int w = width();
3238 int h = height();
3239 QImage m(w, h, Format_MonoLSB);
3241 m.setColorCount(2);
3242 m.setColor(0, QColor(Qt::color0).rgba());
3243 m.setColor(1, QColor(Qt::color1).rgba());
3244 m.fill(0xff);
3245
3246 QRgb background = PIX(0,0);
3247 if (background != PIX(w-1,0) &&
3248 background != PIX(0,h-1) &&
3249 background != PIX(w-1,h-1)) {
3250 background = PIX(w-1,0);
3251 if (background != PIX(w-1,h-1) &&
3252 background != PIX(0,h-1) &&
3253 PIX(0,h-1) == PIX(w-1,h-1)) {
3254 background = PIX(w-1,h-1);
3255 }
3256 }
3257
3258 int x,y;
3259 bool done = false;
3260 uchar *ypp, *ypc, *ypn;
3261 while(!done) {
3262 done = true;
3263 ypn = m.scanLine(0);
3264 ypc = nullptr;
3265 for (y = 0; y < h; y++) {
3266 ypp = ypc;
3267 ypc = ypn;
3268 ypn = (y == h-1) ? nullptr : m.scanLine(y+1);
3269 const QRgb *p = (const QRgb *)scanLine(y);
3270 for (x = 0; x < w; x++) {
3271 // slowness here - it's possible to do six of these tests
3272 // together in one go. oh well.
3273 if ((x == 0 || y == 0 || x == w-1 || y == h-1 ||
3274 !(*(ypc + ((x-1) >> 3)) & (1 << ((x-1) & 7))) ||
3275 !(*(ypc + ((x+1) >> 3)) & (1 << ((x+1) & 7))) ||
3276 !(*(ypp + (x >> 3)) & (1 << (x & 7))) ||
3277 !(*(ypn + (x >> 3)) & (1 << (x & 7)))) &&
3278 ( (*(ypc + (x >> 3)) & (1 << (x & 7)))) &&
3279 ((*p & 0x00ffffff) == background)) {
3280 done = false;
3281 *(ypc + (x >> 3)) &= ~(1 << (x & 7));
3282 }
3283 p++;
3284 }
3285 }
3286 }
3287
3288 if (!clipTight) {
3289 ypn = m.scanLine(0);
3290 ypc = nullptr;
3291 for (y = 0; y < h; y++) {
3292 ypp = ypc;
3293 ypc = ypn;
3294 ypn = (y == h-1) ? nullptr : m.scanLine(y+1);
3295 const QRgb *p = (const QRgb *)scanLine(y);
3296 for (x = 0; x < w; x++) {
3297 if ((*p & 0x00ffffff) != background) {
3298 if (x > 0)
3299 *(ypc + ((x-1) >> 3)) |= (1 << ((x-1) & 7));
3300 if (x < w-1)
3301 *(ypc + ((x+1) >> 3)) |= (1 << ((x+1) & 7));
3302 if (y > 0)
3303 *(ypp + (x >> 3)) |= (1 << (x & 7));
3304 if (y < h-1)
3305 *(ypn + (x >> 3)) |= (1 << (x & 7));
3306 }
3307 p++;
3308 }
3309 }
3310 }
3311
3312#undef PIX
3313
3314 copyPhysicalMetadata(m.d, d);
3315 return m;
3316}
3317#endif //QT_NO_IMAGE_HEURISTIC_MASK
3318
3319/*!
3320 Creates and returns a mask for this image based on the given \a
3321 color value. If the \a mode is MaskInColor (the default value),
3322 all pixels matching \a color will be opaque pixels in the mask. If
3323 \a mode is MaskOutColor, all pixels matching the given color will
3324 be transparent.
3325
3326 \sa createAlphaMask(), createHeuristicMask()
3327*/
3328
3329QImage QImage::createMaskFromColor(QRgb color, Qt::MaskMode mode) const
3330{
3331 if (!d)
3332 return QImage();
3333 QImage maskImage(size(), QImage::Format_MonoLSB);
3334 QIMAGE_SANITYCHECK_MEMORY(maskImage);
3335 maskImage.fill(0);
3336 uchar *s = maskImage.bits();
3337 if (!s)
3338 return QImage();
3339
3340 if (depth() == 32) {
3341 for (int h = 0; h < d->height; h++) {
3342 const uint *sl = (const uint *) scanLine(h);
3343 for (int w = 0; w < d->width; w++) {
3344 if (sl[w] == color)
3345 *(s + (w >> 3)) |= (1 << (w & 7));
3346 }
3347 s += maskImage.bytesPerLine();
3348 }
3349 } else {
3350 for (int h = 0; h < d->height; h++) {
3351 for (int w = 0; w < d->width; w++) {
3352 if ((uint) pixel(w, h) == color)
3353 *(s + (w >> 3)) |= (1 << (w & 7));
3354 }
3355 s += maskImage.bytesPerLine();
3356 }
3357 }
3358 if (mode == Qt::MaskOutColor)
3359 maskImage.invertPixels();
3360
3361 copyPhysicalMetadata(maskImage.d, d);
3362 return maskImage;
3363}
3364
3365/*!
3366 \fn QImage QImage::mirrored(bool horizontal = false, bool vertical = true) const &
3367 \fn QImage QImage::mirrored(bool horizontal = false, bool vertical = true) &&
3368 \deprecated [6.13] Use flipped(Qt::Orientations) instead.
3369
3370 Returns a mirror of the image, mirrored in the horizontal and/or
3371 the vertical direction depending on whether \a horizontal and \a
3372 vertical are set to true or false.
3373
3374 Note that the original image is not changed.
3375
3376 \sa mirror(), {QImage#Image Transformations}{Image Transformations}
3377*/
3378
3379/*!
3380 \fn void QImage::mirror(bool horizontal = false, bool vertical = true)
3381 \since 6.0
3382 \deprecated [6.13] Use flip(Qt::Orientations) instead.
3383
3384 Mirrors of the image in the horizontal and/or the vertical direction depending
3385 on whether \a horizontal and \a vertical are set to true or false.
3386
3387 \sa mirrored(), {QImage#Image Transformations}{Image Transformations}
3388*/
3389
3390/*!
3391 \fn QImage QImage::flipped(Qt::Orientations orient) const &
3392 \fn QImage QImage::flipped(Qt::Orientations orient) &&
3393 \since 6.9
3394
3395 Returns a flipped or mirror version of the image, mirrored in the horizontal and/or
3396 the vertical direction depending on \a orient.
3397
3398 Note that the original image is not changed.
3399
3400 \sa flip(Qt::Orientations), {QImage#Image Transformations}{Image Transformations}
3401*/
3402
3403/*!
3404 \fn void QImage::flip(Qt::Orientations orient)
3405 \since 6.9
3406
3407 Flips or mirrors the image in the horizontal and/or the vertical direction depending
3408 on \a orient.
3409
3410 \sa flipped(Qt::Orientations), {QImage#Image Transformations}{Image Transformations}
3411*/
3412
3413template<class T> inline void do_mirror_data(QImageData *dst, QImageData *src,
3414 int dstX0, int dstY0,
3415 int dstXIncr, int dstYIncr,
3416 int w, int h)
3417{
3418 if (dst == src) {
3419 // When mirroring in-place, stop in the middle for one of the directions, since we
3420 // are swapping the bytes instead of merely copying.
3421 const int srcXEnd = (dstX0 && !dstY0) ? w / 2 : w;
3422 const int srcYEnd = dstY0 ? h / 2 : h;
3423 for (int srcY = 0, dstY = dstY0; srcY < srcYEnd; ++srcY, dstY += dstYIncr) {
3424 T *srcPtr = (T *) (src->data + srcY * src->bytes_per_line);
3425 T *dstPtr = (T *) (dst->data + dstY * dst->bytes_per_line);
3426 for (int srcX = 0, dstX = dstX0; srcX < srcXEnd; ++srcX, dstX += dstXIncr)
3427 std::swap(srcPtr[srcX], dstPtr[dstX]);
3428 }
3429 // If mirroring both ways, the middle line needs to be mirrored horizontally only.
3430 if (dstX0 && dstY0 && (h & 1)) {
3431 int srcY = h / 2;
3432 int srcXEnd2 = w / 2;
3433 T *srcPtr = (T *) (src->data + srcY * src->bytes_per_line);
3434 for (int srcX = 0, dstX = dstX0; srcX < srcXEnd2; ++srcX, dstX += dstXIncr)
3435 std::swap(srcPtr[srcX], srcPtr[dstX]);
3436 }
3437 } else {
3438 for (int srcY = 0, dstY = dstY0; srcY < h; ++srcY, dstY += dstYIncr) {
3439 T *srcPtr = (T *) (src->data + srcY * src->bytes_per_line);
3440 T *dstPtr = (T *) (dst->data + dstY * dst->bytes_per_line);
3441 for (int srcX = 0, dstX = dstX0; srcX < w; ++srcX, dstX += dstXIncr)
3442 dstPtr[dstX] = srcPtr[srcX];
3443 }
3444 }
3445}
3446
3447inline void do_flip(QImageData *dst, QImageData *src, int w, int h, int depth)
3448{
3449 const int data_bytes_per_line = w * (depth / 8);
3450 if (dst == src) {
3451 uint *srcPtr = reinterpret_cast<uint *>(src->data);
3452 uint *dstPtr = reinterpret_cast<uint *>(dst->data + (h - 1) * dst->bytes_per_line);
3453 h = h / 2;
3454 const int uint_per_line = (data_bytes_per_line + 3) >> 2; // bytes per line must be a multiple of 4
3455 for (int y = 0; y < h; ++y) {
3456 // This is auto-vectorized, no need for SSE2 or NEON versions:
3457 for (int x = 0; x < uint_per_line; x++) {
3458 const uint d = dstPtr[x];
3459 const uint s = srcPtr[x];
3460 dstPtr[x] = s;
3461 srcPtr[x] = d;
3462 }
3463 srcPtr += src->bytes_per_line >> 2;
3464 dstPtr -= dst->bytes_per_line >> 2;
3465 }
3466
3467 } else {
3468 const uchar *srcPtr = src->data;
3469 uchar *dstPtr = dst->data + (h - 1) * dst->bytes_per_line;
3470 for (int y = 0; y < h; ++y) {
3471 memcpy(dstPtr, srcPtr, data_bytes_per_line);
3472 srcPtr += src->bytes_per_line;
3473 dstPtr -= dst->bytes_per_line;
3474 }
3475 }
3476}
3477
3478inline void do_mirror(QImageData *dst, QImageData *src, bool horizontal, bool vertical)
3479{
3480 Q_ASSERT(src->width == dst->width && src->height == dst->height && src->depth == dst->depth);
3481 int w = src->width;
3482 int h = src->height;
3483 int depth = src->depth;
3484
3485 if (src->depth == 1) {
3486 w = (w + 7) / 8; // byte aligned width
3487 depth = 8;
3488 }
3489
3490 if (vertical && !horizontal) {
3491 // This one is simple and common, so do it a little more optimized
3492 do_flip(dst, src, w, h, depth);
3493 return;
3494 }
3495
3496 int dstX0 = 0, dstXIncr = 1;
3497 int dstY0 = 0, dstYIncr = 1;
3498 if (horizontal) {
3499 // 0 -> w-1, 1 -> w-2, 2 -> w-3, ...
3500 dstX0 = w - 1;
3501 dstXIncr = -1;
3502 }
3503 if (vertical) {
3504 // 0 -> h-1, 1 -> h-2, 2 -> h-3, ...
3505 dstY0 = h - 1;
3506 dstYIncr = -1;
3507 }
3508
3509 switch (depth) {
3510 case 128:
3511 do_mirror_data<QRgbaFloat32>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3512 break;
3513 case 64:
3514 do_mirror_data<quint64>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3515 break;
3516 case 32:
3517 do_mirror_data<quint32>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3518 break;
3519 case 24:
3520 do_mirror_data<quint24>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3521 break;
3522 case 16:
3523 do_mirror_data<quint16>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3524 break;
3525 case 8:
3526 do_mirror_data<quint8>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3527 break;
3528 default:
3529 Q_ASSERT(false);
3530 break;
3531 }
3532
3533 // The bytes are now all in the correct place. In addition, the bits in the individual
3534 // bytes have to be flipped too when horizontally mirroring a 1 bit-per-pixel image.
3535 if (horizontal && dst->depth == 1) {
3536 Q_ASSERT(dst->format == QImage::Format_Mono || dst->format == QImage::Format_MonoLSB);
3537 const int shift = 8 - (dst->width % 8);
3538 const uchar *bitflip = qt_get_bitflip_array();
3539 for (int y = 0; y < h; ++y) {
3540 uchar *begin = dst->data + y * dst->bytes_per_line;
3541 uchar *end = begin + dst->bytes_per_line;
3542 for (uchar *p = begin; p < end; ++p) {
3543 *p = bitflip[*p];
3544 // When the data is non-byte aligned, an extra bit shift (of the number of
3545 // unused bits at the end) is needed for the entire scanline.
3546 if (shift != 8 && p != begin) {
3547 if (dst->format == QImage::Format_Mono) {
3548 for (int i = 0; i < shift; ++i) {
3549 p[-1] <<= 1;
3550 p[-1] |= (*p & (128 >> i)) >> (7 - i);
3551 }
3552 } else {
3553 for (int i = 0; i < shift; ++i) {
3554 p[-1] >>= 1;
3555 p[-1] |= (*p & (1 << i)) << (7 - i);
3556 }
3557 }
3558 }
3559 }
3560 if (shift != 8) {
3561 if (dst->format == QImage::Format_Mono)
3562 end[-1] <<= shift;
3563 else
3564 end[-1] >>= shift;
3565 }
3566 }
3567 }
3568}
3569
3570/*!
3571 \internal
3572*/
3573QImage QImage::mirrored_helper(bool horizontal, bool vertical) const
3574{
3575 if (!d)
3576 return QImage();
3577
3578 if ((d->width <= 1 && d->height <= 1) || (!horizontal && !vertical))
3579 return *this;
3580
3581 // Create result image, copy colormap
3582 QImage result(d->width, d->height, d->format);
3584
3585 // check if we ran out of of memory..
3586 if (!result.d)
3587 return QImage();
3588
3589 result.d->colortable = d->colortable;
3590 result.d->has_alpha_clut = d->has_alpha_clut;
3591 copyMetadata(result.d, d);
3592
3593 do_mirror(result.d, d, horizontal, vertical);
3594
3595 return result;
3596}
3597
3598/*!
3599 \internal
3600*/
3601void QImage::mirrored_inplace(bool horizontal, bool vertical)
3602{
3603 if (!d || (d->width <= 1 && d->height <= 1) || (!horizontal && !vertical))
3604 return;
3605
3606 detach();
3607 if (!d)
3608 return;
3609 if (!d->own_data)
3610 *this = copy();
3611
3612 do_mirror(d, d, horizontal, vertical);
3613}
3614
3615/*!
3616 \fn QImage QImage::rgbSwapped() const &
3617 \fn QImage QImage::rgbSwapped() &&
3618
3619 Returns a QImage in which the values of the red and blue
3620 components of all pixels have been swapped, effectively converting
3621 an RGB image to an BGR image.
3622
3623 The original QImage is not changed.
3624
3625 \sa rgbSwap(), {QImage#Image Transformations}{Image Transformations}
3626*/
3627
3628/*!
3629 \fn void QImage::rgbSwap()
3630 \since 6.0
3631
3632 Swaps the values of the red and blue components of all pixels, effectively converting
3633 an RGB image to an BGR image.
3634
3635 \sa rgbSwapped(), {QImage#Image Transformations}{Image Transformations}
3636*/
3637
3638static inline void rgbSwapped_generic(int width, int height, const QImage *src, QImage *dst, const QPixelLayout* layout)
3639{
3640 const RbSwapFunc func = layout->rbSwap;
3641 if (!func) {
3642 qWarning("Trying to rb-swap an image format where it doesn't make sense");
3643 if (src != dst)
3644 *dst = *src;
3645 return;
3646 }
3647
3648 for (int i = 0; i < height; ++i) {
3649 uchar *q = dst->scanLine(i);
3650 const uchar *p = src->constScanLine(i);
3651 func(q, p, width);
3652 }
3653}
3654
3655/*!
3656 \internal
3657*/
3658QImage Q_TRACE_INSTRUMENT(qtgui) QImage::rgbSwapped_helper() const
3659{
3660 if (isNull())
3661 return *this;
3662
3663 Q_TRACE_SCOPE(QImage_rgbSwapped_helper);
3664
3665 QImage res;
3666
3667 switch (d->format) {
3668 case Format_Invalid:
3669 case NImageFormats:
3670 Q_ASSERT(false);
3671 break;
3672 case Format_Alpha8:
3673 case Format_Grayscale8:
3674 case Format_Grayscale16:
3675 return *this;
3676 case Format_Mono:
3677 case Format_MonoLSB:
3678 case Format_Indexed8:
3679 res = copy();
3680 for (int i = 0; i < res.d->colortable.size(); i++) {
3681 QRgb c = res.d->colortable.at(i);
3682 res.d->colortable[i] = QRgb(((c << 16) & 0xff0000) | ((c >> 16) & 0xff) | (c & 0xff00ff00));
3683 }
3684 break;
3685 case Format_RGBX8888:
3686 case Format_RGBA8888:
3687 case Format_RGBA8888_Premultiplied:
3688#if Q_BYTE_ORDER == Q_BIG_ENDIAN
3689 res = QImage(d->width, d->height, d->format);
3691 for (int i = 0; i < d->height; i++) {
3692 uint *q = (uint*)res.scanLine(i);
3693 const uint *p = (const uint*)constScanLine(i);
3694 const uint *end = p + d->width;
3695 while (p < end) {
3696 uint c = *p;
3697 *q = ((c << 16) & 0xff000000) | ((c >> 16) & 0xff00) | (c & 0x00ff00ff);
3698 p++;
3699 q++;
3700 }
3701 }
3702 break;
3703#else
3704 // On little-endian rgba8888 is abgr32 and can use same rgb-swap as argb32
3705 Q_FALLTHROUGH();
3706#endif
3707 case Format_RGB32:
3708 case Format_ARGB32:
3709 case Format_ARGB32_Premultiplied:
3710 res = QImage(d->width, d->height, d->format);
3712 for (int i = 0; i < d->height; i++) {
3713 uint *q = (uint*)res.scanLine(i);
3714 const uint *p = (const uint*)constScanLine(i);
3715 const uint *end = p + d->width;
3716 while (p < end) {
3717 uint c = *p;
3718 *q = ((c << 16) & 0xff0000) | ((c >> 16) & 0xff) | (c & 0xff00ff00);
3719 p++;
3720 q++;
3721 }
3722 }
3723 break;
3724 case Format_RGB16:
3725 res = QImage(d->width, d->height, d->format);
3727 for (int i = 0; i < d->height; i++) {
3728 ushort *q = (ushort*)res.scanLine(i);
3729 const ushort *p = (const ushort*)constScanLine(i);
3730 const ushort *end = p + d->width;
3731 while (p < end) {
3732 ushort c = *p;
3733 *q = ((c << 11) & 0xf800) | ((c >> 11) & 0x1f) | (c & 0x07e0);
3734 p++;
3735 q++;
3736 }
3737 }
3738 break;
3739 default:
3740 res = QImage(d->width, d->height, d->format);
3742 rgbSwapped_generic(d->width, d->height, this, &res, &qPixelLayouts[d->format]);
3743 break;
3744 }
3745 copyMetadata(res.d, d);
3746 return res;
3747}
3748
3749/*!
3750 \internal
3751*/
3752void QImage::rgbSwapped_inplace()
3753{
3754 if (isNull())
3755 return;
3756
3757 detach();
3758 if (!d)
3759 return;
3760 if (!d->own_data)
3761 *this = copy();
3762
3763 switch (d->format) {
3764 case Format_Invalid:
3765 case NImageFormats:
3766 Q_ASSERT(false);
3767 break;
3768 case Format_Alpha8:
3769 case Format_Grayscale8:
3770 case Format_Grayscale16:
3771 return;
3772 case Format_Mono:
3773 case Format_MonoLSB:
3774 case Format_Indexed8:
3775 for (int i = 0; i < d->colortable.size(); i++) {
3776 QRgb c = d->colortable.at(i);
3777 d->colortable[i] = QRgb(((c << 16) & 0xff0000) | ((c >> 16) & 0xff) | (c & 0xff00ff00));
3778 }
3779 break;
3780 case Format_RGBX8888:
3781 case Format_RGBA8888:
3782 case Format_RGBA8888_Premultiplied:
3783#if Q_BYTE_ORDER == Q_BIG_ENDIAN
3784 for (int i = 0; i < d->height; i++) {
3785 uint *p = (uint*)scanLine(i);
3786 uint *end = p + d->width;
3787 while (p < end) {
3788 uint c = *p;
3789 *p = ((c << 16) & 0xff000000) | ((c >> 16) & 0xff00) | (c & 0x00ff00ff);
3790 p++;
3791 }
3792 }
3793 break;
3794#else
3795 // On little-endian rgba8888 is abgr32 and can use same rgb-swap as argb32
3796 Q_FALLTHROUGH();
3797#endif
3798 case Format_RGB32:
3799 case Format_ARGB32:
3800 case Format_ARGB32_Premultiplied:
3801 for (int i = 0; i < d->height; i++) {
3802 uint *p = (uint*)scanLine(i);
3803 uint *end = p + d->width;
3804 while (p < end) {
3805 uint c = *p;
3806 *p = ((c << 16) & 0xff0000) | ((c >> 16) & 0xff) | (c & 0xff00ff00);
3807 p++;
3808 }
3809 }
3810 break;
3811 case Format_RGB16:
3812 for (int i = 0; i < d->height; i++) {
3813 ushort *p = (ushort*)scanLine(i);
3814 ushort *end = p + d->width;
3815 while (p < end) {
3816 ushort c = *p;
3817 *p = ((c << 11) & 0xf800) | ((c >> 11) & 0x1f) | (c & 0x07e0);
3818 p++;
3819 }
3820 }
3821 break;
3822 case Format_BGR30:
3823 case Format_A2BGR30_Premultiplied:
3824 case Format_RGB30:
3825 case Format_A2RGB30_Premultiplied:
3826 for (int i = 0; i < d->height; i++) {
3827 uint *p = (uint*)scanLine(i);
3828 uint *end = p + d->width;
3829 while (p < end) {
3830 *p = qRgbSwapRgb30(*p);
3831 p++;
3832 }
3833 }
3834 break;
3835 default:
3836 rgbSwapped_generic(d->width, d->height, this, this, &qPixelLayouts[d->format]);
3837 break;
3838 }
3839}
3840
3841/*!
3842 Loads an image from the file with the given \a fileName. Returns \c true if
3843 the image was successfully loaded; otherwise invalidates the image
3844 and returns \c false.
3845
3846 The loader attempts to read the image using the specified \a format, e.g.,
3847 PNG or JPG. If \a format is not specified (which is the default), it is
3848 auto-detected based on the file's suffix and header. For details, see
3849 QImageReader::setAutoDetectImageFormat() and
3850 \l{QImageReader#Security Considerations}{Security Considerations}.
3851
3852 The file name can either refer to an actual file on disk or to one
3853 of the application's embedded resources. See the
3854 \l{resources.html}{Resource System} overview for details on how to
3855 embed images and other resource files in the application's
3856 executable.
3857
3858 \sa {QImage#Reading and Writing Image Files}{Reading and Writing Image Files}
3859*/
3860
3861bool QImage::load(const QString &fileName, const char* format)
3862{
3863 *this = QImageReader(fileName, format).read();
3864 return !isNull();
3865}
3866
3867/*!
3868 \overload
3869
3870 This function reads a QImage from the given \a device. This can,
3871 for example, be used to load an image directly into a QByteArray.
3872*/
3873
3874bool QImage::load(QIODevice* device, const char* format)
3875{
3876 *this = QImageReader(device, format).read();
3877 return !isNull();
3878}
3879
3880/*!
3881 \since 6.2
3882
3883 Loads an image from the given QByteArrayView \a data. Returns \c true if the image was
3884 successfully loaded; otherwise invalidates the image and returns \c false.
3885
3886 The loader attempts to read the image using the specified \a format, e.g.,
3887 PNG or JPG. If \a format is not specified (which is the default), it
3888 is auto-detected based on the data header. For details, see
3889 QImageReader::setAutoDetectImageFormat() and
3890 \l{QImageReader#Security Considerations}{Security Considerations}.
3891
3892 \sa {QImage#Reading and Writing Image Files}{Reading and Writing Image Files}
3893*/
3894
3895bool QImage::loadFromData(QByteArrayView data, const char *format)
3896{
3897 *this = fromData(data, format);
3898 return !isNull();
3899}
3900
3901/*!
3902 \fn bool QImage::loadFromData(const uchar *data, int len, const char *format)
3903
3904 \overload
3905
3906 Loads an image from the first \a len bytes of the given binary \a data.
3907*/
3908
3909bool QImage::loadFromData(const uchar *buf, int len, const char *format)
3910{
3911 return loadFromData(QByteArrayView(buf, len), format);
3912}
3913
3914/*!
3915 \fn bool QImage::loadFromData(const QByteArray &data, const char *format)
3916
3917 \overload
3918
3919 Loads an image from the given QByteArray \a data.
3920*/
3921
3922/*!
3923 \since 6.2
3924
3925 Constructs an image from the given QByteArrayView \a data. The loader attempts to read the image
3926 using the specified \a format. If \a format is not specified (which is the default), the loader
3927 probes the data for a header to guess the file format.
3928
3929 If \a format is specified, it must be one of the values returned by
3930 QImageReader::supportedImageFormats().
3931
3932 If the loading of the image fails, the image returned will be a null image.
3933
3934 \sa load(), save(), {QImage#Reading and Writing Image Files}{Reading and Writing Image Files}
3935 */
3936
3937QImage QImage::fromData(QByteArrayView data, const char *format)
3938{
3939 QByteArray a = QByteArray::fromRawData(data.constData(), data.size());
3940 QBuffer b;
3941 b.setData(a);
3942 b.open(QIODevice::ReadOnly);
3943 return QImageReader(&b, format).read();
3944}
3945
3946/*!
3947 \fn QImage QImage::fromData(const uchar *data, int size, const char *format)
3948
3949 \overload
3950
3951 Constructs a QImage from the first \a size bytes of the given binary \a data.
3952*/
3953
3954QImage QImage::fromData(const uchar *data, int size, const char *format)
3955{
3956 return fromData(QByteArrayView(data, size), format);
3957}
3958
3959/*!
3960 \fn QImage QImage::fromData(const QByteArray &data, const char *format)
3961
3962 \overload
3963
3964 Constructs a QImage from the given QByteArray \a data.
3965
3966*/
3967
3968/*!
3969 Saves the image to the file with the given \a fileName, using the
3970 given image file \a format and \a quality factor. If \a format is
3971 \nullptr, QImage will attempt to guess the format by looking at
3972 \a fileName's suffix.
3973
3974 The \a quality factor must be in the range 0 to 100 or -1. Specify
3975 0 to obtain small compressed files, 100 for large uncompressed
3976 files, and -1 (the default) to use the default settings.
3977
3978 Returns \c true if the image was successfully saved; otherwise
3979 returns \c false.
3980
3981 \sa {QImage#Reading and Writing Image Files}{Reading and Writing
3982 Image Files}
3983*/
3984bool QImage::save(const QString &fileName, const char *format, int quality) const
3985{
3986 if (isNull())
3987 return false;
3988 QImageWriter writer(fileName, format);
3989 return d->doImageIO(this, &writer, quality);
3990}
3991
3992/*!
3993 \overload
3994
3995 This function writes a QImage to the given \a device.
3996
3997 This can, for example, be used to save an image directly into a
3998 QByteArray:
3999
4000 \snippet image/image.cpp 0
4001*/
4002
4003bool QImage::save(QIODevice* device, const char* format, int quality) const
4004{
4005 if (isNull())
4006 return false; // nothing to save
4007 QImageWriter writer(device, format);
4008 return d->doImageIO(this, &writer, quality);
4009}
4010
4011/* \internal
4012*/
4013
4014bool QImageData::doImageIO(const QImage *image, QImageWriter *writer, int quality) const
4015{
4016 if (quality > 100 || quality < -1)
4017 qWarning("QImage::save: Quality out of range [-1, 100]");
4018 if (quality >= 0)
4019 writer->setQuality(qMin(quality,100));
4020 const bool result = writer->write(*image);
4021#ifdef QT_DEBUG
4022 if (!result)
4023 qWarning("QImage::save: failed to write image - %s", qPrintable(writer->errorString()));
4024#endif
4025 return result;
4026}
4027
4028bool QImageData::isWithinIOAllocationLimit(int width, int height, QImage::Format format,
4029 const char *context)
4030{
4031 if (const int mbLimit = QImageReader::allocationLimit()) {
4032 qsizetype depth = qMax(qt_depthForFormat(format), 32); // Effective gui depth = 32
4033 QImageData::ImageSizeParameters szp =
4034 QImageData::calculateImageParameters(width, height, depth);
4035 if (!szp.isValid())
4036 return false;
4037 const qsizetype mb = szp.totalSize >> 20;
4038 if (mb > mbLimit || (mb == mbLimit && szp.totalSize % (1 << 20))) {
4039 if (context) {
4040 qCWarning(lcImageIo, "%s: Rejecting image as it exceeds the current "
4041 "allocation limit of %i megabytes", context, mbLimit);
4042 }
4043 return false;
4044 }
4045 }
4046 return true;
4047}
4048
4049/*****************************************************************************
4050 QImage stream functions
4051 *****************************************************************************/
4052#if !defined(QT_NO_DATASTREAM)
4053/*!
4054 \fn QDataStream &operator<<(QDataStream &stream, const QImage &image)
4055 \relates QImage
4056
4057 Writes the given \a image to the given \a stream as a PNG image,
4058 or as a BMP image if the stream's version is 1. Note that writing
4059 the stream to a file will not produce a valid image file.
4060
4061 \sa QImage::save(), {Serializing Qt Data Types}
4062*/
4063
4064QDataStream &operator<<(QDataStream &s, const QImage &image)
4065{
4066 if (s.version() >= 5) {
4067 if (image.isNull()) {
4068 s << (qint32) 0; // null image marker
4069 return s;
4070 } else {
4071 s << (qint32) 1;
4072 // continue ...
4073 }
4074 }
4075 QImageWriter writer(s.device(), s.version() == 1 ? "bmp" : "png");
4076 writer.write(image);
4077 return s;
4078}
4079
4080/*!
4081 \fn QDataStream &operator>>(QDataStream &stream, QImage &image)
4082 \relates QImage
4083
4084 Reads an image from the given \a stream and stores it in the given
4085 \a image.
4086
4087 \sa QImage::load(), {Serializing Qt Data Types}
4088*/
4089
4090QDataStream &operator>>(QDataStream &s, QImage &image)
4091{
4092 if (s.version() >= 5) {
4093 qint32 nullMarker;
4094 s >> nullMarker;
4095 if (!nullMarker) {
4096 image = QImage(); // null image
4097 return s;
4098 }
4099 }
4100 image = QImageReader(s.device(), s.version() == 1 ? "bmp" : "png").read();
4101 if (image.isNull() && s.version() >= 5)
4102 s.setStatus(QDataStream::ReadPastEnd);
4103 return s;
4104}
4105#endif // QT_NO_DATASTREAM
4106
4107
4108
4109/*!
4110 \fn bool QImage::operator==(const QImage & image) const
4111
4112 Returns \c true if this image and the given \a image have the same
4113 contents; otherwise returns \c false.
4114
4115 The comparison can be slow, unless there is some obvious
4116 difference (e.g. different size or format), in which case the
4117 function will return quickly.
4118
4119 \sa operator=()
4120*/
4121
4122bool QImage::operator==(const QImage & i) const
4123{
4124 // same object, or shared?
4125 if (i.d == d)
4126 return true;
4127 if (!i.d || !d)
4128 return false;
4129
4130 // obviously different stuff?
4131 if (i.d->height != d->height || i.d->width != d->width || i.d->format != d->format || i.d->colorSpace != d->colorSpace)
4132 return false;
4133
4134 if (d->format != Format_RGB32) {
4135 if (d->format >= Format_ARGB32) { // all bits defined
4136 const int n = d->width * d->depth / 8;
4137 if (n == d->bytes_per_line && n == i.d->bytes_per_line) {
4138 if (memcmp(bits(), i.bits(), d->nbytes))
4139 return false;
4140 } else {
4141 for (int y = 0; y < d->height; ++y) {
4142 if (memcmp(scanLine(y), i.scanLine(y), n))
4143 return false;
4144 }
4145 }
4146 } else {
4147 const int w = width();
4148 const int h = height();
4149 const QList<QRgb> &colortable = d->colortable;
4150 const QList<QRgb> &icolortable = i.d->colortable;
4151 for (int y=0; y<h; ++y) {
4152 for (int x=0; x<w; ++x) {
4153 if (colortable[pixelIndex(x, y)] != icolortable[i.pixelIndex(x, y)])
4154 return false;
4155 }
4156 }
4157 }
4158 } else {
4159 //alpha channel undefined, so we must mask it out
4160 for(int l = 0; l < d->height; l++) {
4161 int w = d->width;
4162 const uint *p1 = reinterpret_cast<const uint*>(scanLine(l));
4163 const uint *p2 = reinterpret_cast<const uint*>(i.scanLine(l));
4164 while (w--) {
4165 if ((*p1++ & 0x00ffffff) != (*p2++ & 0x00ffffff))
4166 return false;
4167 }
4168 }
4169 }
4170 return true;
4171}
4172
4173
4174/*!
4175 \fn bool QImage::operator!=(const QImage & image) const
4176
4177 Returns \c true if this image and the given \a image have different
4178 contents; otherwise returns \c false.
4179
4180 The comparison can be slow, unless there is some obvious
4181 difference, such as different widths, in which case the function
4182 will return quickly.
4183
4184 \sa operator=()
4185*/
4186
4187bool QImage::operator!=(const QImage & i) const
4188{
4189 return !(*this == i);
4190}
4191
4192
4193
4194
4195/*!
4196 Returns the number of pixels that fit horizontally in a physical
4197 meter. Together with dotsPerMeterY(), this number defines the
4198 intended scale and aspect ratio of the image.
4199
4200 \sa setDotsPerMeterX(), {QImage#Image Information}{Image
4201 Information}
4202*/
4203int QImage::dotsPerMeterX() const
4204{
4205 return d ? qRound(d->dpmx) : 0;
4206}
4207
4208/*!
4209 Returns the number of pixels that fit vertically in a physical
4210 meter. Together with dotsPerMeterX(), this number defines the
4211 intended scale and aspect ratio of the image.
4212
4213 \sa setDotsPerMeterY(), {QImage#Image Information}{Image
4214 Information}
4215*/
4216int QImage::dotsPerMeterY() const
4217{
4218 return d ? qRound(d->dpmy) : 0;
4219}
4220
4221/*!
4222 Sets the number of pixels that fit horizontally in a physical
4223 meter, to \a x.
4224
4225 Together with dotsPerMeterY(), this number defines the intended
4226 scale and aspect ratio of the image, and determines the scale
4227 at which QPainter will draw graphics on the image. It does not
4228 change the scale or aspect ratio of the image when it is rendered
4229 on other paint devices.
4230
4231 \sa dotsPerMeterX(), {QImage#Image Information}{Image Information}
4232*/
4233void QImage::setDotsPerMeterX(int x)
4234{
4235 if (!d || !x || d->dpmx == x)
4236 return;
4237 detachMetadata();
4238
4239 if (d)
4240 d->dpmx = x;
4241}
4242
4243/*!
4244 Sets the number of pixels that fit vertically in a physical meter,
4245 to \a y.
4246
4247 Together with dotsPerMeterX(), this number defines the intended
4248 scale and aspect ratio of the image, and determines the scale
4249 at which QPainter will draw graphics on the image. It does not
4250 change the scale or aspect ratio of the image when it is rendered
4251 on other paint devices.
4252
4253 \sa dotsPerMeterY(), {QImage#Image Information}{Image Information}
4254*/
4255void QImage::setDotsPerMeterY(int y)
4256{
4257 if (!d || !y || d->dpmy == y)
4258 return;
4259 detachMetadata();
4260
4261 if (d)
4262 d->dpmy = y;
4263}
4264
4265/*!
4266 \fn QPoint QImage::offset() const
4267
4268 Returns the number of pixels by which the image is intended to be
4269 offset by when positioning relative to other images.
4270
4271 \sa setOffset(), {QImage#Image Information}{Image Information}
4272*/
4273QPoint QImage::offset() const
4274{
4275 return d ? d->offset : QPoint();
4276}
4277
4278
4279/*!
4280 \fn void QImage::setOffset(const QPoint& offset)
4281
4282 Sets the number of pixels by which the image is intended to be
4283 offset by when positioning relative to other images, to \a offset.
4284
4285 \sa offset(), {QImage#Image Information}{Image Information}
4286*/
4287void QImage::setOffset(const QPoint& p)
4288{
4289 if (!d || d->offset == p)
4290 return;
4291 detachMetadata();
4292
4293 if (d)
4294 d->offset = p;
4295}
4296
4297/*!
4298 Returns the text keys for this image.
4299
4300 You can use these keys with text() to list the image text for a
4301 certain key.
4302
4303 \sa text()
4304*/
4305QStringList QImage::textKeys() const
4306{
4307 return d ? QStringList(d->text.keys()) : QStringList();
4308}
4309
4310/*!
4311 Returns the image text associated with the given \a key. If the
4312 specified \a key is an empty string, the whole image text is
4313 returned, with each key-text pair separated by a newline.
4314
4315 \sa setText(), textKeys()
4316*/
4317QString QImage::text(const QString &key) const
4318{
4319 if (!d)
4320 return QString();
4321
4322 if (!key.isEmpty())
4323 return d->text.value(key);
4324
4325 QString tmp;
4326 for (auto it = d->text.begin(), end = d->text.end(); it != end; ++it)
4327 tmp += it.key() + ": "_L1 + it.value().simplified() + "\n\n"_L1;
4328 if (!tmp.isEmpty())
4329 tmp.chop(2); // remove final \n\n
4330 return tmp;
4331}
4332
4333/*!
4334 \fn void QImage::setText(const QString &key, const QString &text)
4335
4336 Sets the image text to the given \a text and associate it with the
4337 given \a key.
4338
4339 If you just want to store a single text block (i.e., a "comment"
4340 or just a description), you can either pass an empty key, or use a
4341 generic key like "Description".
4342
4343 The image text is embedded into the image data when you
4344 call save() or QImageWriter::write().
4345
4346 Not all image formats support embedded text. You can find out
4347 if a specific image or format supports embedding text
4348 by using QImageWriter::supportsOption(). We give an example:
4349
4350 \snippet image/supportedformat.cpp 0
4351
4352 You can use QImageWriter::supportedImageFormats() to find out
4353 which image formats are available to you.
4354
4355 \sa text(), textKeys()
4356*/
4357void QImage::setText(const QString &key, const QString &value)
4358{
4359 if (!d)
4360 return;
4361 detachMetadata();
4362
4363 if (d)
4364 d->text.insert(key, value);
4365}
4366
4367/*!
4368 \internal
4369
4370 Used by QPainter to retrieve a paint engine for the image.
4371*/
4372QPaintEngine *QImage::paintEngine() const
4373{
4374 if (!d)
4375 return nullptr;
4376
4377 if (!d->paintEngine) {
4378 QPaintDevice *paintDevice = const_cast<QImage *>(this);
4379 QPlatformIntegration *platformIntegration = QGuiApplicationPrivate::platformIntegration();
4380 if (platformIntegration)
4381 d->paintEngine = platformIntegration->createImagePaintEngine(paintDevice);
4382 if (!d->paintEngine)
4383 d->paintEngine = new QRasterPaintEngine(paintDevice);
4384 }
4385
4386 return d->paintEngine;
4387}
4388
4389
4390/*!
4391 \internal
4392
4393 Returns the size for the specified \a metric on the device.
4394*/
4395int QImage::metric(PaintDeviceMetric metric) const
4396{
4397 if (!d)
4398 return 0;
4399
4400 switch (metric) {
4401 case PdmWidth:
4402 return d->width;
4403
4404 case PdmHeight:
4405 return d->height;
4406
4407 case PdmWidthMM:
4408 return qRound(d->width * 1000 / d->dpmx);
4409
4410 case PdmHeightMM:
4411 return qRound(d->height * 1000 / d->dpmy);
4412
4413 case PdmNumColors:
4414 return d->colortable.size();
4415
4416 case PdmDepth:
4417 return d->depth;
4418
4419 case PdmDpiX:
4420 return qRound(d->dpmx * 0.0254);
4421 break;
4422
4423 case PdmDpiY:
4424 return qRound(d->dpmy * 0.0254);
4425 break;
4426
4427 case PdmPhysicalDpiX:
4428 return qRound(d->dpmx * 0.0254);
4429 break;
4430
4431 case PdmPhysicalDpiY:
4432 return qRound(d->dpmy * 0.0254);
4433 break;
4434
4435 case PdmDevicePixelRatio:
4436 return d->devicePixelRatio;
4437 break;
4438
4439 case PdmDevicePixelRatioScaled:
4440 return d->devicePixelRatio * QPaintDevice::devicePixelRatioFScale();
4441 break;
4442
4443 case PdmDevicePixelRatioF_EncodedA:
4444 Q_FALLTHROUGH();
4445 case PdmDevicePixelRatioF_EncodedB:
4446 return QPaintDevice::encodeMetricF(metric, d->devicePixelRatio);
4447 break;
4448
4449 default:
4450 qWarning("QImage::metric(): Unhandled metric type %d", metric);
4451 break;
4452 }
4453 return 0;
4454}
4455
4456
4457
4458/*****************************************************************************
4459 QPixmap (and QImage) helper functions
4460 *****************************************************************************/
4461/*
4462 This internal function contains the common (i.e. platform independent) code
4463 to do a transformation of pixel data. It is used by QPixmap::transform() and by
4464 QImage::transform().
4465
4466 \a trueMat is the true transformation matrix (see QPixmap::trueMatrix()) and
4467 \a xoffset is an offset to the matrix.
4468
4469 \a msbfirst specifies for 1bpp images, if the MSB or LSB comes first and \a
4470 depth specifies the colordepth of the data.
4471
4472 \a dptr is a pointer to the destination data, \a dbpl specifies the bits per
4473 line for the destination data, \a p_inc is the offset that we advance for
4474 every scanline and \a dHeight is the height of the destination image.
4475
4476 \a sprt is the pointer to the source data, \a sbpl specifies the bits per
4477 line of the source data, \a sWidth and \a sHeight are the width and height of
4478 the source data.
4479*/
4480
4481#undef IWX_MSB
4482#define IWX_MSB(b) if (trigx < maxws && trigy < maxhs) {
4483 if (*(sptr+sbpl*(trigy>>12)+(trigx>>15)) &
4484 (1 << (7-((trigx>>12)&7))))
4485 *dptr |= b;
4486 }
4487 trigx += m11;
4488 trigy += m12;
4489 // END OF MACRO
4490#undef IWX_LSB
4491#define IWX_LSB(b) if (trigx < maxws && trigy < maxhs) {
4492 if (*(sptr+sbpl*(trigy>>12)+(trigx>>15)) &
4493 (1 << ((trigx>>12)&7)))
4494 *dptr |= b;
4495 }
4496 trigx += m11;
4497 trigy += m12;
4498 // END OF MACRO
4499#undef IWX_PIX
4500#define IWX_PIX(b) if (trigx < maxws && trigy < maxhs) {
4501 if ((*(sptr+sbpl*(trigy>>12)+(trigx>>15)) &
4502 (1 << (7-((trigx>>12)&7)))) == 0)
4503 *dptr &= ~b;
4504 }
4505 trigx += m11;
4506 trigy += m12;
4507 // END OF MACRO
4508
4509bool qt_xForm_helper(const QTransform &trueMat, int xoffset, int type, int depth,
4510 uchar *dptr, qsizetype dbpl, int p_inc, int dHeight,
4511 const uchar *sptr, qsizetype sbpl, int sWidth, int sHeight)
4512{
4513 int m11 = int(trueMat.m11()*4096.0);
4514 int m12 = int(trueMat.m12()*4096.0);
4515 int m21 = int(trueMat.m21()*4096.0);
4516 int m22 = int(trueMat.m22()*4096.0);
4517 int dx = qRound(trueMat.dx()*4096.0);
4518 int dy = qRound(trueMat.dy()*4096.0);
4519
4520 int m21ydx = dx + (xoffset<<16) + (m11 + m21) / 2;
4521 int m22ydy = dy + (m12 + m22) / 2;
4522 uint trigx;
4523 uint trigy;
4524 uint maxws = sWidth<<12;
4525 uint maxhs = sHeight<<12;
4526
4527 for (int y=0; y<dHeight; y++) { // for each target scanline
4528 trigx = m21ydx;
4529 trigy = m22ydy;
4530 uchar *maxp = dptr + dbpl;
4531 if (depth != 1) {
4532 switch (depth) {
4533 case 8: // 8 bpp transform
4534 while (dptr < maxp) {
4535 if (trigx < maxws && trigy < maxhs)
4536 *dptr = *(sptr+sbpl*(trigy>>12)+(trigx>>12));
4537 trigx += m11;
4538 trigy += m12;
4539 dptr++;
4540 }
4541 break;
4542
4543 case 16: // 16 bpp transform
4544 while (dptr < maxp) {
4545 if (trigx < maxws && trigy < maxhs)
4546 *((ushort*)dptr) = *((const ushort *)(sptr+sbpl*(trigy>>12) +
4547 ((trigx>>12)<<1)));
4548 trigx += m11;
4549 trigy += m12;
4550 dptr++;
4551 dptr++;
4552 }
4553 break;
4554
4555 case 24: // 24 bpp transform
4556 while (dptr < maxp) {
4557 if (trigx < maxws && trigy < maxhs) {
4558 const uchar *p2 = sptr+sbpl*(trigy>>12) + ((trigx>>12)*3);
4559 dptr[0] = p2[0];
4560 dptr[1] = p2[1];
4561 dptr[2] = p2[2];
4562 }
4563 trigx += m11;
4564 trigy += m12;
4565 dptr += 3;
4566 }
4567 break;
4568
4569 case 32: // 32 bpp transform
4570 while (dptr < maxp) {
4571 if (trigx < maxws && trigy < maxhs)
4572 *((uint*)dptr) = *((const uint *)(sptr+sbpl*(trigy>>12) +
4573 ((trigx>>12)<<2)));
4574 trigx += m11;
4575 trigy += m12;
4576 dptr += 4;
4577 }
4578 break;
4579
4580 default: {
4581 return false;
4582 }
4583 }
4584 } else {
4585 switch (type) {
4587 while (dptr < maxp) {
4588 IWX_MSB(128);
4589 IWX_MSB(64);
4590 IWX_MSB(32);
4591 IWX_MSB(16);
4592 IWX_MSB(8);
4593 IWX_MSB(4);
4594 IWX_MSB(2);
4595 IWX_MSB(1);
4596 dptr++;
4597 }
4598 break;
4600 while (dptr < maxp) {
4601 IWX_LSB(1);
4602 IWX_LSB(2);
4603 IWX_LSB(4);
4604 IWX_LSB(8);
4605 IWX_LSB(16);
4606 IWX_LSB(32);
4607 IWX_LSB(64);
4608 IWX_LSB(128);
4609 dptr++;
4610 }
4611 break;
4612 }
4613 }
4614 m21ydx += m21;
4615 m22ydy += m22;
4616 dptr += p_inc;
4617 }
4618 return true;
4619}
4620#undef IWX_MSB
4621#undef IWX_LSB
4622#undef IWX_PIX
4623
4624/*!
4625 Returns a number that identifies the contents of this QImage
4626 object. Distinct QImage objects can only have the same key if they
4627 refer to the same contents.
4628
4629 The key will change when the image is altered.
4630*/
4631qint64 QImage::cacheKey() const
4632{
4633 if (!d)
4634 return 0;
4635 else
4636 return (((qint64) d->ser_no) << 32) | ((qint64) d->detach_no);
4637}
4638
4639/*!
4640 \internal
4641
4642 Returns \c true if the image is detached; otherwise returns \c false.
4643
4644 \sa detach(), {Implicit Data Sharing}
4645*/
4646
4647bool QImage::isDetached() const
4648{
4649 return d && d->ref.loadRelaxed() == 1;
4650}
4651
4652
4653/*!
4654 Sets the alpha channel of this image to the given \a alphaChannel.
4655
4656 If \a alphaChannel is an 8 bit alpha image, the alpha values are
4657 used directly. Otherwise, \a alphaChannel is converted to 8 bit
4658 grayscale and the intensity of the pixel values is used.
4659
4660 If the image already has an alpha channel, the existing alpha channel
4661 is multiplied with the new one. If the image doesn't have an alpha
4662 channel it will be converted to a format that does.
4663
4664 The operation is similar to painting \a alphaChannel as an alpha image
4665 over this image using \c QPainter::CompositionMode_DestinationIn.
4666
4667 \sa hasAlphaChannel(),
4668 {QImage#Image Transformations}{Image Transformations},
4669 {QImage#Image Formats}{Image Formats}
4670*/
4671
4672void QImage::setAlphaChannel(const QImage &alphaChannel)
4673{
4674 if (!d || alphaChannel.isNull())
4675 return;
4676
4677 if (d->paintEngine && d->paintEngine->isActive()) {
4678 qWarning("QImage::setAlphaChannel: "
4679 "Unable to set alpha channel while image is being painted on");
4680 return;
4681 }
4682
4683 const Format alphaFormat = qt_alphaVersionForPainting(d->format);
4684 if (d->format == alphaFormat)
4685 detach();
4686 else
4687 convertTo(alphaFormat);
4688
4689 if (isNull())
4690 return;
4691
4692 QImage sourceImage;
4693 if (alphaChannel.format() == QImage::Format_Alpha8 || (alphaChannel.d->depth == 8 && alphaChannel.isGrayscale()))
4694 sourceImage = alphaChannel;
4695 else
4696 sourceImage = alphaChannel.convertToFormat(QImage::Format_Grayscale8);
4697 if (!sourceImage.reinterpretAsFormat(QImage::Format_Alpha8))
4698 return;
4699
4700 QPainter painter(this);
4701 if (sourceImage.size() != size())
4702 painter.setRenderHint(QPainter::SmoothPixmapTransform);
4703 painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
4704 painter.drawImage(rect(), sourceImage);
4705}
4706
4707/*!
4708 Returns \c true if the image has a format that respects the alpha
4709 channel, otherwise returns \c false.
4710
4711 \sa {QImage#Image Information}{Image Information}
4712*/
4713bool QImage::hasAlphaChannel() const
4714{
4715 if (!d)
4716 return false;
4717 const QPixelFormat format = pixelFormat();
4718 if (format.alphaUsage() == QPixelFormat::UsesAlpha)
4719 return true;
4720 if (format.colorModel() == QPixelFormat::Indexed)
4721 return d->has_alpha_clut;
4722 return false;
4723}
4724
4725/*!
4726 Returns the number of bit planes in the image.
4727
4728 The number of bit planes is the number of bits of color and
4729 transparency information for each pixel. This is different from
4730 (i.e. smaller than) the depth when the image format contains
4731 unused bits.
4732
4733 \sa depth(), format(), {QImage#Image Formats}{Image Formats}
4734*/
4735int QImage::bitPlaneCount() const
4736{
4737 if (!d)
4738 return 0;
4739 int bpc = 0;
4740 switch (d->format) {
4741 case QImage::Format_Invalid:
4742 break;
4743 case QImage::Format_BGR30:
4744 case QImage::Format_RGB30:
4745 bpc = 30;
4746 break;
4747 case QImage::Format_RGB32:
4748 case QImage::Format_RGBX8888:
4749 bpc = 24;
4750 break;
4751 case QImage::Format_RGB666:
4752 bpc = 18;
4753 break;
4754 case QImage::Format_RGB555:
4755 bpc = 15;
4756 break;
4757 case QImage::Format_ARGB8555_Premultiplied:
4758 bpc = 23;
4759 break;
4760 case QImage::Format_RGB444:
4761 bpc = 12;
4762 break;
4763 case QImage::Format_RGBX64:
4764 case QImage::Format_RGBX16FPx4:
4765 bpc = 48;
4766 break;
4767 case QImage::Format_RGBX32FPx4:
4768 bpc = 96;
4769 break;
4770 default:
4771 bpc = qt_depthForFormat(d->format);
4772 break;
4773 }
4774 return bpc;
4775}
4776
4777/*!
4778 \internal
4779 Returns a smoothly scaled copy of the image. The returned image has a size
4780 of width \a w by height \a h pixels.
4781
4782 The function operates internally on \c Format_RGB32, \c Format_ARGB32_Premultiplied,
4783 \c Format_RGBX8888, \c Format_RGBA8888_Premultiplied, \c Format_RGBX64,
4784 or \c Format_RGBA64_Premultiplied and will convert to those formats
4785 if necessary. To avoid unnecessary conversion the result is returned in the format
4786 internally used, and not in the original format.
4787*/
4788QImage QImage::smoothScaled(int w, int h) const
4789{
4790 QImage src = *this;
4791 switch (src.format()) {
4792 case QImage::Format_RGB32:
4793 case QImage::Format_ARGB32_Premultiplied:
4794#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
4795 case QImage::Format_RGBX8888:
4796#endif
4797 case QImage::Format_RGBA8888_Premultiplied:
4798#if QT_CONFIG(raster_64bit)
4799 case QImage::Format_RGBX64:
4800 case QImage::Format_RGBA64_Premultiplied:
4801 break;
4802 case QImage::Format_RGBA64:
4803 case QImage::Format_Grayscale16:
4804 src.convertTo(QImage::Format_RGBA64_Premultiplied);
4805 break;
4806#endif
4807#if QT_CONFIG(raster_fp)
4808 case QImage::Format_RGBX32FPx4:
4809 case QImage::Format_RGBA32FPx4_Premultiplied:
4810 break;
4811 case QImage::Format_RGBX16FPx4:
4812 src.convertTo(QImage::Format_RGBX32FPx4);
4813 break;
4814 case QImage::Format_RGBA16FPx4:
4815 case QImage::Format_RGBA16FPx4_Premultiplied:
4816 case QImage::Format_RGBA32FPx4:
4817 src.convertTo(QImage::Format_RGBA32FPx4_Premultiplied);
4818 break;
4819#endif
4820 case QImage::Format_CMYK8888:
4821 break;
4822 default:
4823 if (src.hasAlphaChannel())
4824 src.convertTo(QImage::Format_ARGB32_Premultiplied);
4825 else
4826 src.convertTo(QImage::Format_RGB32);
4827 }
4828 src = qSmoothScaleImage(src, w, h);
4829 if (!src.isNull())
4830 copyMetadata(src.d, d);
4831 return src;
4832}
4833
4834static QImage rotated90(const QImage &image)
4835{
4836 QImage out(image.height(), image.width(), image.format());
4837 if (out.isNull())
4838 return out;
4839 copyMetadata(QImageData::get(out), QImageData::get(image));
4840 if (image.colorCount() > 0)
4841 out.setColorTable(image.colorTable());
4842 int w = image.width();
4843 int h = image.height();
4844 const MemRotateFunc memrotate = qMemRotateFunctions[qPixelLayouts[image.format()].bpp][2];
4845 if (memrotate) {
4846 memrotate(image.constBits(), w, h, image.bytesPerLine(), out.bits(), out.bytesPerLine());
4847 } else {
4848 for (int y=0; y<h; ++y) {
4849 if (image.colorCount())
4850 for (int x=0; x<w; ++x)
4851 out.setPixel(h-y-1, x, image.pixelIndex(x, y));
4852 else
4853 for (int x=0; x<w; ++x)
4854 out.setPixel(h-y-1, x, image.pixel(x, y));
4855 }
4856 }
4857 return out;
4858}
4859
4860static QImage rotated180(const QImage &image)
4861{
4862 const MemRotateFunc memrotate = qMemRotateFunctions[qPixelLayouts[image.format()].bpp][1];
4863 if (!memrotate)
4864 return image.flipped(Qt::Horizontal | Qt::Vertical);
4865
4866 QImage out(image.width(), image.height(), image.format());
4867 if (out.isNull())
4868 return out;
4869 copyMetadata(QImageData::get(out), QImageData::get(image));
4870 if (image.colorCount() > 0)
4871 out.setColorTable(image.colorTable());
4872 int w = image.width();
4873 int h = image.height();
4874 memrotate(image.constBits(), w, h, image.bytesPerLine(), out.bits(), out.bytesPerLine());
4875 return out;
4876}
4877
4878static QImage rotated270(const QImage &image)
4879{
4880 QImage out(image.height(), image.width(), image.format());
4881 if (out.isNull())
4882 return out;
4883 copyMetadata(QImageData::get(out), QImageData::get(image));
4884 if (image.colorCount() > 0)
4885 out.setColorTable(image.colorTable());
4886 int w = image.width();
4887 int h = image.height();
4888 const MemRotateFunc memrotate = qMemRotateFunctions[qPixelLayouts[image.format()].bpp][0];
4889 if (memrotate) {
4890 memrotate(image.constBits(), w, h, image.bytesPerLine(), out.bits(), out.bytesPerLine());
4891 } else {
4892 for (int y=0; y<h; ++y) {
4893 if (image.colorCount())
4894 for (int x=0; x<w; ++x)
4895 out.setPixel(y, w-x-1, image.pixelIndex(x, y));
4896 else
4897 for (int x=0; x<w; ++x)
4898 out.setPixel(y, w-x-1, image.pixel(x, y));
4899 }
4900 }
4901 return out;
4902}
4903
4904/*!
4905 Returns a copy of the image that is transformed using the given
4906 transformation \a matrix and transformation \a mode.
4907
4908 The returned image will normally have the same {Image Formats}{format} as
4909 the original image. However, a complex transformation may result in an
4910 image where not all pixels are covered by the transformed pixels of the
4911 original image. In such cases, those background pixels will be assigned a
4912 transparent color value, and the transformed image will be given a format
4913 with an alpha channel, even if the original image did not have that.
4914
4915 The transformation \a matrix is internally adjusted to compensate
4916 for unwanted translation; i.e. the image produced is the smallest
4917 image that contains all the transformed points of the original
4918 image. Use the trueMatrix() function to retrieve the actual matrix
4919 used for transforming an image.
4920
4921 Unlike the other overload, this function can be used to perform perspective
4922 transformations on images.
4923
4924 \sa trueMatrix(), {QImage#Image Transformations}{Image
4925 Transformations}
4926*/
4927
4928QImage Q_TRACE_INSTRUMENT(qtgui) QImage::transformed(const QTransform &matrix, Qt::TransformationMode mode ) const
4929{
4930 if (!d)
4931 return QImage();
4932
4933 Q_TRACE_PARAM_REPLACE(const QTransform &, double[9]);
4934 Q_TRACE_SCOPE(QImage_transformed, QList<double>({matrix.m11(), matrix.m12(), matrix.m13(),
4935 matrix.m21(), matrix.m22(), matrix.m23(),
4936 matrix.m31(), matrix.m32(), matrix.m33()}).data(), mode);
4937
4938 // source image data
4939 const int ws = width();
4940 const int hs = height();
4941
4942 // target image data
4943 qreal wdf;
4944 qreal hdf;
4945
4946 // compute size of target image
4947 QTransform mat = trueMatrix(matrix, ws, hs);
4948 bool complex_xform = false;
4949 bool scale_xform = false;
4950 bool nonpaintable_scale_xform = false;
4951 if (mat.type() <= QTransform::TxScale) {
4952 if (mat.type() == QTransform::TxNone) // identity matrix
4953 return *this;
4954 else if (mat.m11() == -1. && mat.m22() == -1.)
4955 return rotated180(*this);
4956
4957 hdf = qAbs(mat.m22()) * hs;
4958 wdf = qAbs(mat.m11()) * ws;
4959 scale_xform = true;
4960 } else {
4961 if (mat.type() <= QTransform::TxRotate && mat.m11() == 0 && mat.m22() == 0) {
4962 if (mat.m12() == 1. && mat.m21() == -1.)
4963 return rotated90(*this);
4964 else if (mat.m12() == -1. && mat.m21() == 1.)
4965 return rotated270(*this);
4966 }
4967
4968 QPolygonF a(QRectF(0, 0, ws, hs));
4969 a = mat.map(a);
4970 const QRectF r = a.boundingRect();
4971 wdf = std::ceil(r.right()) - std::floor(r.left());
4972 hdf = std::ceil(r.bottom()) - std::floor(r.top());
4973 complex_xform = true;
4974 }
4975
4976 if (!(wdf < INT_MAX && hdf < INT_MAX)) // also rejects NaN
4977 return QImage();
4978 const int wd = qRound(wdf);
4979 const int hd = qRound(hdf);
4980
4981 if (scale_xform) {
4982 // The paint-based scaling is only bilinear, and has problems
4983 // with scaling smoothly more than 2x down.
4984 if (qint64(hd) * 2 < hs || qint64(wd) * 2 < ws)
4985 nonpaintable_scale_xform = true;
4986 // We cannot paint on a CMYK image, so don't try to do so
4987 if (format() == QImage::Format_CMYK8888)
4988 nonpaintable_scale_xform = true;
4989 }
4990
4991 if (wd == 0 || hd == 0)
4992 return QImage();
4993
4994 if (scale_xform && mode == Qt::SmoothTransformation) {
4995 switch (format()) {
4996 case QImage::Format_RGB32:
4997 case QImage::Format_ARGB32_Premultiplied:
4998#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
4999 case QImage::Format_RGBX8888:
5000#endif
5001 case QImage::Format_RGBA8888_Premultiplied:
5002#if QT_CONFIG(raster_64bit)
5003 case QImage::Format_RGBX64:
5004 case QImage::Format_RGBA64_Premultiplied:
5005#endif
5006 case QImage::Format_CMYK8888:
5007 // Use smoothScaled for scaling when we can do so without conversion.
5008 if (mat.m11() > 0.0F && mat.m22() > 0.0F)
5009 return smoothScaled(wd, hd);
5010 break;
5011 default:
5012 break;
5013 }
5014 // Otherwise only use it when the scaling factor demands it, or the image is large enough to scale multi-threaded
5015 if (nonpaintable_scale_xform
5016#if QT_CONFIG(qtgui_threadpool)
5017 || qint64(ws) * hs >= (1 << 20)
5018#endif
5019 ) {
5020 QImage scaledImage;
5021 if (mat.m11() < 0.0F && mat.m22() < 0.0F) { // horizontal/vertical flip
5022 scaledImage = smoothScaled(wd, hd).flipped(Qt::Horizontal | Qt::Vertical);
5023 } else if (mat.m11() < 0.0F) { // horizontal flip
5024 scaledImage = smoothScaled(wd, hd).flipped(Qt::Horizontal);
5025 } else if (mat.m22() < 0.0F) { // vertical flip
5026 scaledImage = smoothScaled(wd, hd).flipped(Qt::Vertical);
5027 } else { // no flipping
5028 scaledImage = smoothScaled(wd, hd);
5029 }
5030
5031 switch (format()) {
5032 case QImage::Format_Mono:
5033 case QImage::Format_MonoLSB:
5034 case QImage::Format_Indexed8:
5035 return scaledImage;
5036 default:
5037 return scaledImage.convertToFormat(format());
5038 }
5039 }
5040 }
5041
5042 int bpp = depth();
5043
5044 qsizetype sbpl = bytesPerLine();
5045 const uchar *sptr = bits();
5046
5047 QImage::Format target_format = d->format;
5048
5049 if (complex_xform || mode == Qt::SmoothTransformation) {
5050 if (d->format < QImage::Format_RGB32 || (!hasAlphaChannel() && complex_xform)) {
5051 target_format = qt_alphaVersion(d->format);
5052 }
5053 }
5054
5055 QImage dImage(wd, hd, target_format);
5057
5058 if (target_format == QImage::Format_MonoLSB
5059 || target_format == QImage::Format_Mono
5060 || target_format == QImage::Format_Indexed8) {
5061 dImage.d->colortable = d->colortable;
5062 dImage.d->has_alpha_clut = d->has_alpha_clut | complex_xform;
5063 }
5064
5065 // initizialize the data
5066 if (target_format == QImage::Format_Indexed8) {
5067 if (dImage.d->colortable.size() < 256) {
5068 // colors are left in the color table, so pick that one as transparent
5069 dImage.d->colortable.append(0x0);
5070 memset(dImage.bits(), dImage.d->colortable.size() - 1, dImage.d->nbytes);
5071 } else {
5072 memset(dImage.bits(), 0, dImage.d->nbytes);
5073 }
5074 } else
5075 memset(dImage.bits(), 0x00, dImage.d->nbytes);
5076
5077 if (target_format >= QImage::Format_RGB32 && target_format != QImage::Format_CMYK8888) {
5078 // Prevent QPainter from applying devicePixelRatio corrections
5079 QImage sImage = (devicePixelRatio() != 1) ? QImage(constBits(), width(), height(), format()) : *this;
5080 if (sImage.d != d
5081 && (d->format == QImage::Format_MonoLSB
5082 || d->format == QImage::Format_Mono
5083 || d->format == QImage::Format_Indexed8)) {
5084 sImage.d->colortable = d->colortable;
5085 sImage.d->has_alpha_clut = d->has_alpha_clut;
5086 }
5087
5088 Q_ASSERT(sImage.devicePixelRatio() == 1);
5089 Q_ASSERT(sImage.devicePixelRatio() == dImage.devicePixelRatio());
5090
5091 QPainter p(&dImage);
5092 if (mode == Qt::SmoothTransformation) {
5093 p.setRenderHint(QPainter::Antialiasing);
5094 p.setRenderHint(QPainter::SmoothPixmapTransform);
5095 }
5096 p.setTransform(mat);
5097 p.drawImage(QPoint(0, 0), sImage);
5098 } else {
5099 bool invertible;
5100 mat = mat.inverted(&invertible); // invert matrix
5101 if (!invertible) // error, return null image
5102 return QImage();
5103
5104 // create target image (some of the code is from QImage::copy())
5105 int type = format() == Format_Mono ? QT_XFORM_TYPE_MSBFIRST : QT_XFORM_TYPE_LSBFIRST;
5106 qsizetype dbpl = dImage.bytesPerLine();
5107 qt_xForm_helper(mat, 0, type, bpp, dImage.bits(), dbpl, 0, hd, sptr, sbpl, ws, hs);
5108 }
5109 copyMetadata(dImage.d, d);
5110
5111 return dImage;
5112}
5113
5114/*!
5115 \fn QTransform QImage::trueMatrix(const QTransform &matrix, int width, int height)
5116
5117 Returns the actual matrix used for transforming an image with the
5118 given \a width, \a height and \a matrix.
5119
5120 When transforming an image using the transformed() function, the
5121 transformation matrix is internally adjusted to compensate for
5122 unwanted translation, i.e. transformed() returns the smallest
5123 image containing all transformed points of the original image.
5124 This function returns the modified matrix, which maps points
5125 correctly from the original image into the new image.
5126
5127 Unlike the other overload, this function creates transformation
5128 matrices that can be used to perform perspective
5129 transformations on images.
5130
5131 \sa transformed(), {QImage#Image Transformations}{Image
5132 Transformations}
5133*/
5134
5135QTransform QImage::trueMatrix(const QTransform &matrix, int w, int h)
5136{
5137 const QRectF mapped = matrix.mapRect(QRectF(0, 0, w, h));
5138 // Same as toAlignedRect().topLeft(), but safe from int overflow:
5139 return matrix * QTransform().translate(-std::floor(mapped.left()), -std::floor(mapped.top()));
5140}
5141
5142/*!
5143 \since 5.14
5144
5145 Sets the image color space to \a colorSpace without performing any conversions on image data.
5146
5147 \sa colorSpace()
5148*/
5149void QImage::setColorSpace(const QColorSpace &colorSpace)
5150{
5151 if (!d)
5152 return;
5153 if (d->colorSpace == colorSpace)
5154 return;
5155 if (colorSpace.isValid() && !qt_compatibleColorModelSource(pixelFormat().colorModel(), colorSpace.colorModel()))
5156 return;
5157
5158 detachMetadata(false);
5159 if (d)
5160 d->colorSpace = colorSpace;
5161}
5162
5163/*!
5164 \since 5.14
5165
5166 Converts the image to \a colorSpace.
5167
5168 If the image has no valid color space, the method does nothing.
5169
5170 \note If \a colorSpace is not compatible with the current format, the image
5171 will be converted to one that is.
5172
5173 \sa convertedToColorSpace(), setColorSpace()
5174*/
5175void QImage::convertToColorSpace(const QColorSpace &colorSpace)
5176{
5177 if (!d || !d->colorSpace.isValid())
5178 return;
5179 if (!colorSpace.isValidTarget()) {
5180 qWarning() << "QImage::convertToColorSpace: Output colorspace is not valid";
5181 return;
5182 }
5183 if (d->colorSpace == colorSpace)
5184 return;
5185 if (!qt_compatibleColorModelTarget(pixelFormat().colorModel(),
5186 colorSpace.colorModel(), colorSpace.transformModel())) {
5187 *this = convertedToColorSpace(colorSpace);
5188 return;
5189 }
5190 applyColorTransform(d->colorSpace.transformationToColorSpace(colorSpace));
5191 if (d->ref.loadRelaxed() != 1)
5192 detachMetadata(false);
5193 d->colorSpace = colorSpace;
5194}
5195
5196/*!
5197 \since 6.8
5198
5199 Converts the image to \a colorSpace and \a format.
5200
5201 If the image has no valid color space, the method does nothing,
5202 nor if the color space is not compatible with with the format.
5203
5204 The specified image conversion \a flags control how the image data
5205 is handled during the format conversion process.
5206
5207 \sa convertedToColorSpace(), setColorSpace()
5208*/
5209void QImage::convertToColorSpace(const QColorSpace &colorSpace, QImage::Format format, Qt::ImageConversionFlags flags)
5210{
5211 if (!d || !d->colorSpace.isValid())
5212 return;
5213 if (!colorSpace.isValidTarget()) {
5214 qWarning() << "QImage::convertToColorSpace: Output colorspace is not valid";
5215 return;
5216 }
5217 if (!qt_compatibleColorModelTarget(toPixelFormat(format).colorModel(),
5218 colorSpace.colorModel(), colorSpace.transformModel())) {
5219 qWarning() << "QImage::convertToColorSpace: Color space is not compatible with format";
5220 return;
5221 }
5222
5223 if (d->colorSpace == colorSpace)
5224 return convertTo(format, flags);
5225 applyColorTransform(d->colorSpace.transformationToColorSpace(colorSpace), format, flags);
5226 d->colorSpace = colorSpace;
5227}
5228
5229/*!
5230 \since 5.14
5231
5232 Returns the image converted to \a colorSpace.
5233
5234 If the image has no valid color space, a null QImage is returned.
5235
5236 \note If \a colorSpace is not compatible with the current format,
5237 the returned image will also be converted to a format this is.
5238 For more control over returned image format, see the three argument
5239 overload of this method.
5240
5241 \sa convertToColorSpace(), colorTransformed()
5242*/
5243QImage QImage::convertedToColorSpace(const QColorSpace &colorSpace) const
5244{
5245 if (!d || !d->colorSpace.isValid())
5246 return QImage();
5247 if (!colorSpace.isValidTarget()) {
5248 qWarning() << "QImage::convertedToColorSpace: Output colorspace is not valid";
5249 return QImage();
5250 }
5251 if (d->colorSpace == colorSpace)
5252 return *this;
5253 QImage image = colorTransformed(d->colorSpace.transformationToColorSpace(colorSpace));
5254 image.setColorSpace(colorSpace);
5255 return image;
5256}
5257
5258/*!
5259 \fn QImage QImage::convertedToColorSpace(const QColorSpace &colorSpace, QImage::Format format, Qt::ImageConversionFlags flags) const &
5260 \fn QImage QImage::convertedToColorSpace(const QColorSpace &colorSpace, QImage::Format format, Qt::ImageConversionFlags flags) &&
5261 \since 6.8
5262
5263 Returns the image converted to \a colorSpace and \a format.
5264
5265 If the image has no valid color space, a null QImage is returned.
5266
5267 The specified image conversion \a flags control how the image data
5268 is handled during the format conversion process.
5269
5270 \sa colorTransformed()
5271*/
5272QImage QImage::convertedToColorSpace(const QColorSpace &colorSpace, QImage::Format format, Qt::ImageConversionFlags flags) const &
5273{
5274 if (!d || !d->colorSpace.isValid())
5275 return QImage();
5276 if (!colorSpace.isValidTarget()) {
5277 qWarning() << "QImage::convertedToColorSpace: Output colorspace is not valid";
5278 return QImage();
5279 }
5280 if (!qt_compatibleColorModelTarget(toPixelFormat(format).colorModel(),
5281 colorSpace.colorModel(), colorSpace.transformModel())) {
5282 qWarning() << "QImage::convertedToColorSpace: Color space is not compatible with format";
5283 return QImage();
5284 }
5285 if (d->colorSpace == colorSpace)
5286 return convertedTo(format, flags);
5287 QImage image = colorTransformed(d->colorSpace.transformationToColorSpace(colorSpace), format, flags);
5288 image.setColorSpace(colorSpace);
5289 return image;
5290}
5291
5292QImage QImage::convertedToColorSpace(const QColorSpace &colorSpace, QImage::Format format, Qt::ImageConversionFlags flags) &&
5293{
5294 if (!d || !d->colorSpace.isValid())
5295 return QImage();
5296 if (!colorSpace.isValidTarget()) {
5297 qWarning() << "QImage::convertedToColorSpace: Output colorspace is not valid";
5298 return QImage();
5299 }
5300 if (!qt_compatibleColorModelTarget(toPixelFormat(format).colorModel(),
5301 colorSpace.colorModel(), colorSpace.transformModel())) {
5302 qWarning() << "QImage::convertedToColorSpace: Color space is not compatible with format";
5303 return QImage();
5304 }
5305 if (d->colorSpace == colorSpace)
5306 return convertedTo(format, flags);
5307 applyColorTransform(d->colorSpace.transformationToColorSpace(colorSpace), format, flags);
5308 return std::move(*this);
5309}
5310
5311/*!
5312 \since 5.14
5313
5314 Returns the color space of the image if a color space is defined.
5315*/
5316QColorSpace QImage::colorSpace() const
5317{
5318 if (!d)
5319 return QColorSpace();
5320 return d->colorSpace;
5321}
5322
5323/*!
5324 \since 5.14
5325
5326 Applies the color transformation \a transform to all pixels in the image.
5327*/
5328void QImage::applyColorTransform(const QColorTransform &transform)
5329{
5330 if (transform.isIdentity())
5331 return;
5332
5333 if (!qt_compatibleColorModelSource(pixelFormat().colorModel(), QColorTransformPrivate::get(transform)->colorSpaceIn->colorModel) ||
5334 !qt_compatibleColorModelTarget(pixelFormat().colorModel(), QColorTransformPrivate::get(transform)->colorSpaceOut->colorModel,
5335 QColorTransformPrivate::get(transform)->colorSpaceOut->transformModel)) {
5336 qWarning() << "QImage::applyColorTransform can not apply format switching transform without switching format";
5337 return;
5338 }
5339
5340 detach();
5341 if (!d)
5342 return;
5343 if (pixelFormat().colorModel() == QPixelFormat::Indexed) {
5344 for (int i = 0; i < d->colortable.size(); ++i)
5345 d->colortable[i] = transform.map(d->colortable[i]);
5346 return;
5347 }
5348 QImage::Format oldFormat = format();
5349 if (qt_fpColorPrecision(oldFormat)) {
5350 if (oldFormat != QImage::Format_RGBX32FPx4 && oldFormat != QImage::Format_RGBA32FPx4
5351 && oldFormat != QImage::Format_RGBA32FPx4_Premultiplied)
5352 convertTo(QImage::Format_RGBA32FPx4);
5353 } else if (depth() > 32) {
5354 if (oldFormat != QImage::Format_RGBX64 && oldFormat != QImage::Format_RGBA64
5355 && oldFormat != QImage::Format_RGBA64_Premultiplied)
5356 convertTo(QImage::Format_RGBA64);
5357 } else if (oldFormat != QImage::Format_ARGB32 && oldFormat != QImage::Format_RGB32
5358 && oldFormat != QImage::Format_ARGB32_Premultiplied && oldFormat != QImage::Format_CMYK8888
5359 && oldFormat != QImage::Format_Grayscale8 && oldFormat != QImage::Format_Grayscale16) {
5360 if (hasAlphaChannel())
5361 convertTo(QImage::Format_ARGB32);
5362 else
5363 convertTo(QImage::Format_RGB32);
5364 }
5365
5366 QColorTransformPrivate::TransformFlags flags = QColorTransformPrivate::Unpremultiplied;
5367 switch (format()) {
5368 case Format_ARGB32_Premultiplied:
5369 case Format_RGBA64_Premultiplied:
5370 case Format_RGBA32FPx4_Premultiplied:
5371 flags = QColorTransformPrivate::Premultiplied;
5372 break;
5373 case Format_Grayscale8:
5374 case Format_Grayscale16:
5375 case Format_RGB32:
5376 case Format_CMYK8888:
5377 case Format_RGBX64:
5378 case Format_RGBX32FPx4:
5379 flags = QColorTransformPrivate::InputOpaque;
5380 break;
5381 case Format_ARGB32:
5382 case Format_RGBA64:
5383 case Format_RGBA32FPx4:
5384 break;
5385 default:
5386 Q_UNREACHABLE();
5387 }
5388
5389 std::function<void(int,int)> transformSegment;
5390
5391 if (format() == Format_Grayscale8) {
5392 transformSegment = [&](int yStart, int yEnd) {
5393 for (int y = yStart; y < yEnd; ++y) {
5394 uint8_t *scanline = reinterpret_cast<uint8_t *>(d->data + y * d->bytes_per_line);
5395 QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
5396 }
5397 };
5398 } else if (format() == Format_Grayscale16) {
5399 transformSegment = [&](int yStart, int yEnd) {
5400 for (int y = yStart; y < yEnd; ++y) {
5401 uint16_t *scanline = reinterpret_cast<uint16_t *>(d->data + y * d->bytes_per_line);
5402 QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
5403 }
5404 };
5405 } else if (qt_fpColorPrecision(format())) {
5406 transformSegment = [&](int yStart, int yEnd) {
5407 for (int y = yStart; y < yEnd; ++y) {
5408 QRgbaFloat32 *scanline = reinterpret_cast<QRgbaFloat32 *>(d->data + y * d->bytes_per_line);
5409 QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
5410 }
5411 };
5412 } else if (depth() > 32) {
5413 transformSegment = [&](int yStart, int yEnd) {
5414 for (int y = yStart; y < yEnd; ++y) {
5415 QRgba64 *scanline = reinterpret_cast<QRgba64 *>(d->data + y * d->bytes_per_line);
5416 QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
5417 }
5418 };
5419 } else if (oldFormat == QImage::Format_CMYK8888) {
5420 transformSegment = [&](int yStart, int yEnd) {
5421 for (int y = yStart; y < yEnd; ++y) {
5422 QCmyk32 *scanline = reinterpret_cast<QCmyk32 *>(d->data + y * d->bytes_per_line);
5423 QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
5424 }
5425 };
5426 } else {
5427 transformSegment = [&](int yStart, int yEnd) {
5428 for (int y = yStart; y < yEnd; ++y) {
5429 QRgb *scanline = reinterpret_cast<QRgb *>(d->data + y * d->bytes_per_line);
5430 QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
5431 }
5432 };
5433 }
5434
5435#if QT_CONFIG(qtgui_threadpool)
5436 int segments = (qsizetype(width()) * height()) >> 16;
5437 segments = std::min(segments, height());
5438 QThreadPool *threadPool = QGuiApplicationPrivate::qtGuiThreadPool();
5439 if (segments > 1 && threadPool && !threadPool->contains(QThread::currentThread())) {
5440 QLatch latch(segments);
5441 int y = 0;
5442 for (int i = 0; i < segments; ++i) {
5443 int yn = (height() - y) / (segments - i);
5444 threadPool->start([&, y, yn]() {
5445 transformSegment(y, y + yn);
5446 latch.countDown();
5447 });
5448 y += yn;
5449 }
5450 latch.wait();
5451 } else
5452#endif
5453 transformSegment(0, height());
5454
5455 if (oldFormat != format())
5456 *this = std::move(*this).convertToFormat(oldFormat);
5457}
5458
5459/*!
5460 \since 6.8
5461
5462 Applies the color transformation \a transform to all pixels in the image, and converts the format of the image to \a toFormat.
5463
5464 The specified image conversion \a flags control how the image data
5465 is handled during the format conversion process.
5466*/
5467void QImage::applyColorTransform(const QColorTransform &transform, QImage::Format toFormat, Qt::ImageConversionFlags flags)
5468{
5469 if (!d)
5470 return;
5471 if (transform.isIdentity())
5472 return convertTo(toFormat, flags);
5473
5474 *this = colorTransformed(transform, toFormat, flags);
5475}
5476
5477/*!
5478 \since 6.4
5479
5480 Returns the image color transformed using \a transform on all pixels in the image.
5481
5482 \note If \a transform has a source color space which is incompatible with the format of this image,
5483 returns a null QImage. If \a transform has a target color space which is incompatible with the format
5484 of this image, the image will also be converted to a compatible format. For more control about the
5485 choice of the target pixel format, see the three argument overload of this method.
5486
5487 \sa applyColorTransform()
5488*/
5489QImage QImage::colorTransformed(const QColorTransform &transform) const &
5490{
5491 if (!d)
5492 return QImage();
5493 if (transform.isIdentity())
5494 return *this;
5495
5496 const QColorSpacePrivate *inColorSpace = QColorTransformPrivate::get(transform)->colorSpaceIn.constData();
5497 const QColorSpacePrivate *outColorSpace = QColorTransformPrivate::get(transform)->colorSpaceOut.constData();
5498 if (!qt_compatibleColorModelSource(pixelFormat().colorModel(), inColorSpace->colorModel)) {
5499 qWarning() << "QImage::colorTransformed: Invalid input color space for transform";
5500 return QImage();
5501 }
5502 if (!qt_compatibleColorModelTarget(pixelFormat().colorModel(), outColorSpace->colorModel, outColorSpace->transformModel)) {
5503 // All model switching transforms are opaque in at least one end.
5504 switch (outColorSpace->colorModel) {
5505 case QColorSpace::ColorModel::Rgb:
5506 return colorTransformed(transform, qt_highColorPrecision(format(), true) ? QImage::Format_RGBX64 : QImage::Format_RGB32);
5507 case QColorSpace::ColorModel::Gray:
5508 return colorTransformed(transform, qt_highColorPrecision(format(), true) ? QImage::Format_Grayscale16 : QImage::Format_Grayscale8);
5509 case QColorSpace::ColorModel::Cmyk:
5510 return colorTransformed(transform, QImage::Format_CMYK8888);
5511 case QColorSpace::ColorModel::Undefined:
5512 break;
5513 }
5514 return QImage();
5515 }
5516
5517 QImage image = copy();
5518 image.applyColorTransform(transform);
5519 return image;
5520}
5521
5522static bool isRgb32Data(QImage::Format f)
5523{
5524 switch (f) {
5525 case QImage::Format_RGB32:
5526 case QImage::Format_ARGB32:
5527 case QImage::Format_ARGB32_Premultiplied:
5528 return true;
5529 default:
5530 break;
5531 }
5532 return false;
5533}
5534
5535static bool isRgb64Data(QImage::Format f)
5536{
5537 switch (f) {
5538 case QImage::Format_RGBX64:
5539 case QImage::Format_RGBA64:
5540 case QImage::Format_RGBA64_Premultiplied:
5541 return true;
5542 default:
5543 break;
5544 }
5545 return false;
5546}
5547
5548static bool isRgb32fpx4Data(QImage::Format f)
5549{
5550 switch (f) {
5551 case QImage::Format_RGBX32FPx4:
5552 case QImage::Format_RGBA32FPx4:
5553 case QImage::Format_RGBA32FPx4_Premultiplied:
5554 return true;
5555 default:
5556 break;
5557 }
5558 return false;
5559}
5560
5561/*!
5562 \since 6.8
5563
5564 Returns the image color transformed using \a transform on all pixels in the image, returning an image of format \a toFormat.
5565
5566 The specified image conversion \a flags control how the image data
5567 is handled during the format conversion process.
5568
5569 \note If \a transform has a source color space which is incompatible with the format of this image,
5570 or a target color space that is incompatible with \a toFormat, returns a null QImage.
5571
5572 \sa applyColorTransform()
5573*/
5574QImage QImage::colorTransformed(const QColorTransform &transform, QImage::Format toFormat, Qt::ImageConversionFlags flags) const &
5575{
5576 if (!d)
5577 return QImage();
5578 if (toFormat == QImage::Format_Invalid)
5579 toFormat = format();
5580 if (transform.isIdentity())
5581 return convertedTo(toFormat, flags);
5582
5583 const QColorSpacePrivate *inColorSpace = QColorTransformPrivate::get(transform)->colorSpaceIn.constData();
5584 const QColorSpacePrivate *outColorSpace = QColorTransformPrivate::get(transform)->colorSpaceOut.constData();
5585 if (!qt_compatibleColorModelSource(pixelFormat().colorModel(), inColorSpace->colorModel)) {
5586 qWarning() << "QImage::colorTransformed: Invalid input color space for transform";
5587 return QImage();
5588 }
5589 if (!qt_compatibleColorModelTarget(toPixelFormat(toFormat).colorModel(), outColorSpace->colorModel, outColorSpace->transformModel)) {
5590 qWarning() << "QImage::colorTransformed: Invalid output color space for transform";
5591 return QImage();
5592 }
5593
5594 QImage fromImage = *this;
5595
5596 QImage::Format tmpFormat = toFormat;
5597 switch (toFormat) {
5598 case QImage::Format_RGB32:
5599 case QImage::Format_ARGB32:
5600 case QImage::Format_ARGB32_Premultiplied:
5601 case QImage::Format_RGBX32FPx4:
5602 case QImage::Format_RGBA32FPx4:
5603 case QImage::Format_RGBA32FPx4_Premultiplied:
5604 case QImage::Format_RGBX64:
5605 case QImage::Format_RGBA64:
5606 case QImage::Format_RGBA64_Premultiplied:
5607 case QImage::Format_Grayscale8:
5608 case QImage::Format_Grayscale16:
5609 case QImage::Format_CMYK8888:
5610 // can be output natively
5611 break;
5612 case QImage::Format_RGB16:
5613 case QImage::Format_RGB444:
5614 case QImage::Format_RGB555:
5615 case QImage::Format_RGB666:
5616 case QImage::Format_RGB888:
5617 case QImage::Format_BGR888:
5618 case QImage::Format_RGBX8888:
5619 tmpFormat = QImage::Format_RGB32;
5620 break;
5621 case QImage::Format_Mono:
5622 case QImage::Format_MonoLSB:
5623 case QImage::Format_Indexed8:
5624 case QImage::Format_ARGB8565_Premultiplied:
5625 case QImage::Format_ARGB6666_Premultiplied:
5626 case QImage::Format_ARGB8555_Premultiplied:
5627 case QImage::Format_ARGB4444_Premultiplied:
5628 case QImage::Format_RGBA8888:
5629 case QImage::Format_RGBA8888_Premultiplied:
5630 tmpFormat = QImage::Format_ARGB32;
5631 break;
5632 case QImage::Format_BGR30:
5633 case QImage::Format_RGB30:
5634 tmpFormat = QImage::Format_RGBX64;
5635 break;
5636 case QImage::Format_A2BGR30_Premultiplied:
5637 case QImage::Format_A2RGB30_Premultiplied:
5638 tmpFormat = QImage::Format_RGBA64;
5639 break;
5640 case QImage::Format_RGBX16FPx4:
5641 case QImage::Format_RGBA16FPx4:
5642 case QImage::Format_RGBA16FPx4_Premultiplied:
5643 tmpFormat = QImage::Format_RGBA32FPx4;
5644 break;
5645 case QImage::Format_Alpha8:
5646 return convertedTo(QImage::Format_Alpha8);
5647 case QImage::Format_Invalid:
5648 case QImage::NImageFormats:
5649 Q_UNREACHABLE();
5650 break;
5651 }
5652 QColorSpace::ColorModel inColorData = qt_csColorData(pixelFormat().colorModel());
5653 QColorSpace::ColorModel outColorData = qt_csColorData(toPixelFormat(toFormat).colorModel());
5654 // Ensure only precision increasing transforms
5655 if (inColorData != outColorData) {
5656 if (fromImage.format() == QImage::Format_Grayscale8 && outColorData == QColorSpace::ColorModel::Rgb)
5657 tmpFormat = QImage::Format_RGB32;
5658 else if (tmpFormat == QImage::Format_Grayscale8 && qt_highColorPrecision(fromImage.format()))
5659 tmpFormat = QImage::Format_Grayscale16;
5660 else if (fromImage.format() == QImage::Format_Grayscale16 && outColorData == QColorSpace::ColorModel::Rgb)
5661 tmpFormat = QImage::Format_RGBX64;
5662 } else {
5663 if (tmpFormat == QImage::Format_Grayscale8 && fromImage.format() == QImage::Format_Grayscale16)
5664 tmpFormat = QImage::Format_Grayscale16;
5665 else if (qt_fpColorPrecision(fromImage.format()) && !qt_fpColorPrecision(tmpFormat))
5666 tmpFormat = QImage::Format_RGBA32FPx4;
5667 else if (isRgb32Data(tmpFormat) && qt_highColorPrecision(fromImage.format(), true))
5668 tmpFormat = QImage::Format_RGBA64;
5669 }
5670
5671 QImage toImage(size(), tmpFormat);
5672 copyMetadata(&toImage, *this);
5673
5674 std::function<void(int, int)> transformSegment;
5675 QColorTransformPrivate::TransformFlags transFlags = QColorTransformPrivate::Unpremultiplied;
5676
5677 if (inColorData != outColorData) {
5678 // Needs color model switching transform
5679 if (inColorData == QColorSpace::ColorModel::Gray && outColorData == QColorSpace::ColorModel::Rgb) {
5680 // Gray -> RGB
5681 if (format() == QImage::Format_Grayscale8) {
5682 transformSegment = [&](int yStart, int yEnd) {
5683 for (int y = yStart; y < yEnd; ++y) {
5684 const quint8 *in_scanline = reinterpret_cast<const quint8 *>(d->data + y * d->bytes_per_line);
5685 QRgb *out_scanline = reinterpret_cast<QRgb *>(toImage.d->data + y * toImage.bytesPerLine());
5686 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5687 }
5688 };
5689 } else {
5690 transformSegment = [&](int yStart, int yEnd) {
5691 for (int y = yStart; y < yEnd; ++y) {
5692 const quint16 *in_scanline = reinterpret_cast<const quint16 *>(d->data + y * d->bytes_per_line);
5693 QRgba64 *out_scanline = reinterpret_cast<QRgba64 *>(toImage.d->data + y * toImage.bytesPerLine());
5694 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5695 }
5696 };
5697 }
5698 } else if (inColorData == QColorSpace::ColorModel::Gray && outColorData == QColorSpace::ColorModel::Cmyk) {
5699 // Gray -> CMYK
5700 if (format() == QImage::Format_Grayscale8) {
5701 transformSegment = [&](int yStart, int yEnd) {
5702 for (int y = yStart; y < yEnd; ++y) {
5703 const quint8 *in_scanline = reinterpret_cast<const quint8 *>(d->data + y * d->bytes_per_line);
5704 QCmyk32 *out_scanline = reinterpret_cast<QCmyk32 *>(toImage.d->data + y * toImage.bytesPerLine());
5705 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5706 }
5707 };
5708 } else {
5709 transformSegment = [&](int yStart, int yEnd) {
5710 for (int y = yStart; y < yEnd; ++y) {
5711 const quint16 *in_scanline = reinterpret_cast<const quint16 *>(d->data + y * d->bytes_per_line);
5712 QCmyk32 *out_scanline = reinterpret_cast<QCmyk32 *>(toImage.d->data + y * toImage.bytesPerLine());
5713 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5714 }
5715 };
5716 }
5717 } else if (inColorData == QColorSpace::ColorModel::Rgb && outColorData == QColorSpace::ColorModel::Gray) {
5718 // RGB -> Gray
5719 if (tmpFormat == QImage::Format_Grayscale8) {
5720 fromImage.convertTo(QImage::Format_RGB32);
5721 transformSegment = [&](int yStart, int yEnd) {
5722 for (int y = yStart; y < yEnd; ++y) {
5723 const QRgb *in_scanline = reinterpret_cast<const QRgb *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5724 quint8 *out_scanline = reinterpret_cast<quint8 *>(toImage.d->data + y * toImage.bytesPerLine());
5725 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5726 }
5727 };
5728 } else {
5729 fromImage.convertTo(QImage::Format_RGBX64);
5730 transformSegment = [&](int yStart, int yEnd) {
5731 for (int y = yStart; y < yEnd; ++y) {
5732 const QRgba64 *in_scanline = reinterpret_cast<const QRgba64 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5733 quint16 *out_scanline = reinterpret_cast<quint16 *>(toImage.d->data + y * toImage.bytesPerLine());
5734 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5735 }
5736 };
5737 }
5738 } else if (inColorData == QColorSpace::ColorModel::Cmyk && outColorData == QColorSpace::ColorModel::Gray) {
5739 // CMYK -> Gray
5740 if (tmpFormat == QImage::Format_Grayscale8) {
5741 transformSegment = [&](int yStart, int yEnd) {
5742 for (int y = yStart; y < yEnd; ++y) {
5743 const QCmyk32 *in_scanline = reinterpret_cast<const QCmyk32 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5744 quint8 *out_scanline = reinterpret_cast<quint8 *>(toImage.d->data + y * toImage.bytesPerLine());
5745 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5746 }
5747 };
5748 } else {
5749 transformSegment = [&](int yStart, int yEnd) {
5750 for (int y = yStart; y < yEnd; ++y) {
5751 const QCmyk32 *in_scanline = reinterpret_cast<const QCmyk32 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5752 quint16 *out_scanline = reinterpret_cast<quint16 *>(toImage.d->data + y * toImage.bytesPerLine());
5753 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5754 }
5755 };
5756 }
5757 } else if (inColorData == QColorSpace::ColorModel::Cmyk && outColorData == QColorSpace::ColorModel::Rgb) {
5758 // CMYK -> RGB
5759 if (isRgb32Data(tmpFormat) ) {
5760 transformSegment = [&](int yStart, int yEnd) {
5761 for (int y = yStart; y < yEnd; ++y) {
5762 const QCmyk32 *in_scanline = reinterpret_cast<const QCmyk32 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5763 QRgb *out_scanline = reinterpret_cast<QRgb *>(toImage.d->data + y * toImage.bytesPerLine());
5764 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5765 }
5766 };
5767 } else if (isRgb64Data(tmpFormat)) {
5768 transformSegment = [&](int yStart, int yEnd) {
5769 for (int y = yStart; y < yEnd; ++y) {
5770 const QCmyk32 *in_scanline = reinterpret_cast<const QCmyk32 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5771 QRgba64 *out_scanline = reinterpret_cast<QRgba64 *>(toImage.d->data + y * toImage.bytesPerLine());
5772 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5773 }
5774 };
5775 } else {
5776 Q_ASSERT(isRgb32fpx4Data(tmpFormat));
5777 transformSegment = [&](int yStart, int yEnd) {
5778 for (int y = yStart; y < yEnd; ++y) {
5779 const QCmyk32 *in_scanline = reinterpret_cast<const QCmyk32 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5780 QRgbaFloat32 *out_scanline = reinterpret_cast<QRgbaFloat32 *>(toImage.d->data + y * toImage.bytesPerLine());
5781 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), QColorTransformPrivate::InputOpaque);
5782 }
5783 };
5784 }
5785 } else if (inColorData == QColorSpace::ColorModel::Rgb && outColorData == QColorSpace::ColorModel::Cmyk) {
5786 // RGB -> CMYK
5787 if (!fromImage.hasAlphaChannel())
5788 transFlags = QColorTransformPrivate::InputOpaque;
5789 else if (qPixelLayouts[fromImage.format()].premultiplied)
5790 transFlags = QColorTransformPrivate::Premultiplied;
5791 if (isRgb32Data(fromImage.format()) ) {
5792 transformSegment = [&](int yStart, int yEnd) {
5793 for (int y = yStart; y < yEnd; ++y) {
5794 const QRgb *in_scanline = reinterpret_cast<const QRgb *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5795 QCmyk32 *out_scanline = reinterpret_cast<QCmyk32 *>(toImage.d->data + y * toImage.bytesPerLine());
5796 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5797 }
5798 };
5799 } else if (isRgb64Data(fromImage.format())) {
5800 transformSegment = [&](int yStart, int yEnd) {
5801 for (int y = yStart; y < yEnd; ++y) {
5802 const QRgba64 *in_scanline = reinterpret_cast<const QRgba64 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5803 QCmyk32 *out_scanline = reinterpret_cast<QCmyk32 *>(toImage.d->data + y * toImage.bytesPerLine());
5804 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5805 }
5806 };
5807 } else {
5808 Q_ASSERT(isRgb32fpx4Data(fromImage.format()));
5809 transformSegment = [&](int yStart, int yEnd) {
5810 for (int y = yStart; y < yEnd; ++y) {
5811 const QRgbaFloat32 *in_scanline = reinterpret_cast<const QRgbaFloat32 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5812 QCmyk32 *out_scanline = reinterpret_cast<QCmyk32 *>(toImage.d->data + y * toImage.bytesPerLine());
5813 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5814 }
5815 };
5816 }
5817 } else {
5818 Q_UNREACHABLE();
5819 }
5820 } else {
5821 // Conversion on same color model
5822 if (pixelFormat().colorModel() == QPixelFormat::Indexed) {
5823 for (int i = 0; i < d->colortable.size(); ++i)
5824 fromImage.d->colortable[i] = transform.map(d->colortable[i]);
5825 return fromImage.convertedTo(toFormat, flags);
5826 }
5827
5828 QImage::Format oldFormat = format();
5829 if (qt_fpColorPrecision(oldFormat)) {
5830 if (oldFormat != QImage::Format_RGBX32FPx4 && oldFormat != QImage::Format_RGBA32FPx4
5831 && oldFormat != QImage::Format_RGBA32FPx4_Premultiplied)
5832 fromImage.convertTo(QImage::Format_RGBA32FPx4);
5833 } else if (qt_highColorPrecision(oldFormat, true)) {
5834 if (oldFormat != QImage::Format_RGBX64 && oldFormat != QImage::Format_RGBA64
5835 && oldFormat != QImage::Format_RGBA64_Premultiplied && oldFormat != QImage::Format_Grayscale16)
5836 fromImage.convertTo(QImage::Format_RGBA64);
5837 } else if (oldFormat != QImage::Format_ARGB32 && oldFormat != QImage::Format_RGB32
5838 && oldFormat != QImage::Format_ARGB32_Premultiplied && oldFormat != QImage::Format_CMYK8888
5839 && oldFormat != QImage::Format_Grayscale8 && oldFormat != QImage::Format_Grayscale16) {
5840 if (hasAlphaChannel())
5841 fromImage.convertTo(QImage::Format_ARGB32);
5842 else
5843 fromImage.convertTo(QImage::Format_RGB32);
5844 }
5845
5846 if (!fromImage.hasAlphaChannel())
5847 transFlags = QColorTransformPrivate::InputOpaque;
5848 else if (qPixelLayouts[fromImage.format()].premultiplied)
5849 transFlags = QColorTransformPrivate::Premultiplied;
5850
5851 if (fromImage.format() == Format_Grayscale8) {
5852 transformSegment = [&](int yStart, int yEnd) {
5853 for (int y = yStart; y < yEnd; ++y) {
5854 const quint8 *in_scanline = reinterpret_cast<const quint8 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5855 if (tmpFormat == Format_Grayscale8) {
5856 quint8 *out_scanline = reinterpret_cast<quint8 *>(toImage.d->data + y * toImage.bytesPerLine());
5857 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5858 } else {
5859 Q_ASSERT(tmpFormat == Format_Grayscale16);
5860 quint16 *out_scanline = reinterpret_cast<quint16 *>(toImage.d->data + y * toImage.bytesPerLine());
5861 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5862 }
5863 }
5864 };
5865 } else if (fromImage.format() == Format_Grayscale16) {
5866 transformSegment = [&](int yStart, int yEnd) {
5867 for (int y = yStart; y < yEnd; ++y) {
5868 const quint16 *in_scanline = reinterpret_cast<const quint16 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5869 quint16 *out_scanline = reinterpret_cast<quint16 *>(toImage.d->data + y * toImage.bytesPerLine());
5870 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5871 }
5872 };
5873 } else if (fromImage.format() == Format_CMYK8888) {
5874 Q_ASSERT(tmpFormat == Format_CMYK8888);
5875 transformSegment = [&](int yStart, int yEnd) {
5876 for (int y = yStart; y < yEnd; ++y) {
5877 const QCmyk32 *in_scanline = reinterpret_cast<const QCmyk32 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5878 QCmyk32 *out_scanline = reinterpret_cast<QCmyk32 *>(toImage.d->data + y * toImage.bytesPerLine());
5879 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5880 }
5881 };
5882 } else if (isRgb32fpx4Data(fromImage.format())) {
5883 Q_ASSERT(isRgb32fpx4Data(tmpFormat));
5884 transformSegment = [&](int yStart, int yEnd) {
5885 for (int y = yStart; y < yEnd; ++y) {
5886 const QRgbaFloat32 *in_scanline = reinterpret_cast<const QRgbaFloat32 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5887 QRgbaFloat32 *out_scanline = reinterpret_cast<QRgbaFloat32 *>(toImage.d->data + y * toImage.bytesPerLine());
5888 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5889 }
5890 };
5891 } else if (isRgb64Data(fromImage.format())) {
5892 transformSegment = [&](int yStart, int yEnd) {
5893 for (int y = yStart; y < yEnd; ++y) {
5894 const QRgba64 *in_scanline = reinterpret_cast<const QRgba64 *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5895 if (isRgb32fpx4Data(tmpFormat)) {
5896 QRgbaFloat32 *out_scanline = reinterpret_cast<QRgbaFloat32 *>(toImage.d->data + y * toImage.bytesPerLine());
5897 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5898 } else {
5899 Q_ASSERT(isRgb64Data(tmpFormat));
5900 QRgba64 *out_scanline = reinterpret_cast<QRgba64 *>(toImage.d->data + y * toImage.bytesPerLine());
5901 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5902 }
5903 }
5904 };
5905 } else {
5906 transformSegment = [&](int yStart, int yEnd) {
5907 for (int y = yStart; y < yEnd; ++y) {
5908 const QRgb *in_scanline = reinterpret_cast<const QRgb *>(fromImage.constBits() + y * fromImage.bytesPerLine());
5909 if (isRgb32fpx4Data(tmpFormat)) {
5910 QRgbaFloat32 *out_scanline = reinterpret_cast<QRgbaFloat32 *>(toImage.d->data + y * toImage.bytesPerLine());
5911 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5912 } else if (isRgb64Data(tmpFormat)) {
5913 QRgba64 *out_scanline = reinterpret_cast<QRgba64 *>(toImage.d->data + y * toImage.bytesPerLine());
5914 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5915 } else {
5916 Q_ASSERT(isRgb32Data(tmpFormat));
5917 QRgb *out_scanline = reinterpret_cast<QRgb *>(toImage.d->data + y * toImage.bytesPerLine());
5918 QColorTransformPrivate::get(transform)->apply(out_scanline, in_scanline, width(), transFlags);
5919 }
5920 }
5921 };
5922 }
5923 }
5924
5925#if QT_CONFIG(qtgui_threadpool)
5926 int segments = (qsizetype(width()) * height()) >> 16;
5927 segments = std::min(segments, height());
5928 QThreadPool *threadPool = QGuiApplicationPrivate::qtGuiThreadPool();
5929 if (segments > 1 && threadPool && !threadPool->contains(QThread::currentThread())) {
5930 QLatch latch(segments);
5931 int y = 0;
5932 for (int i = 0; i < segments; ++i) {
5933 int yn = (height() - y) / (segments - i);
5934 threadPool->start([&, y, yn]() {
5935 transformSegment(y, y + yn);
5936 latch.countDown();
5937 });
5938 y += yn;
5939 }
5940 latch.wait();
5941 } else
5942#endif
5943 transformSegment(0, height());
5944
5945 if (tmpFormat != toFormat)
5946 toImage.convertTo(toFormat);
5947
5948 return toImage;
5949}
5950
5951/*!
5952 \since 6.4
5953 \overload
5954
5955 Returns the image color transformed using \a transform on all pixels in the image.
5956
5957 \sa applyColorTransform()
5958*/
5959QImage QImage::colorTransformed(const QColorTransform &transform) &&
5960{
5961 if (!d)
5962 return QImage();
5963
5964 const QColorSpacePrivate *inColorSpace = QColorTransformPrivate::get(transform)->colorSpaceIn.constData();
5965 const QColorSpacePrivate *outColorSpace = QColorTransformPrivate::get(transform)->colorSpaceOut.constData();
5966 if (!qt_compatibleColorModelSource(pixelFormat().colorModel(), inColorSpace->colorModel)) {
5967 qWarning() << "QImage::colorTransformed: Invalid input color space for transform";
5968 return QImage();
5969 }
5970 if (!qt_compatibleColorModelTarget(pixelFormat().colorModel(), outColorSpace->colorModel, outColorSpace->transformModel)) {
5971 // There is currently no inplace conversion of both colorspace and format, so just use the normal version.
5972 switch (outColorSpace->colorModel) {
5973 case QColorSpace::ColorModel::Rgb:
5974 return colorTransformed(transform, qt_highColorPrecision(format(), true) ? QImage::Format_RGBX64 : QImage::Format_RGB32);
5975 case QColorSpace::ColorModel::Gray:
5976 return colorTransformed(transform, qt_highColorPrecision(format(), true) ? QImage::Format_Grayscale16 : QImage::Format_Grayscale8);
5977 case QColorSpace::ColorModel::Cmyk:
5978 return colorTransformed(transform, QImage::Format_CMYK8888);
5979 case QColorSpace::ColorModel::Undefined:
5980 break;
5981 }
5982 return QImage();
5983 }
5984
5985 applyColorTransform(transform);
5986 return std::move(*this);
5987}
5988
5989/*!
5990 \since 6.8
5991 \overload
5992
5993 Returns the image color transformed using \a transform on all pixels in the image.
5994
5995 \sa applyColorTransform()
5996*/
5997QImage QImage::colorTransformed(const QColorTransform &transform, QImage::Format format, Qt::ImageConversionFlags flags) &&
5998{
5999 // There is currently no inplace conversion of both colorspace and format, so just use the normal version.
6000 return colorTransformed(transform, format, flags);
6001}
6002
6003bool QImageData::convertInPlace(QImage::Format newFormat, Qt::ImageConversionFlags flags)
6004{
6005 if (format == newFormat)
6006 return true;
6007
6008 // No in-place conversion if we have to detach
6009 if (ref.loadRelaxed() > 1 || !own_data)
6010 return false;
6011
6012 InPlace_Image_Converter converter = qimage_inplace_converter_map[format][newFormat];
6013 if (converter)
6014 return converter(this, flags);
6015 if (format > QImage::Format_Indexed8 && newFormat > QImage::Format_Indexed8 && !qimage_converter_map[format][newFormat]) {
6016 // Convert inplace generic, but only if there are no direct converters,
6017 // any direct ones are probably better even if not inplace.
6018 if (qt_highColorPrecision(newFormat, !qPixelLayouts[newFormat].hasAlphaChannel)
6019 && qt_highColorPrecision(format, !qPixelLayouts[format].hasAlphaChannel)) {
6020#if QT_CONFIG(raster_fp)
6021 if (qt_fpColorPrecision(format) && qt_fpColorPrecision(newFormat))
6022 return convert_generic_inplace_over_rgba32f(this, newFormat, flags);
6023#endif
6024 return convert_generic_inplace_over_rgb64(this, newFormat, flags);
6025 }
6026 return convert_generic_inplace(this, newFormat, flags);
6027 }
6028 return false;
6029}
6030
6031/*!
6032 \typedef QImage::DataPtr
6033 \internal
6034*/
6035
6036/*!
6037 \fn DataPtr & QImage::data_ptr()
6038 \internal
6039*/
6040
6041#ifndef QT_NO_DEBUG_STREAM
6042QDebug operator<<(QDebug dbg, const QImage &i)
6043{
6044 QDebugStateSaver saver(dbg);
6045 dbg.nospace();
6046 dbg.noquote();
6047 dbg << "QImage(";
6048 if (i.isNull()) {
6049 dbg << "null";
6050 } else {
6051 dbg << i.size() << ",format=" << i.format() << ",depth=" << i.depth();
6052 if (i.colorCount())
6053 dbg << ",colorCount=" << i.colorCount();
6054 const int bytesPerLine = i.bytesPerLine();
6055 dbg << ",devicePixelRatio=" << i.devicePixelRatio()
6056 << ",bytesPerLine=" << bytesPerLine << ",sizeInBytes=" << i.sizeInBytes();
6057 if (dbg.verbosity() > 2 && i.height() > 0) {
6058 const int outputLength = qMin(bytesPerLine, 24);
6059 dbg << ",line0="
6060 << QByteArray(reinterpret_cast<const char *>(i.scanLine(0)), outputLength).toHex()
6061 << "...";
6062 }
6063 }
6064 dbg << ')';
6065 return dbg;
6066}
6067#endif
6068
6069static constexpr QPixelFormat pixelformats[] = {
6070 //QImage::Format_Invalid:
6071 QPixelFormat(),
6072 //QImage::Format_Mono:
6073 QPixelFormat(QPixelFormat::Indexed,
6074 /*RED*/ 1,
6075 /*GREEN*/ 0,
6076 /*BLUE*/ 0,
6077 /*FOURTH*/ 0,
6078 /*FIFTH*/ 0,
6079 /*ALPHA*/ 0,
6080 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6081 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6082 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6083 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6084 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6085 //QImage::Format_MonoLSB:
6086 QPixelFormat(QPixelFormat::Indexed,
6087 /*RED*/ 1,
6088 /*GREEN*/ 0,
6089 /*BLUE*/ 0,
6090 /*FOURTH*/ 0,
6091 /*FIFTH*/ 0,
6092 /*ALPHA*/ 0,
6093 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6094 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6095 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6096 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6097 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6098 //QImage::Format_Indexed8:
6099 QPixelFormat(QPixelFormat::Indexed,
6100 /*RED*/ 8,
6101 /*GREEN*/ 0,
6102 /*BLUE*/ 0,
6103 /*FOURTH*/ 0,
6104 /*FIFTH*/ 0,
6105 /*ALPHA*/ 0,
6106 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6107 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6108 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6109 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6110 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6111 //QImage::Format_RGB32:
6112 QPixelFormat(QPixelFormat::RGB,
6113 /*RED*/ 8,
6114 /*GREEN*/ 8,
6115 /*BLUE*/ 8,
6116 /*FOURTH*/ 0,
6117 /*FIFTH*/ 0,
6118 /*ALPHA*/ 8,
6119 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6120 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6121 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6122 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6123 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6124 //QImage::Format_ARGB32:
6125 QPixelFormat(QPixelFormat::RGB,
6126 /*RED*/ 8,
6127 /*GREEN*/ 8,
6128 /*BLUE*/ 8,
6129 /*FOURTH*/ 0,
6130 /*FIFTH*/ 0,
6131 /*ALPHA*/ 8,
6132 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6133 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6134 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6135 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6136 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6137 //QImage::Format_ARGB32_Premultiplied:
6138 QPixelFormat(QPixelFormat::RGB,
6139 /*RED*/ 8,
6140 /*GREEN*/ 8,
6141 /*BLUE*/ 8,
6142 /*FOURTH*/ 0,
6143 /*FIFTH*/ 0,
6144 /*ALPHA*/ 8,
6145 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6146 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6147 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6148 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6149 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6150 //QImage::Format_RGB16:
6151 QPixelFormat(QPixelFormat::RGB,
6152 /*RED*/ 5,
6153 /*GREEN*/ 6,
6154 /*BLUE*/ 5,
6155 /*FOURTH*/ 0,
6156 /*FIFTH*/ 0,
6157 /*ALPHA*/ 0,
6158 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6159 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6160 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6161 /*INTERPRETATION*/ QPixelFormat::UnsignedShort,
6162 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6163 //QImage::Format_ARGB8565_Premultiplied:
6164 QPixelFormat(QPixelFormat::RGB,
6165 /*RED*/ 5,
6166 /*GREEN*/ 6,
6167 /*BLUE*/ 5,
6168 /*FOURTH*/ 0,
6169 /*FIFTH*/ 0,
6170 /*ALPHA*/ 8,
6171 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6172 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6173 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6174 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6175 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6176 //QImage::Format_RGB666:
6177 QPixelFormat(QPixelFormat::RGB,
6178 /*RED*/ 6,
6179 /*GREEN*/ 6,
6180 /*BLUE*/ 6,
6181 /*FOURTH*/ 0,
6182 /*FIFTH*/ 0,
6183 /*ALPHA*/ 0,
6184 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6185 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6186 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6187 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6188 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6189 //QImage::Format_ARGB6666_Premultiplied:
6190 QPixelFormat(QPixelFormat::RGB,
6191 /*RED*/ 6,
6192 /*GREEN*/ 6,
6193 /*BLUE*/ 6,
6194 /*FOURTH*/ 0,
6195 /*FIFTH*/ 0,
6196 /*ALPHA*/ 6,
6197 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6198 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6199 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6200 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6201 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6202 //QImage::Format_RGB555:
6203 QPixelFormat(QPixelFormat::RGB,
6204 /*RED*/ 5,
6205 /*GREEN*/ 5,
6206 /*BLUE*/ 5,
6207 /*FOURTH*/ 0,
6208 /*FIFTH*/ 0,
6209 /*ALPHA*/ 0,
6210 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6211 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6212 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6213 /*INTERPRETATION*/ QPixelFormat::UnsignedShort,
6214 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6215 //QImage::Format_ARGB8555_Premultiplied:
6216 QPixelFormat(QPixelFormat::RGB,
6217 /*RED*/ 5,
6218 /*GREEN*/ 5,
6219 /*BLUE*/ 5,
6220 /*FOURTH*/ 0,
6221 /*FIFTH*/ 0,
6222 /*ALPHA*/ 8,
6223 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6224 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6225 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6226 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6227 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6228 //QImage::Format_RGB888:
6229 QPixelFormat(QPixelFormat::RGB,
6230 /*RED*/ 8,
6231 /*GREEN*/ 8,
6232 /*BLUE*/ 8,
6233 /*FOURTH*/ 0,
6234 /*FIFTH*/ 0,
6235 /*ALPHA*/ 0,
6236 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6237 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6238 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6239 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6240 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6241 //QImage::Format_RGB444:
6242 QPixelFormat(QPixelFormat::RGB,
6243 /*RED*/ 4,
6244 /*GREEN*/ 4,
6245 /*BLUE*/ 4,
6246 /*FOURTH*/ 0,
6247 /*FIFTH*/ 0,
6248 /*ALPHA*/ 0,
6249 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6250 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6251 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6252 /*INTERPRETATION*/ QPixelFormat::UnsignedShort,
6253 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6254 //QImage::Format_ARGB4444_Premultiplied:
6255 QPixelFormat(QPixelFormat::RGB,
6256 /*RED*/ 4,
6257 /*GREEN*/ 4,
6258 /*BLUE*/ 4,
6259 /*FOURTH*/ 0,
6260 /*FIFTH*/ 0,
6261 /*ALPHA*/ 4,
6262 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6263 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6264 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6265 /*INTERPRETATION*/ QPixelFormat::UnsignedShort,
6266 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6267 //QImage::Format_RGBX8888:
6268 QPixelFormat(QPixelFormat::RGB,
6269 /*RED*/ 8,
6270 /*GREEN*/ 8,
6271 /*BLUE*/ 8,
6272 /*FOURTH*/ 0,
6273 /*FIFTH*/ 0,
6274 /*ALPHA*/ 8,
6275 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6276 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6277 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6278 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6279 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6280 //QImage::Format_RGBA8888:
6281 QPixelFormat(QPixelFormat::RGB,
6282 /*RED*/ 8,
6283 /*GREEN*/ 8,
6284 /*BLUE*/ 8,
6285 /*FOURTH*/ 0,
6286 /*FIFTH*/ 0,
6287 /*ALPHA*/ 8,
6288 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6289 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6290 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6291 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6292 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6293 //QImage::Format_RGBA8888_Premultiplied:
6294 QPixelFormat(QPixelFormat::RGB,
6295 /*RED*/ 8,
6296 /*GREEN*/ 8,
6297 /*BLUE*/ 8,
6298 /*FOURTH*/ 0,
6299 /*FIFTH*/ 0,
6300 /*ALPHA*/ 8,
6301 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6302 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6303 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6304 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6305 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6306 //QImage::Format_BGR30:
6307 QPixelFormat(QPixelFormat::BGR,
6308 /*RED*/ 10,
6309 /*GREEN*/ 10,
6310 /*BLUE*/ 10,
6311 /*FOURTH*/ 0,
6312 /*FIFTH*/ 0,
6313 /*ALPHA*/ 2,
6314 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6315 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6316 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6317 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6318 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6319 //QImage::Format_A2BGR30_Premultiplied:
6320 QPixelFormat(QPixelFormat::BGR,
6321 /*RED*/ 10,
6322 /*GREEN*/ 10,
6323 /*BLUE*/ 10,
6324 /*FOURTH*/ 0,
6325 /*FIFTH*/ 0,
6326 /*ALPHA*/ 2,
6327 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6328 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6329 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6330 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6331 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6332 //QImage::Format_RGB30:
6333 QPixelFormat(QPixelFormat::RGB,
6334 /*RED*/ 10,
6335 /*GREEN*/ 10,
6336 /*BLUE*/ 10,
6337 /*FOURTH*/ 0,
6338 /*FIFTH*/ 0,
6339 /*ALPHA*/ 2,
6340 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6341 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6342 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6343 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6344 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6345 //QImage::Format_A2RGB30_Premultiplied:
6346 QPixelFormat(QPixelFormat::RGB,
6347 /*RED*/ 10,
6348 /*GREEN*/ 10,
6349 /*BLUE*/ 10,
6350 /*FOURTH*/ 0,
6351 /*FIFTH*/ 0,
6352 /*ALPHA*/ 2,
6353 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6354 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6355 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6356 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6357 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6358 //QImage::Format_Alpha8:
6359 QPixelFormat(QPixelFormat::Alpha,
6360 /*First*/ 0,
6361 /*SECOND*/ 0,
6362 /*THIRD*/ 0,
6363 /*FOURTH*/ 0,
6364 /*FIFTH*/ 0,
6365 /*ALPHA*/ 8,
6366 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6367 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6368 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6369 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6370 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6371 //QImage::Format_Grayscale8:
6372 QPixelFormat(QPixelFormat::Grayscale,
6373 /*GRAY*/ 8,
6374 /*SECOND*/ 0,
6375 /*THIRD*/ 0,
6376 /*FOURTH*/ 0,
6377 /*FIFTH*/ 0,
6378 /*ALPHA*/ 0,
6379 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6380 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6381 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6382 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6383 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6384 //QImage::Format_RGBX64:
6385 QPixelFormat(QPixelFormat::RGB,
6386 /*RED*/ 16,
6387 /*GREEN*/ 16,
6388 /*BLUE*/ 16,
6389 /*FOURTH*/ 0,
6390 /*FIFTH*/ 0,
6391 /*ALPHA*/ 16,
6392 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6393 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6394 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6395 /*INTERPRETATION*/ QPixelFormat::UnsignedShort,
6396 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6397 //QImage::Format_RGBA64:
6398 QPixelFormat(QPixelFormat::RGB,
6399 /*RED*/ 16,
6400 /*GREEN*/ 16,
6401 /*BLUE*/ 16,
6402 /*FOURTH*/ 0,
6403 /*FIFTH*/ 0,
6404 /*ALPHA*/ 16,
6405 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6406 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6407 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6408 /*INTERPRETATION*/ QPixelFormat::UnsignedShort,
6409 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6410 //QImage::Format_RGBA64_Premultiplied:
6411 QPixelFormat(QPixelFormat::RGB,
6412 /*RED*/ 16,
6413 /*GREEN*/ 16,
6414 /*BLUE*/ 16,
6415 /*FOURTH*/ 0,
6416 /*FIFTH*/ 0,
6417 /*ALPHA*/ 16,
6418 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6419 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6420 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6421 /*INTERPRETATION*/ QPixelFormat::UnsignedShort,
6422 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6423 //QImage::Format_Grayscale16:
6424 QPixelFormat(QPixelFormat::Grayscale,
6425 /*GRAY*/ 16,
6426 /*SECOND*/ 0,
6427 /*THIRD*/ 0,
6428 /*FOURTH*/ 0,
6429 /*FIFTH*/ 0,
6430 /*ALPHA*/ 0,
6431 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6432 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6433 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6434 /*INTERPRETATION*/ QPixelFormat::UnsignedShort,
6435 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6436 //QImage::Format_BGR888:
6437 QPixelFormat(QPixelFormat::BGR,
6438 /*RED*/ 8,
6439 /*GREEN*/ 8,
6440 /*BLUE*/ 8,
6441 /*FOURTH*/ 0,
6442 /*FIFTH*/ 0,
6443 /*ALPHA*/ 0,
6444 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6445 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6446 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6447 /*INTERPRETATION*/ QPixelFormat::UnsignedByte,
6448 /*BYTE ORDER*/ QPixelFormat::BigEndian),
6449 //QImage::Format_RGBX16FPx4:
6450 QPixelFormat(QPixelFormat::RGB,
6451 /*RED*/ 16,
6452 /*GREEN*/ 16,
6453 /*BLUE*/ 16,
6454 /*FOURTH*/ 0,
6455 /*FIFTH*/ 0,
6456 /*ALPHA*/ 16,
6457 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6458 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6459 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6460 /*INTERPRETATION*/ QPixelFormat::FloatingPoint,
6461 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6462 //QImage::Format_RGBA16FPx4:
6463 QPixelFormat(QPixelFormat::RGB,
6464 /*RED*/ 16,
6465 /*GREEN*/ 16,
6466 /*BLUE*/ 16,
6467 /*FOURTH*/ 0,
6468 /*FIFTH*/ 0,
6469 /*ALPHA*/ 16,
6470 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6471 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6472 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6473 /*INTERPRETATION*/ QPixelFormat::FloatingPoint,
6474 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6475 //QImage::Format_RGBA16FPx4_Premultiplied:
6476 QPixelFormat(QPixelFormat::RGB,
6477 /*RED*/ 16,
6478 /*GREEN*/ 16,
6479 /*BLUE*/ 16,
6480 /*FOURTH*/ 0,
6481 /*FIFTH*/ 0,
6482 /*ALPHA*/ 16,
6483 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6484 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6485 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6486 /*INTERPRETATION*/ QPixelFormat::FloatingPoint,
6487 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6488 //QImage::Format_RGBX32FPx4:
6489 QPixelFormat(QPixelFormat::RGB,
6490 /*RED*/ 32,
6491 /*GREEN*/ 32,
6492 /*BLUE*/ 32,
6493 /*FOURTH*/ 0,
6494 /*FIFTH*/ 0,
6495 /*ALPHA*/ 32,
6496 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6497 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6498 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6499 /*INTERPRETATION*/ QPixelFormat::FloatingPoint,
6500 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6501 //QImage::Format_RGBA32FPx4:
6502 QPixelFormat(QPixelFormat::RGB,
6503 /*RED*/ 32,
6504 /*GREEN*/ 32,
6505 /*BLUE*/ 32,
6506 /*FOURTH*/ 0,
6507 /*FIFTH*/ 0,
6508 /*ALPHA*/ 32,
6509 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6510 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6511 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6512 /*INTERPRETATION*/ QPixelFormat::FloatingPoint,
6513 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6514 //QImage::Format_RGBA32FPx4_Premultiplied:
6515 QPixelFormat(QPixelFormat::RGB,
6516 /*RED*/ 32,
6517 /*GREEN*/ 32,
6518 /*BLUE*/ 32,
6519 /*FOURTH*/ 0,
6520 /*FIFTH*/ 0,
6521 /*ALPHA*/ 32,
6522 /*ALPHA USAGE*/ QPixelFormat::UsesAlpha,
6523 /*ALPHA POSITION*/ QPixelFormat::AtEnd,
6524 /*PREMULTIPLIED*/ QPixelFormat::Premultiplied,
6525 /*INTERPRETATION*/ QPixelFormat::FloatingPoint,
6526 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6527 //QImage::Format_CMYK8888:
6528 QPixelFormat(QPixelFormat::CMYK,
6529 /*RED*/ 8,
6530 /*GREEN*/ 8,
6531 /*BLUE*/ 8,
6532 /*FOURTH*/ 8,
6533 /*FIFTH*/ 0,
6534 /*ALPHA*/ 0,
6535 /*ALPHA USAGE*/ QPixelFormat::IgnoresAlpha,
6536 /*ALPHA POSITION*/ QPixelFormat::AtBeginning,
6537 /*PREMULTIPLIED*/ QPixelFormat::NotPremultiplied,
6538 /*INTERPRETATION*/ QPixelFormat::UnsignedInteger,
6539 /*BYTE ORDER*/ QPixelFormat::CurrentSystemEndian),
6540};
6541static_assert(sizeof(pixelformats) / sizeof(*pixelformats) == QImage::NImageFormats);
6542
6543/*!
6544 Returns the QImage::Format as a QPixelFormat
6545*/
6546QPixelFormat QImage::pixelFormat() const noexcept
6547{
6548 return toPixelFormat(format());
6549}
6550
6551/*!
6552 Converts \a format into a QPixelFormat
6553*/
6554QPixelFormat QImage::toPixelFormat(QImage::Format format) noexcept
6555{
6556 Q_ASSERT(static_cast<int>(format) < NImageFormats && static_cast<int>(format) >= 0);
6557 return pixelformats[format];
6558}
6559
6560/*!
6561 Converts \a format into a QImage::Format
6562*/
6563QImage::Format QImage::toImageFormat(QPixelFormat format) noexcept
6564{
6565 for (int i = 0; i < NImageFormats; i++) {
6566 if (format == pixelformats[i])
6567 return Format(i);
6568 }
6569 return Format_Invalid;
6570}
6571
6572static inline Qt::Orientations toOrientations(QImageIOHandler::Transformations orient)
6573{
6574 Qt::Orientations orients = {};
6575 if (orient.testFlag(QImageIOHandler::TransformationMirror))
6576 orients |= Qt::Horizontal;
6577 if (orient.testFlag(QImageIOHandler::TransformationFlip))
6578 orients |= Qt::Vertical;
6579 return orients;
6580}
6581
6582Q_GUI_EXPORT void qt_imageTransform(QImage &src, QImageIOHandler::Transformations orient)
6583{
6584 if (orient == QImageIOHandler::TransformationNone)
6585 return;
6586 if (orient == QImageIOHandler::TransformationRotate270) {
6587 src = rotated270(src);
6588 } else {
6589 src.flip(toOrientations(orient));
6590 if (orient & QImageIOHandler::TransformationRotate90)
6591 src = rotated90(src);
6592 }
6593}
6594
6595QMap<QString, QString> qt_getImageText(const QImage &image, const QString &description)
6596{
6597 QMap<QString, QString> text = qt_getImageTextFromDescription(description);
6598 const auto textKeys = image.textKeys();
6599 for (const QString &key : textKeys) {
6600 if (!key.isEmpty() && !text.contains(key))
6601 text.insert(key, image.text(key));
6602 }
6603 return text;
6604}
6605
6606QMap<QString, QString> qt_getImageTextFromDescription(const QString &description)
6607{
6608 QMap<QString, QString> text;
6609 for (const auto &pair : QStringView{description}.tokenize(u"\n\n")) {
6610 int index = pair.indexOf(u':');
6611 if (index >= 0 && pair.indexOf(u' ') < index) {
6612 if (!pair.trimmed().isEmpty())
6613 text.insert("Description"_L1, pair.toString().simplified());
6614 } else {
6615 const auto key = pair.left(index);
6616 if (!key.trimmed().isEmpty())
6617 text.insert(key.toString(), pair.mid(index + 2).toString().simplified());
6618 }
6619 }
6620 return text;
6621}
6622
6623QT_END_NAMESPACE
6624
6625#include "moc_qimage.cpp"
Definition qmap.h:295
Combined button and popup list for selecting options.
Q_TRACE_METADATA(qtcore, "ENUM { AUTO, RANGE User ... MaxUser } QEvent::Type;")
#define IWX_MSB(b)
Definition qimage.cpp:4482
static QImage rotated90(const QImage &src)
Definition qimage.cpp:4834
static void copyMetadata(QImage *dst, const QImage &src)
Definition qimage.cpp:1189
#define QT_XFORM_TYPE_LSBFIRST
Definition qimage.cpp:51
static void copyMetadata(QImageData *dst, const QImageData *src)
Definition qimage.cpp:1180
#define QT_XFORM_TYPE_MSBFIRST
Definition qimage.cpp:50
static int next_qimage_serial_number()
Definition qimage.cpp:90
#define QIMAGE_SANITYCHECK_MEMORY(image)
Definition qimage.cpp:68
static void copyPhysicalMetadata(QImageData *dst, const QImageData *src)
Definition qimage.cpp:1173
#define IWX_LSB(b)
Definition qimage.cpp:4491
static QImage rotated270(const QImage &src)
Definition qimage.cpp:4878
QMap< QString, QString > qt_getImageText(const QImage &image, const QString &description)
Definition qimage.cpp:6595
Q_GUI_EXPORT void qt_imageTransform(QImage &src, QImageIOHandler::Transformations orient)
Definition qimage.cpp:6582
#define PIX(x, y)
static QImage rotated180(const QImage &src)
Definition qimage.cpp:4860
static Qt::Orientations toOrientations(QImageIOHandler::Transformations orient)
Definition qimage.cpp:6572
QMap< QString, QString > qt_getImageTextFromDescription(const QString &description)
Definition qimage.cpp:6606