1/****************************************************************************
2**
3** Copyright (C) 2018 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtGui module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#include "qimage.h"
41
42#include "qbuffer.h"
43#include "qdatastream.h"
44#include "qcolortransform.h"
45#include "qmap.h"
46#include "qtransform.h"
47#include "qimagereader.h"
48#include "qimagewriter.h"
49#include "qstringlist.h"
50#include "qvariant.h"
51#include "qimagepixmapcleanuphooks_p.h"
52#include <qpa/qplatformintegration.h>
53#include <private/qguiapplication_p.h>
54#include <ctype.h>
55#include <stdlib.h>
56#include <limits.h>
57#include <qpa/qplatformpixmap.h>
58#include <private/qcolortransform_p.h>
59#include <private/qmemrotate_p.h>
60#include <private/qimagescale_p.h>
61#include <private/qpixellayout_p.h>
62#include <private/qsimd_p.h>
63
64#include <qhash.h>
65
66#include <private/qpaintengine_raster_p.h>
67
68#include <private/qimage_p.h>
69#include <private/qfont_p.h>
70
71#if QT_CONFIG(thread)
72#include "qsemaphore.h"
73#include "qthreadpool.h"
74#endif
75
76#include <qtgui_tracepoints_p.h>
77
78QT_BEGIN_NAMESPACE
79
80static inline bool isLocked(QImageData *data)
81{
82 return data != nullptr && data->is_locked;
83}
84
85#if defined(Q_CC_DEC) && defined(__alpha) && (__DECCXX_VER-0 >= 50190001)
86#pragma message disable narrowptr
87#endif
88
89
90#define QIMAGE_SANITYCHECK_MEMORY(image) \
91 if ((image).isNull()) { \
92 qWarning("QImage: out of memory, returning null image"); \
93 return QImage(); \
94 }
95
96
97static QImage rotated90(const QImage &src);
98static QImage rotated180(const QImage &src);
99static QImage rotated270(const QImage &src);
100
101static int next_qimage_serial_number()
102{
103 static QBasicAtomicInt serial = Q_BASIC_ATOMIC_INITIALIZER(0);
104 return 1 + serial.fetchAndAddRelaxed(1);
105}
106
107QImageData::QImageData()
108 : ref(0), width(0), height(0), depth(0), nbytes(0), devicePixelRatio(1.0), data(nullptr),
109 format(QImage::Format_ARGB32), bytes_per_line(0),
110 ser_no(next_qimage_serial_number()),
111 detach_no(0),
112 dpmx(qt_defaultDpiX() * 100 / qreal(2.54)),
113 dpmy(qt_defaultDpiY() * 100 / qreal(2.54)),
114 offset(0, 0), own_data(true), ro_data(false), has_alpha_clut(false),
115 is_cached(false), is_locked(false), cleanupFunction(nullptr), cleanupInfo(nullptr),
116 paintEngine(nullptr)
117{
118}
119
120/*! \fn QImageData * QImageData::create(const QSize &size, QImage::Format format)
121
122 \internal
123
124 Creates a new image data.
125 Returns \nullptr if invalid parameters are give or anything else failed.
126*/
127QImageData * QImageData::create(const QSize &size, QImage::Format format)
128{
129 if (size.isEmpty() || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
130 return nullptr; // invalid parameter(s)
131
132 Q_TRACE_SCOPE(QImageData_create, size, format);
133
134 int width = size.width();
135 int height = size.height();
136 int depth = qt_depthForFormat(format);
137 auto params = calculateImageParameters(width, height, depth);
138 if (!params.isValid())
139 return nullptr;
140
141 QScopedPointer<QImageData> d(new QImageData);
142
143 switch (format) {
144 case QImage::Format_Mono:
145 case QImage::Format_MonoLSB:
146 d->colortable.resize(2);
147 d->colortable[0] = QColor(Qt::black).rgba();
148 d->colortable[1] = QColor(Qt::white).rgba();
149 break;
150 default:
151 break;
152 }
153
154 d->width = width;
155 d->height = height;
156 d->depth = depth;
157 d->format = format;
158 d->has_alpha_clut = false;
159 d->is_cached = false;
160
161 d->bytes_per_line = params.bytesPerLine;
162 d->nbytes = params.totalSize;
163 d->data = (uchar *)malloc(d->nbytes);
164
165 if (!d->data)
166 return nullptr;
167
168 d->ref.ref();
169 return d.take();
170}
171
172QImageData::~QImageData()
173{
174 if (cleanupFunction)
175 cleanupFunction(cleanupInfo);
176 if (is_cached)
177 QImagePixmapCleanupHooks::executeImageHooks((((qint64) ser_no) << 32) | ((qint64) detach_no));
178 delete paintEngine;
179 if (data && own_data)
180 free(data);
181 data = nullptr;
182}
183
184#if defined(_M_ARM) && defined(_MSC_VER)
185#pragma optimize("", off)
186#endif
187
188bool QImageData::checkForAlphaPixels() const
189{
190 bool has_alpha_pixels = false;
191
192 switch (format) {
193
194 case QImage::Format_Mono:
195 case QImage::Format_MonoLSB:
196 case QImage::Format_Indexed8:
197 has_alpha_pixels = has_alpha_clut;
198 break;
199 case QImage::Format_Alpha8:
200 has_alpha_pixels = true;
201 break;
202 case QImage::Format_ARGB32:
203 case QImage::Format_ARGB32_Premultiplied: {
204 const uchar *bits = data;
205 for (int y=0; y<height && !has_alpha_pixels; ++y) {
206 uint alphaAnd = 0xff000000;
207 for (int x=0; x<width; ++x)
208 alphaAnd &= reinterpret_cast<const uint*>(bits)[x];
209 has_alpha_pixels = (alphaAnd != 0xff000000);
210 bits += bytes_per_line;
211 }
212 } break;
213
214 case QImage::Format_RGBA8888:
215 case QImage::Format_RGBA8888_Premultiplied: {
216 const uchar *bits = data;
217 for (int y=0; y<height && !has_alpha_pixels; ++y) {
218 uchar alphaAnd = 0xff;
219 for (int x=0; x<width; ++x)
220 alphaAnd &= bits[x * 4+ 3];
221 has_alpha_pixels = (alphaAnd != 0xff);
222 bits += bytes_per_line;
223 }
224 } break;
225
226 case QImage::Format_A2BGR30_Premultiplied:
227 case QImage::Format_A2RGB30_Premultiplied: {
228 const uchar *bits = data;
229 for (int y=0; y<height && !has_alpha_pixels; ++y) {
230 uint alphaAnd = 0xc0000000;
231 for (int x=0; x<width; ++x)
232 alphaAnd &= reinterpret_cast<const uint*>(bits)[x];
233 has_alpha_pixels = (alphaAnd != 0xc0000000);
234 bits += bytes_per_line;
235 }
236 } break;
237
238 case QImage::Format_ARGB8555_Premultiplied:
239 case QImage::Format_ARGB8565_Premultiplied: {
240 const uchar *bits = data;
241 const uchar *end_bits = data + bytes_per_line;
242
243 for (int y=0; y<height && !has_alpha_pixels; ++y) {
244 uchar alphaAnd = 0xff;
245 while (bits < end_bits) {
246 alphaAnd &= bits[0];
247 bits += 3;
248 }
249 has_alpha_pixels = (alphaAnd != 0xff);
250 bits = end_bits;
251 end_bits += bytes_per_line;
252 }
253 } break;
254
255 case QImage::Format_ARGB6666_Premultiplied: {
256 const uchar *bits = data;
257 const uchar *end_bits = data + bytes_per_line;
258
259 for (int y=0; y<height && !has_alpha_pixels; ++y) {
260 uchar alphaAnd = 0xfc;
261 while (bits < end_bits) {
262 alphaAnd &= bits[0];
263 bits += 3;
264 }
265 has_alpha_pixels = (alphaAnd != 0xfc);
266 bits = end_bits;
267 end_bits += bytes_per_line;
268 }
269 } break;
270
271 case QImage::Format_ARGB4444_Premultiplied: {
272 const uchar *bits = data;
273 for (int y=0; y<height && !has_alpha_pixels; ++y) {
274 ushort alphaAnd = 0xf000;
275 for (int x=0; x<width; ++x)
276 alphaAnd &= reinterpret_cast<const ushort*>(bits)[x];
277 has_alpha_pixels = (alphaAnd != 0xf000);
278 bits += bytes_per_line;
279 }
280 } break;
281 case QImage::Format_RGBA64:
282 case QImage::Format_RGBA64_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 |= !(((QRgba64 *)bits)[x].isOpaque());
287 }
288 bits += bytes_per_line;
289 }
290 } break;
291
292 case QImage::Format_RGB32:
293 case QImage::Format_RGB16:
294 case QImage::Format_RGB444:
295 case QImage::Format_RGB555:
296 case QImage::Format_RGB666:
297 case QImage::Format_RGB888:
298 case QImage::Format_BGR888:
299 case QImage::Format_RGBX8888:
300 case QImage::Format_BGR30:
301 case QImage::Format_RGB30:
302 case QImage::Format_Grayscale8:
303 case QImage::Format_Grayscale16:
304 case QImage::Format_RGBX64:
305 break;
306 case QImage::Format_Invalid:
307 case QImage::NImageFormats:
308 Q_UNREACHABLE();
309 break;
310 }
311
312 return has_alpha_pixels;
313}
314#if defined(_M_ARM) && defined(_MSC_VER)
315#pragma optimize("", on)
316#endif
317
318/*!
319 \class QImage
320
321 \inmodule QtGui
322 \ingroup painting
323 \ingroup shared
324
325 \reentrant
326
327 \brief The QImage class provides a hardware-independent image
328 representation that allows direct access to the pixel data, and
329 can be used as a paint device.
330
331 Qt provides four classes for handling image data: QImage, QPixmap,
332 QBitmap and QPicture. QImage is designed and optimized for I/O,
333 and for direct pixel access and manipulation, while QPixmap is
334 designed and optimized for showing images on screen. QBitmap is
335 only a convenience class that inherits QPixmap, ensuring a
336 depth of 1. Finally, the QPicture class is a paint device that
337 records and replays QPainter commands.
338
339 Because QImage is a QPaintDevice subclass, QPainter can be used to
340 draw directly onto images. When using QPainter on a QImage, the
341 painting can be performed in another thread than the current GUI
342 thread.
343
344 The QImage class supports several image formats described by the
345 \l Format enum. These include monochrome, 8-bit, 32-bit and
346 alpha-blended images which are available in all versions of Qt
347 4.x.
348
349 QImage provides a collection of functions that can be used to
350 obtain a variety of information about the image. There are also
351 several functions that enables transformation of the image.
352
353 QImage objects can be passed around by value since the QImage
354 class uses \l{Implicit Data Sharing}{implicit data
355 sharing}. QImage objects can also be streamed and compared.
356
357 \note If you would like to load QImage objects in a static build of Qt,
358 refer to the \l{How to Create Qt Plugins}{Plugin HowTo}.
359
360 \warning Painting on a QImage with the format
361 QImage::Format_Indexed8 is not supported.
362
363 \tableofcontents
364
365 \section1 Reading and Writing Image Files
366
367 QImage provides several ways of loading an image file: The file
368 can be loaded when constructing the QImage object, or by using the
369 load() or loadFromData() functions later on. QImage also provides
370 the static fromData() function, constructing a QImage from the
371 given data. When loading an image, the file name can either refer
372 to an actual file on disk or to one of the application's embedded
373 resources. See \l{The Qt Resource System} overview for details
374 on how to embed images and other resource files in the
375 application's executable.
376
377 Simply call the save() function to save a QImage object.
378
379 The complete list of supported file formats are available through
380 the QImageReader::supportedImageFormats() and
381 QImageWriter::supportedImageFormats() functions. New file formats
382 can be added as plugins. By default, Qt supports the following
383 formats:
384
385 \table
386 \header \li Format \li Description \li Qt's support
387 \row \li BMP \li Windows Bitmap \li Read/write
388 \row \li GIF \li Graphic Interchange Format (optional) \li Read
389 \row \li JPG \li Joint Photographic Experts Group \li Read/write
390 \row \li JPEG \li Joint Photographic Experts Group \li Read/write
391 \row \li PNG \li Portable Network Graphics \li Read/write
392 \row \li PBM \li Portable Bitmap \li Read
393 \row \li PGM \li Portable Graymap \li Read
394 \row \li PPM \li Portable Pixmap \li Read/write
395 \row \li XBM \li X11 Bitmap \li Read/write
396 \row \li XPM \li X11 Pixmap \li Read/write
397 \endtable
398
399 \section1 Image Information
400
401 QImage provides a collection of functions that can be used to
402 obtain a variety of information about the image:
403
404 \table
405 \header
406 \li \li Available Functions
407
408 \row
409 \li Geometry
410 \li
411
412 The size(), width(), height(), dotsPerMeterX(), and
413 dotsPerMeterY() functions provide information about the image size
414 and aspect ratio.
415
416 The rect() function returns the image's enclosing rectangle. The
417 valid() function tells if a given pair of coordinates is within
418 this rectangle. The offset() function returns the number of pixels
419 by which the image is intended to be offset by when positioned
420 relative to other images, which also can be manipulated using the
421 setOffset() function.
422
423 \row
424 \li Colors
425 \li
426
427 The color of a pixel can be retrieved by passing its coordinates
428 to the pixel() function. The pixel() function returns the color
429 as a QRgb value indepedent of the image's format.
430
431 In case of monochrome and 8-bit images, the colorCount() and
432 colorTable() functions provide information about the color
433 components used to store the image data: The colorTable() function
434 returns the image's entire color table. To obtain a single entry,
435 use the pixelIndex() function to retrieve the pixel index for a
436 given pair of coordinates, then use the color() function to
437 retrieve the color. Note that if you create an 8-bit image
438 manually, you have to set a valid color table on the image as
439 well.
440
441 The hasAlphaChannel() function tells if the image's format
442 respects the alpha channel, or not. The allGray() and
443 isGrayscale() functions tell whether an image's colors are all
444 shades of gray.
445
446 See also the \l {QImage#Pixel Manipulation}{Pixel Manipulation}
447 and \l {QImage#Image Transformations}{Image Transformations}
448 sections.
449
450 \row
451 \li Text
452 \li
453
454 The text() function returns the image text associated with the
455 given text key. An image's text keys can be retrieved using the
456 textKeys() function. Use the setText() function to alter an
457 image's text.
458
459 \row
460 \li Low-level information
461 \li
462
463 The depth() function returns the depth of the image. The supported
464 depths are 1 (monochrome), 8, 16, 24 and 32 bits. The
465 bitPlaneCount() function tells how many of those bits that are
466 used. For more information see the
467 \l {QImage#Image Formats}{Image Formats} section.
468
469 The format(), bytesPerLine(), and sizeInBytes() functions provide
470 low-level information about the data stored in the image.
471
472 The cacheKey() function returns a number that uniquely
473 identifies the contents of this QImage object.
474 \endtable
475
476 \section1 Pixel Manipulation
477
478 The functions used to manipulate an image's pixels depend on the
479 image format. The reason is that monochrome and 8-bit images are
480 index-based and use a color lookup table, while 32-bit images
481 store ARGB values directly. For more information on image formats,
482 see the \l {Image Formats} section.
483
484 In case of a 32-bit image, the setPixel() function can be used to
485 alter the color of the pixel at the given coordinates to any other
486 color specified as an ARGB quadruplet. To make a suitable QRgb
487 value, use the qRgb() (adding a default alpha component to the
488 given RGB values, i.e. creating an opaque color) or qRgba()
489 function. For example:
490
491 \table
492 \header
493 \li {2,1}32-bit
494 \row
495 \li \inlineimage qimage-32bit_scaled.png
496 \li
497 \snippet code/src_gui_image_qimage.cpp 0
498 \endtable
499
500 In case of a 8-bit and monchrome images, the pixel value is only
501 an index from the image's color table. So the setPixel() function
502 can only be used to alter the color of the pixel at the given
503 coordinates to a predefined color from the image's color table,
504 i.e. it can only change the pixel's index value. To alter or add a
505 color to an image's color table, use the setColor() function.
506
507 An entry in the color table is an ARGB quadruplet encoded as an
508 QRgb value. Use the qRgb() and qRgba() functions to make a
509 suitable QRgb value for use with the setColor() function. For
510 example:
511
512 \table
513 \header
514 \li {2,1} 8-bit
515 \row
516 \li \inlineimage qimage-8bit_scaled.png
517 \li
518 \snippet code/src_gui_image_qimage.cpp 1
519 \endtable
520
521 For images with more than 8-bit per color-channel. The methods
522 setPixelColor() and pixelColor() can be used to set and get
523 with QColor values.
524
525 QImage also provide the scanLine() function which returns a
526 pointer to the pixel data at the scanline with the given index,
527 and the bits() function which returns a pointer to the first pixel
528 data (this is equivalent to \c scanLine(0)).
529
530 \section1 Image Formats
531
532 Each pixel stored in a QImage is represented by an integer. The
533 size of the integer varies depending on the format. QImage
534 supports several image formats described by the \l Format
535 enum.
536
537 Monochrome images are stored using 1-bit indexes into a color table
538 with at most two colors. There are two different types of
539 monochrome images: big endian (MSB first) or little endian (LSB
540 first) bit order.
541
542 8-bit images are stored using 8-bit indexes into a color table,
543 i.e. they have a single byte per pixel. The color table is a
544 QList<QRgb>, and the QRgb typedef is equivalent to an unsigned
545 int containing an ARGB quadruplet on the format 0xAARRGGBB.
546
547 32-bit images have no color table; instead, each pixel contains an
548 QRgb value. There are three different types of 32-bit images
549 storing RGB (i.e. 0xffRRGGBB), ARGB and premultiplied ARGB
550 values respectively. In the premultiplied format the red, green,
551 and blue channels are multiplied by the alpha component divided by
552 255.
553
554 An image's format can be retrieved using the format()
555 function. Use the convertToFormat() functions to convert an image
556 into another format. The allGray() and isGrayscale() functions
557 tell whether a color image can safely be converted to a grayscale
558 image.
559
560 \section1 Image Transformations
561
562 QImage supports a number of functions for creating a new image
563 that is a transformed version of the original: The
564 createAlphaMask() function builds and returns a 1-bpp mask from
565 the alpha buffer in this image, and the createHeuristicMask()
566 function creates and returns a 1-bpp heuristic mask for this
567 image. The latter function works by selecting a color from one of
568 the corners, then chipping away pixels of that color starting at
569 all the edges.
570
571 The mirrored() function returns a mirror of the image in the
572 desired direction, the scaled() returns a copy of the image scaled
573 to a rectangle of the desired measures, and the rgbSwapped() function
574 constructs a BGR image from a RGB image.
575
576 The scaledToWidth() and scaledToHeight() functions return scaled
577 copies of the image.
578
579 The transformed() function returns a copy of the image that is
580 transformed with the given transformation matrix and
581 transformation mode: Internally, the transformation matrix is
582 adjusted to compensate for unwanted translation,
583 i.e. transformed() returns the smallest image containing all
584 transformed points of the original image. The static trueMatrix()
585 function returns the actual matrix used for transforming the
586 image.
587
588 There are also functions for changing attributes of an image
589 in-place:
590
591 \table
592 \header \li Function \li Description
593 \row
594 \li setDotsPerMeterX()
595 \li Defines the aspect ratio by setting the number of pixels that fit
596 horizontally in a physical meter.
597 \row
598 \li setDotsPerMeterY()
599 \li Defines the aspect ratio by setting the number of pixels that fit
600 vertically in a physical meter.
601 \row
602 \li fill()
603 \li Fills the entire image with the given pixel value.
604 \row
605 \li invertPixels()
606 \li Inverts all pixel values in the image using the given InvertMode value.
607 \row
608 \li setColorTable()
609 \li Sets the color table used to translate color indexes. Only
610 monochrome and 8-bit formats.
611 \row
612 \li setColorCount()
613 \li Resizes the color table. Only monochrome and 8-bit formats.
614
615 \endtable
616
617 \sa QImageReader, QImageWriter, QPixmap, QSvgRenderer, {Image Composition Example},
618 {Image Viewer Example}, {Scribble Example}, {Pixelator Example}
619*/
620
621/*!
622 \fn QImage::QImage(QImage &&other)
623
624 Move-constructs a QImage instance, making it point at the same
625 object that \a other was pointing to.
626
627 \since 5.2
628*/
629
630/*!
631 \fn QImage &QImage::operator=(QImage &&other)
632
633 Move-assigns \a other to this QImage instance.
634
635 \since 5.2
636*/
637
638/*!
639 \typedef QImageCleanupFunction
640 \relates QImage
641 \since 5.0
642
643 A function with the following signature that can be used to
644 implement basic image memory management:
645
646 \code
647 void myImageCleanupHandler(void *info);
648 \endcode
649*/
650
651/*!
652 \enum QImage::InvertMode
653
654 This enum type is used to describe how pixel values should be
655 inverted in the invertPixels() function.
656
657 \value InvertRgb Invert only the RGB values and leave the alpha
658 channel unchanged.
659
660 \value InvertRgba Invert all channels, including the alpha channel.
661
662 \sa invertPixels()
663*/
664
665/*!
666 \enum QImage::Format
667
668 The following image formats are available in Qt.
669 See the notes after the table.
670
671 \value Format_Invalid The image is invalid.
672 \value Format_Mono The image is stored using 1-bit per pixel. Bytes are
673 packed with the most significant bit (MSB) first.
674 \value Format_MonoLSB The image is stored using 1-bit per pixel. Bytes are
675 packed with the less significant bit (LSB) first.
676
677 \value Format_Indexed8 The image is stored using 8-bit indexes
678 into a colormap.
679
680 \value Format_RGB32 The image is stored using a 32-bit RGB format (0xffRRGGBB).
681
682 \value Format_ARGB32 The image is stored using a 32-bit ARGB
683 format (0xAARRGGBB).
684
685 \value Format_ARGB32_Premultiplied The image is stored using a premultiplied 32-bit
686 ARGB format (0xAARRGGBB), i.e. the red,
687 green, and blue channels are multiplied
688 by the alpha component divided by 255. (If RR, GG, or BB
689 has a higher value than the alpha channel, the results are
690 undefined.) Certain operations (such as image composition
691 using alpha blending) are faster using premultiplied ARGB32
692 than with plain ARGB32.
693
694 \value Format_RGB16 The image is stored using a 16-bit RGB format (5-6-5).
695
696 \value Format_ARGB8565_Premultiplied The image is stored using a
697 premultiplied 24-bit ARGB format (8-5-6-5).
698 \value Format_RGB666 The image is stored using a 24-bit RGB format (6-6-6).
699 The unused most significant bits is always zero.
700 \value Format_ARGB6666_Premultiplied The image is stored using a
701 premultiplied 24-bit ARGB format (6-6-6-6).
702 \value Format_RGB555 The image is stored using a 16-bit RGB format (5-5-5).
703 The unused most significant bit is always zero.
704 \value Format_ARGB8555_Premultiplied The image is stored using a
705 premultiplied 24-bit ARGB format (8-5-5-5).
706 \value Format_RGB888 The image is stored using a 24-bit RGB format (8-8-8).
707 \value Format_RGB444 The image is stored using a 16-bit RGB format (4-4-4).
708 The unused bits are always zero.
709 \value Format_ARGB4444_Premultiplied The image is stored using a
710 premultiplied 16-bit ARGB format (4-4-4-4).
711 \value Format_RGBX8888 The image is stored using a 32-bit byte-ordered RGB(x) format (8-8-8-8).
712 This is the same as the Format_RGBA8888 except alpha must always be 255. (added in Qt 5.2)
713 \value Format_RGBA8888 The image is stored using a 32-bit byte-ordered RGBA format (8-8-8-8).
714 Unlike ARGB32 this is a byte-ordered format, which means the 32bit
715 encoding differs between big endian and little endian architectures,
716 being respectively (0xRRGGBBAA) and (0xAABBGGRR). The order of the colors
717 is the same on any architecture if read as bytes 0xRR,0xGG,0xBB,0xAA. (added in Qt 5.2)
718 \value Format_RGBA8888_Premultiplied The image is stored using a
719 premultiplied 32-bit byte-ordered RGBA format (8-8-8-8). (added in Qt 5.2)
720 \value Format_BGR30 The image is stored using a 32-bit BGR format (x-10-10-10). (added in Qt 5.4)
721 \value Format_A2BGR30_Premultiplied The image is stored using a 32-bit premultiplied ABGR format (2-10-10-10). (added in Qt 5.4)
722 \value Format_RGB30 The image is stored using a 32-bit RGB format (x-10-10-10). (added in Qt 5.4)
723 \value Format_A2RGB30_Premultiplied The image is stored using a 32-bit premultiplied ARGB format (2-10-10-10). (added in Qt 5.4)
724 \value Format_Alpha8 The image is stored using an 8-bit alpha only format. (added in Qt 5.5)
725 \value Format_Grayscale8 The image is stored using an 8-bit grayscale format. (added in Qt 5.5)
726 \value Format_Grayscale16 The image is stored using an 16-bit grayscale format. (added in Qt 5.13)
727 \value Format_RGBX64 The image is stored using a 64-bit halfword-ordered RGB(x) format (16-16-16-16).
728 This is the same as the Format_RGBA64 except alpha must always be 65535. (added in Qt 5.12)
729 \value Format_RGBA64 The image is stored using a 64-bit halfword-ordered RGBA format (16-16-16-16). (added in Qt 5.12)
730 \value Format_RGBA64_Premultiplied The image is stored using a premultiplied 64-bit halfword-ordered
731 RGBA format (16-16-16-16). (added in Qt 5.12)
732 \value Format_BGR888 The image is stored using a 24-bit BGR format. (added in Qt 5.14)
733
734 \note Drawing into a QImage with QImage::Format_Indexed8 is not
735 supported.
736
737 \note Avoid most rendering directly to most of these formats using QPainter. Rendering
738 is best optimized to the \c Format_RGB32 and \c Format_ARGB32_Premultiplied formats, and secondarily for rendering to the
739 \c Format_RGB16, \c Format_RGBX8888, \c Format_RGBA8888_Premultiplied, \c Format_RGBX64 and \c Format_RGBA64_Premultiplied formats
740
741 \sa format(), convertToFormat()
742*/
743
744/*****************************************************************************
745 QImage member functions
746 *****************************************************************************/
747
748/*!
749 Constructs a null image.
750
751 \sa isNull()
752*/
753
754QImage::QImage() noexcept
755 : QPaintDevice()
756{
757 d = nullptr;
758}
759
760/*!
761 Constructs an image with the given \a width, \a height and \a
762 format.
763
764 A \l{isNull()}{null} image will be returned if memory cannot be allocated.
765
766 \warning This will create a QImage with uninitialized data. Call
767 fill() to fill the image with an appropriate pixel value before
768 drawing onto it with QPainter.
769*/
770QImage::QImage(int width, int height, Format format)
771 : QImage(QSize(width, height), format)
772{
773}
774
775/*!
776 Constructs an image with the given \a size and \a format.
777
778 A \l{isNull()}{null} image is returned if memory cannot be allocated.
779
780 \warning This will create a QImage with uninitialized data. Call
781 fill() to fill the image with an appropriate pixel value before
782 drawing onto it with QPainter.
783*/
784QImage::QImage(const QSize &size, Format format)
785 : QPaintDevice()
786{
787 d = QImageData::create(size, format);
788}
789
790
791
792QImageData *QImageData::create(uchar *data, int width, int height, qsizetype bpl, QImage::Format format, bool readOnly, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
793{
794 if (width <= 0 || height <= 0 || !data || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
795 return nullptr;
796
797 const int depth = qt_depthForFormat(format);
798 auto params = calculateImageParameters(width, height, depth);
799 if (!params.isValid())
800 return nullptr;
801
802 if (bpl > 0) {
803 // can't overflow, because has calculateImageParameters already done this multiplication
804 const qsizetype min_bytes_per_line = (qsizetype(width) * depth + 7)/8;
805 if (bpl < min_bytes_per_line)
806 return nullptr;
807
808 // recalculate the total with this value
809 params.bytesPerLine = bpl;
810 if (mul_overflow<qsizetype>(bpl, height, &params.totalSize))
811 return nullptr;
812 }
813
814 QImageData *d = new QImageData;
815 d->ref.ref();
816
817 d->own_data = false;
818 d->ro_data = readOnly;
819 d->data = data;
820 d->width = width;
821 d->height = height;
822 d->depth = depth;
823 d->format = format;
824
825 d->bytes_per_line = params.bytesPerLine;
826 d->nbytes = params.totalSize;
827
828 d->cleanupFunction = cleanupFunction;
829 d->cleanupInfo = cleanupInfo;
830
831 return d;
832}
833
834/*!
835 Constructs an image with the given \a width, \a height and \a
836 format, that uses an existing memory buffer, \a data. The \a width
837 and \a height must be specified in pixels, \a data must be 32-bit aligned,
838 and each scanline of data in the image must also be 32-bit aligned.
839
840 The buffer must remain valid throughout the life of the QImage and
841 all copies that have not been modified or otherwise detached from
842 the original buffer. The image does not delete the buffer at destruction.
843 You can provide a function pointer \a cleanupFunction along with an
844 extra pointer \a cleanupInfo that will be called when the last copy
845 is destroyed.
846
847 If \a format is an indexed color format, the image color table is
848 initially empty and must be sufficiently expanded with
849 setColorCount() or setColorTable() before the image is used.
850*/
851QImage::QImage(uchar* data, int width, int height, Format format, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
852 : QPaintDevice()
853{
854 d = QImageData::create(data, width, height, 0, format, false, cleanupFunction, cleanupInfo);
855}
856
857/*!
858 Constructs an image with the given \a width, \a height and \a
859 format, that uses an existing read-only memory buffer, \a
860 data. The \a width and \a height must be specified in pixels, \a
861 data must be 32-bit aligned, and each scanline of data in the
862 image must also be 32-bit aligned.
863
864 The buffer must remain valid throughout the life of the QImage and
865 all copies that have not been modified or otherwise detached from
866 the original buffer. The image does not delete the buffer at destruction.
867 You can provide a function pointer \a cleanupFunction along with an
868 extra pointer \a cleanupInfo that will be called when the last copy
869 is destroyed.
870
871 If \a format is an indexed color format, the image color table is
872 initially empty and must be sufficiently expanded with
873 setColorCount() or setColorTable() before the image is used.
874
875 Unlike the similar QImage constructor that takes a non-const data buffer,
876 this version will never alter the contents of the buffer. For example,
877 calling QImage::bits() will return a deep copy of the image, rather than
878 the buffer passed to the constructor. This allows for the efficiency of
879 constructing a QImage from raw data, without the possibility of the raw
880 data being changed.
881*/
882QImage::QImage(const uchar* data, int width, int height, Format format, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
883 : QPaintDevice()
884{
885 d = QImageData::create(const_cast<uchar*>(data), width, height, 0, format, true, cleanupFunction, cleanupInfo);
886}
887
888/*!
889 Constructs an image with the given \a width, \a height and \a
890 format, that uses an existing memory buffer, \a data. The \a width
891 and \a height must be specified in pixels. \a bytesPerLine
892 specifies the number of bytes per line (stride).
893
894 The buffer must remain valid throughout the life of the QImage and
895 all copies that have not been modified or otherwise detached from
896 the original buffer. The image does not delete the buffer at destruction.
897 You can provide a function pointer \a cleanupFunction along with an
898 extra pointer \a cleanupInfo that will be called when the last copy
899 is destroyed.
900
901 If \a format is an indexed color format, the image color table is
902 initially empty and must be sufficiently expanded with
903 setColorCount() or setColorTable() before the image is used.
904*/
905
906QImage::QImage(uchar *data, int width, int height, qsizetype bytesPerLine, Format format, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
907 :QPaintDevice()
908{
909 d = QImageData::create(data, width, height, bytesPerLine, format, false, cleanupFunction, cleanupInfo);
910}
911
912/*!
913 Constructs an image with the given \a width, \a height and \a
914 format, that uses an existing memory buffer, \a data. The \a width
915 and \a height must be specified in pixels. \a bytesPerLine
916 specifies the number of bytes per line (stride).
917
918 The buffer must remain valid throughout the life of the QImage and
919 all copies that have not been modified or otherwise detached from
920 the original buffer. The image does not delete the buffer at destruction.
921 You can provide a function pointer \a cleanupFunction along with an
922 extra pointer \a cleanupInfo that will be called when the last copy
923 is destroyed.
924
925 If \a format is an indexed color format, the image color table is
926 initially empty and must be sufficiently expanded with
927 setColorCount() or setColorTable() before the image is used.
928
929 Unlike the similar QImage constructor that takes a non-const data buffer,
930 this version will never alter the contents of the buffer. For example,
931 calling QImage::bits() will return a deep copy of the image, rather than
932 the buffer passed to the constructor. This allows for the efficiency of
933 constructing a QImage from raw data, without the possibility of the raw
934 data being changed.
935*/
936
937QImage::QImage(const uchar *data, int width, int height, qsizetype bytesPerLine, Format format, QImageCleanupFunction cleanupFunction, void *cleanupInfo)
938 :QPaintDevice()
939{
940 d = QImageData::create(const_cast<uchar*>(data), width, height, bytesPerLine, format, true, cleanupFunction, cleanupInfo);
941}
942
943/*!
944 Constructs an image and tries to load the image from the file with
945 the given \a fileName.
946
947 The loader attempts to read the image using the specified \a
948 format. If the \a format is not specified (which is the default),
949 it is auto-detected based on the file's suffix and header. For
950 details, see {QImageReader::setAutoDetectImageFormat()}{QImageReader}.
951
952 If the loading of the image failed, this object is a null image.
953
954 The file name can either refer to an actual file on disk or to one
955 of the application's embedded resources. See the
956 \l{resources.html}{Resource System} overview for details on how to
957 embed images and other resource files in the application's
958 executable.
959
960 \sa isNull(), {QImage#Reading and Writing Image Files}{Reading and Writing Image Files}
961*/
962
963QImage::QImage(const QString &fileName, const char *format)
964 : QPaintDevice()
965{
966 d = nullptr;
967 load(fileName, format);
968}
969
970#ifndef QT_NO_IMAGEFORMAT_XPM
971extern bool qt_read_xpm_image_or_array(QIODevice *device, const char * const *source, QImage &image);
972
973/*!
974 Constructs an image from the given \a xpm image.
975
976 Make sure that the image is a valid XPM image. Errors are silently
977 ignored.
978
979 Note that it's possible to squeeze the XPM variable a little bit
980 by using an unusual declaration:
981
982 \snippet code/src_gui_image_qimage.cpp 2
983
984 The extra \c const makes the entire definition read-only, which is
985 slightly more efficient (e.g., when the code is in a shared
986 library) and able to be stored in ROM with the application.
987*/
988
989QImage::QImage(const char * const xpm[])
990 : QPaintDevice()
991{
992 d = nullptr;
993 if (!xpm)
994 return;
995 if (!qt_read_xpm_image_or_array(nullptr, xpm, *this))
996 // Issue: Warning because the constructor may be ambigious
997 qWarning("QImage::QImage(), XPM is not supported");
998}
999#endif // QT_NO_IMAGEFORMAT_XPM
1000
1001/*!
1002 Constructs a shallow copy of the given \a image.
1003
1004 For more information about shallow copies, see the \l {Implicit
1005 Data Sharing} documentation.
1006
1007 \sa copy()
1008*/
1009
1010QImage::QImage(const QImage &image)
1011 : QPaintDevice()
1012{
1013 if (image.paintingActive() || isLocked(image.d)) {
1014 d = nullptr;
1015 image.copy().swap(*this);
1016 } else {
1017 d = image.d;
1018 if (d)
1019 d->ref.ref();
1020 }
1021}
1022
1023/*!
1024 Destroys the image and cleans up.
1025*/
1026
1027QImage::~QImage()
1028{
1029 if (d && !d->ref.deref())
1030 delete d;
1031}
1032
1033/*!
1034 Assigns a shallow copy of the given \a image to this image and
1035 returns a reference to this image.
1036
1037 For more information about shallow copies, see the \l {Implicit
1038 Data Sharing} documentation.
1039
1040 \sa copy(), QImage()
1041*/
1042
1043QImage &QImage::operator=(const QImage &image)
1044{
1045 if (image.paintingActive() || isLocked(image.d)) {
1046 operator=(image.copy());
1047 } else {
1048 if (image.d)
1049 image.d->ref.ref();
1050 if (d && !d->ref.deref())
1051 delete d;
1052 d = image.d;
1053 }
1054 return *this;
1055}
1056
1057/*!
1058 \fn void QImage::swap(QImage &other)
1059 \since 4.8
1060
1061 Swaps image \a other with this image. This operation is very
1062 fast and never fails.
1063*/
1064
1065/*!
1066 \internal
1067*/
1068int QImage::devType() const
1069{
1070 return QInternal::Image;
1071}
1072
1073/*!
1074 Returns the image as a QVariant.
1075*/
1076QImage::operator QVariant() const
1077{
1078 return QVariant::fromValue(*this);
1079}
1080
1081/*!
1082 \internal
1083
1084 If multiple images share common data, this image makes a copy of
1085 the data and detaches itself from the sharing mechanism, making
1086 sure that this image is the only one referring to the data.
1087
1088 Nothing is done if there is just a single reference.
1089
1090 \sa copy(), {QImage::isDetached()}{isDetached()}, {Implicit Data Sharing}
1091*/
1092void QImage::detach()
1093{
1094 if (d) {
1095 if (d->is_cached && d->ref.loadRelaxed() == 1)
1096 QImagePixmapCleanupHooks::executeImageHooks(cacheKey());
1097
1098 if (d->ref.loadRelaxed() != 1 || d->ro_data)
1099 *this = copy();
1100
1101 if (d)
1102 ++d->detach_no;
1103 }
1104}
1105
1106
1107static void copyPhysicalMetadata(QImageData *dst, const QImageData *src)
1108{
1109 dst->dpmx = src->dpmx;
1110 dst->dpmy = src->dpmy;
1111 dst->devicePixelRatio = src->devicePixelRatio;
1112}
1113
1114static void copyMetadata(QImageData *dst, const QImageData *src)
1115{
1116 // Doesn't copy colortable and alpha_clut, or offset.
1117 copyPhysicalMetadata(dst, src);
1118 dst->text = src->text;
1119 dst->colorSpace = src->colorSpace;
1120}
1121
1122static void copyMetadata(QImage *dst, const QImage &src)
1123{
1124 dst->setDotsPerMeterX(src.dotsPerMeterX());
1125 dst->setDotsPerMeterY(src.dotsPerMeterY());
1126 dst->setDevicePixelRatio(src.devicePixelRatio());
1127 const auto textKeys = src.textKeys();
1128 for (const auto &key: textKeys)
1129 dst->setText(key, src.text(key));
1130
1131}
1132
1133/*!
1134 \fn QImage QImage::copy(int x, int y, int width, int height) const
1135 \overload
1136
1137 The returned image is copied from the position (\a x, \a y) in
1138 this image, and will always have the given \a width and \a height.
1139 In areas beyond this image, pixels are set to 0.
1140
1141*/
1142
1143/*!
1144 \fn QImage QImage::copy(const QRect& rectangle) const
1145
1146 Returns a sub-area of the image as a new image.
1147
1148 The returned image is copied from the position (\a
1149 {rectangle}.x(), \a{rectangle}.y()) in this image, and will always
1150 have the size of the given \a rectangle.
1151
1152 In areas beyond this image, pixels are set to 0. For 32-bit RGB
1153 images, this means black; for 32-bit ARGB images, this means
1154 transparent black; for 8-bit images, this means the color with
1155 index 0 in the color table which can be anything; for 1-bit
1156 images, this means Qt::color0.
1157
1158 If the given \a rectangle is a null rectangle the entire image is
1159 copied.
1160
1161 \sa QImage()
1162*/
1163QImage QImage::copy(const QRect& r) const
1164{
1165 Q_TRACE_SCOPE(QImage_copy, r);
1166 if (!d)
1167 return QImage();
1168
1169 if (r.isNull()) {
1170 QImage image(d->width, d->height, d->format);
1171 if (image.isNull())
1172 return image;
1173
1174 // Qt for Embedded Linux can create images with non-default bpl
1175 // make sure we don't crash.
1176 if (image.d->nbytes != d->nbytes) {
1177 qsizetype bpl = qMin(bytesPerLine(), image.bytesPerLine());
1178 for (int i = 0; i < height(); i++)
1179 memcpy(image.scanLine(i), scanLine(i), bpl);
1180 } else
1181 memcpy(image.bits(), bits(), d->nbytes);
1182 image.d->colortable = d->colortable;
1183 image.d->offset = d->offset;
1184 image.d->has_alpha_clut = d->has_alpha_clut;
1185 copyMetadata(image.d, d);
1186 return image;
1187 }
1188
1189 int x = r.x();
1190 int y = r.y();
1191 int w = r.width();
1192 int h = r.height();
1193
1194 int dx = 0;
1195 int dy = 0;
1196 if (w <= 0 || h <= 0)
1197 return QImage();
1198
1199 QImage image(w, h, d->format);
1200 if (image.isNull())
1201 return image;
1202
1203 if (x < 0 || y < 0 || x + w > d->width || y + h > d->height) {
1204 // bitBlt will not cover entire image - clear it.
1205 image.fill(0);
1206 if (x < 0) {
1207 dx = -x;
1208 x = 0;
1209 }
1210 if (y < 0) {
1211 dy = -y;
1212 y = 0;
1213 }
1214 }
1215
1216 image.d->colortable = d->colortable;
1217
1218 int pixels_to_copy = qMax(w - dx, 0);
1219 if (x > d->width)
1220 pixels_to_copy = 0;
1221 else if (pixels_to_copy > d->width - x)
1222 pixels_to_copy = d->width - x;
1223 int lines_to_copy = qMax(h - dy, 0);
1224 if (y > d->height)
1225 lines_to_copy = 0;
1226 else if (lines_to_copy > d->height - y)
1227 lines_to_copy = d->height - y;
1228
1229 bool byteAligned = true;
1230 if (d->format == Format_Mono || d->format == Format_MonoLSB)
1231 byteAligned = !(dx & 7) && !(x & 7) && !(pixels_to_copy & 7);
1232
1233 if (byteAligned) {
1234 const uchar *src = d->data + ((x * d->depth) >> 3) + y * d->bytes_per_line;
1235 uchar *dest = image.d->data + ((dx * d->depth) >> 3) + dy * image.d->bytes_per_line;
1236 const qsizetype bytes_to_copy = (qsizetype(pixels_to_copy) * d->depth) >> 3;
1237 for (int i = 0; i < lines_to_copy; ++i) {
1238 memcpy(dest, src, bytes_to_copy);
1239 src += d->bytes_per_line;
1240 dest += image.d->bytes_per_line;
1241 }
1242 } else if (d->format == Format_Mono) {
1243 const uchar *src = d->data + y * d->bytes_per_line;
1244 uchar *dest = image.d->data + dy * image.d->bytes_per_line;
1245 for (int i = 0; i < lines_to_copy; ++i) {
1246 for (int j = 0; j < pixels_to_copy; ++j) {
1247 if (src[(x + j) >> 3] & (0x80 >> ((x + j) & 7)))
1248 dest[(dx + j) >> 3] |= (0x80 >> ((dx + j) & 7));
1249 else
1250 dest[(dx + j) >> 3] &= ~(0x80 >> ((dx + j) & 7));
1251 }
1252 src += d->bytes_per_line;
1253 dest += image.d->bytes_per_line;
1254 }
1255 } else { // Format_MonoLSB
1256 Q_ASSERT(d->format == Format_MonoLSB);
1257 const uchar *src = d->data + y * d->bytes_per_line;
1258 uchar *dest = image.d->data + dy * image.d->bytes_per_line;
1259 for (int i = 0; i < lines_to_copy; ++i) {
1260 for (int j = 0; j < pixels_to_copy; ++j) {
1261 if (src[(x + j) >> 3] & (0x1 << ((x + j) & 7)))
1262 dest[(dx + j) >> 3] |= (0x1 << ((dx + j) & 7));
1263 else
1264 dest[(dx + j) >> 3] &= ~(0x1 << ((dx + j) & 7));
1265 }
1266 src += d->bytes_per_line;
1267 dest += image.d->bytes_per_line;
1268 }
1269 }
1270
1271 copyMetadata(image.d, d);
1272 image.d->offset = offset();
1273 image.d->has_alpha_clut = d->has_alpha_clut;
1274 return image;
1275}
1276
1277
1278/*!
1279 \fn bool QImage::isNull() const
1280
1281 Returns \c true if it is a null image, otherwise returns \c false.
1282
1283 A null image has all parameters set to zero and no allocated data.
1284*/
1285bool QImage::isNull() const
1286{
1287 return !d;
1288}
1289
1290/*!
1291 \fn int QImage::width() const
1292
1293 Returns the width of the image.
1294
1295 \sa {QImage#Image Information}{Image Information}
1296*/
1297int QImage::width() const
1298{
1299 return d ? d->width : 0;
1300}
1301
1302/*!
1303 \fn int QImage::height() const
1304
1305 Returns the height of the image.
1306
1307 \sa {QImage#Image Information}{Image Information}
1308*/
1309int QImage::height() const
1310{
1311 return d ? d->height : 0;
1312}
1313
1314/*!
1315 \fn QSize QImage::size() const
1316
1317 Returns the size of the image, i.e. its width() and height().
1318
1319 \sa {QImage#Image Information}{Image Information}, deviceIndependentSize()
1320*/
1321QSize QImage::size() const
1322{
1323 return d ? QSize(d->width, d->height) : QSize(0, 0);
1324}
1325
1326/*!
1327 \fn QRect QImage::rect() const
1328
1329 Returns the enclosing rectangle (0, 0, width(), height()) of the
1330 image.
1331
1332 \sa {QImage#Image Information}{Image Information}
1333*/
1334QRect QImage::rect() const
1335{
1336 return d ? QRect(0, 0, d->width, d->height) : QRect();
1337}
1338
1339/*!
1340 Returns the depth of the image.
1341
1342 The image depth is the number of bits used to store a single
1343 pixel, also called bits per pixel (bpp).
1344
1345 The supported depths are 1, 8, 16, 24, 32 and 64.
1346
1347 \sa bitPlaneCount(), convertToFormat(), {QImage#Image Formats}{Image Formats},
1348 {QImage#Image Information}{Image Information}
1349
1350*/
1351int QImage::depth() const
1352{
1353 return d ? d->depth : 0;
1354}
1355
1356/*!
1357 \since 4.6
1358 \fn int QImage::colorCount() const
1359
1360 Returns the size of the color table for the image.
1361
1362 Notice that colorCount() returns 0 for 32-bpp images because these
1363 images do not use color tables, but instead encode pixel values as
1364 ARGB quadruplets.
1365
1366 \sa setColorCount(), {QImage#Image Information}{Image Information}
1367*/
1368int QImage::colorCount() const
1369{
1370 return d ? d->colortable.size() : 0;
1371}
1372
1373/*!
1374 Sets the color table used to translate color indexes to QRgb
1375 values, to the specified \a colors.
1376
1377 When the image is used, the color table must be large enough to
1378 have entries for all the pixel/index values present in the image,
1379 otherwise the results are undefined.
1380
1381 \sa colorTable(), setColor(), {QImage#Image Transformations}{Image
1382 Transformations}
1383*/
1384void QImage::setColorTable(const QList<QRgb> &colors)
1385{
1386 if (!d)
1387 return;
1388 detach();
1389
1390 // In case detach() ran out of memory
1391 if (!d)
1392 return;
1393
1394 d->colortable = colors;
1395 d->has_alpha_clut = false;
1396 for (int i = 0; i < d->colortable.size(); ++i) {
1397 if (qAlpha(d->colortable.at(i)) != 255) {
1398 d->has_alpha_clut = true;
1399 break;
1400 }
1401 }
1402}
1403
1404/*!
1405 Returns a list of the colors contained in the image's color table,
1406 or an empty list if the image does not have a color table
1407
1408 \sa setColorTable(), colorCount(), color()
1409*/
1410QList<QRgb> QImage::colorTable() const
1411{
1412 return d ? d->colortable : QList<QRgb>();
1413}
1414
1415/*!
1416 Returns the device pixel ratio for the image. This is the
1417 ratio between \e{device pixels} and \e{device independent pixels}.
1418
1419 Use this function when calculating layout geometry based on
1420 the image size: QSize layoutSize = image.size() / image.devicePixelRatio()
1421
1422 The default value is 1.0.
1423
1424 \sa setDevicePixelRatio(), QImageReader
1425*/
1426qreal QImage::devicePixelRatio() const
1427{
1428 if (!d)
1429 return 1.0;
1430 return d->devicePixelRatio;
1431}
1432
1433/*!
1434 Sets the device pixel ratio for the image. This is the
1435 ratio between image pixels and device-independent pixels.
1436
1437 The default \a scaleFactor is 1.0. Setting it to something else has
1438 two effects:
1439
1440 QPainters that are opened on the image will be scaled. For
1441 example, painting on a 200x200 image if with a ratio of 2.0
1442 will result in effective (device-independent) painting bounds
1443 of 100x100.
1444
1445 Code paths in Qt that calculate layout geometry based on the
1446 image size will take the ratio into account:
1447 QSize layoutSize = image.size() / image.devicePixelRatio()
1448 The net effect of this is that the image is displayed as
1449 high-DPI image rather than a large image
1450 (see \l{Drawing High Resolution Versions of Pixmaps and Images}).
1451
1452 \sa devicePixelRatio(), deviceIndependentSize()
1453*/
1454void QImage::setDevicePixelRatio(qreal scaleFactor)
1455{
1456 if (!d)
1457 return;
1458
1459 if (scaleFactor == d->devicePixelRatio)
1460 return;
1461
1462 detach();
1463 if (d)
1464 d->devicePixelRatio = scaleFactor;
1465}
1466
1467/*!
1468 Returns the size of the pixmap in device independent pixels.
1469
1470 This value should be used when using the pixmap size in user interface
1471 size calculations.
1472
1473 The return value is equivalent to pixmap.size() / pixmap.devicePixelRatio(),
1474*/
1475QSizeF QImage::deviceIndependentSize() const
1476{
1477 if (!d)
1478 return QSizeF(0, 0);
1479 return QSizeF(d->width, d->height) / d->devicePixelRatio;
1480}
1481
1482
1483/*!
1484 \since 5.10
1485 Returns the image data size in bytes.
1486
1487 \sa bytesPerLine(), bits(), {QImage#Image Information}{Image
1488 Information}
1489*/
1490qsizetype QImage::sizeInBytes() const
1491{
1492 return d ? d->nbytes : 0;
1493}
1494
1495/*!
1496 Returns the number of bytes per image scanline.
1497
1498 This is equivalent to sizeInBytes() / height() if height() is non-zero.
1499
1500 \sa scanLine()
1501*/
1502qsizetype QImage::bytesPerLine() const
1503{
1504 return d ? d->bytes_per_line : 0;
1505}
1506
1507
1508/*!
1509 Returns the color in the color table at index \a i. The first
1510 color is at index 0.
1511
1512 The colors in an image's color table are specified as ARGB
1513 quadruplets (QRgb). Use the qAlpha(), qRed(), qGreen(), and
1514 qBlue() functions to get the color value components.
1515
1516 \sa setColor(), pixelIndex(), {QImage#Pixel Manipulation}{Pixel
1517 Manipulation}
1518*/
1519QRgb QImage::color(int i) const
1520{
1521 Q_ASSERT(i < colorCount());
1522 return d ? d->colortable.at(i) : QRgb(uint(-1));
1523}
1524
1525/*!
1526 \fn void QImage::setColor(int index, QRgb colorValue)
1527
1528 Sets the color at the given \a index in the color table, to the
1529 given to \a colorValue. The color value is an ARGB quadruplet.
1530
1531 If \a index is outside the current size of the color table, it is
1532 expanded with setColorCount().
1533
1534 \sa color(), colorCount(), setColorTable(), {QImage#Pixel Manipulation}{Pixel
1535 Manipulation}
1536*/
1537void QImage::setColor(int i, QRgb c)
1538{
1539 if (!d)
1540 return;
1541 if (i < 0 || d->depth > 8 || i >= 1<<d->depth) {
1542 qWarning("QImage::setColor: Index out of bound %d", i);
1543 return;
1544 }
1545 detach();
1546
1547 // In case detach() run out of memory
1548 if (!d)
1549 return;
1550
1551 if (i >= d->colortable.size())
1552 setColorCount(i+1);
1553 d->colortable[i] = c;
1554 d->has_alpha_clut |= (qAlpha(c) != 255);
1555}
1556
1557/*!
1558 Returns a pointer to the pixel data at the scanline with index \a
1559 i. The first scanline is at index 0.
1560
1561 The scanline data is as minimum 32-bit aligned. For 64-bit formats
1562 it follows the native alignment of 64-bit integers (64-bit for most
1563 platforms, but notably 32-bit on i386).
1564
1565 For example, to remove the green component of each pixel in an image:
1566
1567 \snippet code/src_gui_image_qimage.cpp scanLine
1568
1569 \warning If you are accessing 32-bpp image data, cast the returned
1570 pointer to \c{QRgb*} (QRgb has a 32-bit size) and use it to
1571 read/write the pixel value. You cannot use the \c{uchar*} pointer
1572 directly, because the pixel format depends on the byte order on
1573 the underlying platform. Use qRed(), qGreen(), qBlue(), and
1574 qAlpha() to access the pixels.
1575
1576 \sa bytesPerLine(), bits(), {QImage#Pixel Manipulation}{Pixel
1577 Manipulation}, constScanLine()
1578*/
1579uchar *QImage::scanLine(int i)
1580{
1581 if (!d)
1582 return nullptr;
1583
1584 detach();
1585
1586 // In case detach() ran out of memory
1587 if (!d)
1588 return nullptr;
1589
1590 return d->data + i * d->bytes_per_line;
1591}
1592
1593/*!
1594 \overload
1595*/
1596const uchar *QImage::scanLine(int i) const
1597{
1598 if (!d)
1599 return nullptr;
1600
1601 Q_ASSERT(i >= 0 && i < height());
1602 return d->data + i * d->bytes_per_line;
1603}
1604
1605
1606/*!
1607 Returns a pointer to the pixel data at the scanline with index \a
1608 i. The first scanline is at index 0.
1609
1610 The scanline data is as minimum 32-bit aligned. For 64-bit formats
1611 it follows the native alignment of 64-bit integers (64-bit for most
1612 platforms, but notably 32-bit on i386).
1613
1614 Note that QImage uses \l{Implicit Data Sharing} {implicit data
1615 sharing}, but this function does \e not perform a deep copy of the
1616 shared pixel data, because the returned data is const.
1617
1618 \sa scanLine(), constBits()
1619 \since 4.7
1620*/
1621const uchar *QImage::constScanLine(int i) const
1622{
1623 if (!d)
1624 return nullptr;
1625
1626 Q_ASSERT(i >= 0 && i < height());
1627 return d->data + i * d->bytes_per_line;
1628}
1629
1630/*!
1631 Returns a pointer to the first pixel data. This is equivalent to
1632 scanLine(0).
1633
1634 Note that QImage uses \l{Implicit Data Sharing} {implicit data
1635 sharing}. This function performs a deep copy of the shared pixel
1636 data, thus ensuring that this QImage is the only one using the
1637 current return value.
1638
1639 \sa scanLine(), sizeInBytes(), constBits()
1640*/
1641uchar *QImage::bits()
1642{
1643 if (!d)
1644 return nullptr;
1645 detach();
1646
1647 // In case detach ran out of memory...
1648 if (!d)
1649 return nullptr;
1650
1651 return d->data;
1652}
1653
1654/*!
1655 \overload
1656
1657 Note that QImage uses \l{Implicit Data Sharing} {implicit data
1658 sharing}, but this function does \e not perform a deep copy of the
1659 shared pixel data, because the returned data is const.
1660*/
1661const uchar *QImage::bits() const
1662{
1663 return d ? d->data : nullptr;
1664}
1665
1666
1667/*!
1668 Returns a pointer to the first pixel data.
1669
1670 Note that QImage uses \l{Implicit Data Sharing} {implicit data
1671 sharing}, but this function does \e not perform a deep copy of the
1672 shared pixel data, because the returned data is const.
1673
1674 \sa bits(), constScanLine()
1675 \since 4.7
1676*/
1677const uchar *QImage::constBits() const
1678{
1679 return d ? d->data : nullptr;
1680}
1681
1682/*!
1683 \fn void QImage::fill(uint pixelValue)
1684
1685 Fills the entire image with the given \a pixelValue.
1686
1687 If the depth of this image is 1, only the lowest bit is used. If
1688 you say fill(0), fill(2), etc., the image is filled with 0s. If
1689 you say fill(1), fill(3), etc., the image is filled with 1s. If
1690 the depth is 8, the lowest 8 bits are used and if the depth is 16
1691 the lowest 16 bits are used.
1692
1693 If the image depth is higher than 32bit the result is undefined.
1694
1695 \note There are no corresponding value getter, though QImage::pixelIndex()
1696 will return the same value for indexed formats, and QImage::pixel() for
1697 RGB32, ARGB32, and ARGB32PM formats.
1698
1699 \sa depth(), {QImage#Image Transformations}{Image Transformations}
1700*/
1701
1702void QImage::fill(uint pixel)
1703{
1704 if (!d)
1705 return;
1706
1707 detach();
1708
1709 // In case detach() ran out of memory
1710 if (!d)
1711 return;
1712
1713 if (d->depth == 1 || d->depth == 8) {
1714 int w = d->width;
1715 if (d->depth == 1) {
1716 if (pixel & 1)
1717 pixel = 0xffffffff;
1718 else
1719 pixel = 0;
1720 w = (w + 7) / 8;
1721 } else {
1722 pixel &= 0xff;
1723 }
1724 qt_rectfill<quint8>(d->data, pixel, 0, 0,
1725 w, d->height, d->bytes_per_line);
1726 return;
1727 } else if (d->depth == 16) {
1728 if (d->format == Format_RGB444)
1729 pixel |= 0xf000;
1730 qt_rectfill<quint16>(reinterpret_cast<quint16*>(d->data), pixel,
1731 0, 0, d->width, d->height, d->bytes_per_line);
1732 return;
1733 } else if (d->depth == 24) {
1734 if (d->format == Format_RGB666)
1735 pixel |= 0xfc0000;
1736 qt_rectfill<quint24>(reinterpret_cast<quint24*>(d->data), pixel,
1737 0, 0, d->width, d->height, d->bytes_per_line);
1738 return;
1739 } else if (d->depth == 64) {
1740 qt_rectfill<quint64>(reinterpret_cast<quint64*>(d->data), QRgba64::fromArgb32(pixel),
1741 0, 0, d->width, d->height, d->bytes_per_line);
1742 return;
1743 }
1744
1745 if (d->format == Format_RGB32)
1746 pixel |= 0xff000000;
1747 if (d->format == Format_RGBX8888)
1748#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
1749 pixel |= 0xff000000;
1750#else
1751 pixel |= 0x000000ff;
1752#endif
1753 if (d->format == Format_BGR30 || d->format == Format_RGB30)
1754 pixel |= 0xc0000000;
1755
1756 qt_rectfill<uint>(reinterpret_cast<uint*>(d->data), pixel,
1757 0, 0, d->width, d->height, d->bytes_per_line);
1758}
1759
1760
1761/*!
1762 \fn void QImage::fill(Qt::GlobalColor color)
1763 \overload
1764 \since 4.8
1765
1766 Fills the image with the given \a color, described as a standard global
1767 color.
1768 */
1769
1770void QImage::fill(Qt::GlobalColor color)
1771{
1772 fill(QColor(color));
1773}
1774
1775
1776
1777/*!
1778 \fn void QImage::fill(const QColor &color)
1779
1780 \overload
1781
1782 Fills the entire image with the given \a color.
1783
1784 If the depth of the image is 1, the image will be filled with 1 if
1785 \a color equals Qt::color1; it will otherwise be filled with 0.
1786
1787 If the depth of the image is 8, the image will be filled with the
1788 index corresponding the \a color in the color table if present; it
1789 will otherwise be filled with 0.
1790
1791 \since 4.8
1792*/
1793
1794void QImage::fill(const QColor &color)
1795{
1796 if (!d)
1797 return;
1798 detach();
1799
1800 // In case we run out of memory
1801 if (!d)
1802 return;
1803
1804 QRgba64 opaque = color.rgba64();
1805 opaque.setAlpha(65535);
1806 switch (d->format) {
1807 case QImage::Format_RGB32:
1808 case QImage::Format_ARGB32:
1809 fill(color.rgba());
1810 break;
1811 case QImage::Format_ARGB32_Premultiplied:
1812 fill(qPremultiply(color.rgba()));
1813 break;
1814 case QImage::Format_RGBX8888:
1815 fill(ARGB2RGBA(color.rgba() | 0xff000000));
1816 break;
1817 case QImage::Format_RGBA8888:
1818 fill(ARGB2RGBA(color.rgba()));
1819 break;
1820 case QImage::Format_RGBA8888_Premultiplied:
1821 fill(ARGB2RGBA(qPremultiply(color.rgba())));
1822 break;
1823 case QImage::Format_BGR30:
1824 fill(qConvertRgb64ToRgb30<PixelOrderBGR>(opaque));
1825 break;
1826 case QImage::Format_RGB30:
1827 fill(qConvertRgb64ToRgb30<PixelOrderRGB>(opaque));
1828 break;
1829 case QImage::Format_RGB16:
1830 fill((uint) qConvertRgb32To16(color.rgba()));
1831 break;
1832 case QImage::Format_Indexed8: {
1833 uint pixel = 0;
1834 for (int i=0; i<d->colortable.size(); ++i) {
1835 if (color.rgba() == d->colortable.at(i)) {
1836 pixel = i;
1837 break;
1838 }
1839 }
1840 fill(pixel);
1841 break;
1842 }
1843 case QImage::Format_Mono:
1844 case QImage::Format_MonoLSB:
1845 if (color == Qt::color1)
1846 fill((uint) 1);
1847 else
1848 fill((uint) 0);
1849 break;
1850 case QImage::Format_RGBX64:
1851 qt_rectfill<quint64>(reinterpret_cast<quint64*>(d->data), opaque,
1852 0, 0, d->width, d->height, d->bytes_per_line);
1853 break;
1854 case QImage::Format_RGBA64:
1855 qt_rectfill<quint64>(reinterpret_cast<quint64*>(d->data), color.rgba64(),
1856 0, 0, d->width, d->height, d->bytes_per_line);
1857 break;
1858 case QImage::Format_RGBA64_Premultiplied:
1859 qt_rectfill<quint64>(reinterpret_cast<quint64 *>(d->data), color.rgba64().premultiplied(),
1860 0, 0, d->width, d->height, d->bytes_per_line);
1861 break;
1862 default: {
1863 QPainter p(this);
1864 p.setCompositionMode(QPainter::CompositionMode_Source);
1865 p.fillRect(rect(), color);
1866 }}
1867}
1868
1869
1870
1871/*!
1872 Inverts all pixel values in the image.
1873
1874 The given invert \a mode only have a meaning when the image's
1875 depth is 32. The default \a mode is InvertRgb, which leaves the
1876 alpha channel unchanged. If the \a mode is InvertRgba, the alpha
1877 bits are also inverted.
1878
1879 Inverting an 8-bit image means to replace all pixels using color
1880 index \e i with a pixel using color index 255 minus \e i. The same
1881 is the case for a 1-bit image. Note that the color table is \e not
1882 changed.
1883
1884 If the image has a premultiplied alpha channel, the image is first
1885 converted to an unpremultiplied image format to be inverted and
1886 then converted back.
1887
1888 \sa {QImage#Image Transformations}{Image Transformations}
1889*/
1890
1891void QImage::invertPixels(InvertMode mode)
1892{
1893 if (!d)
1894 return;
1895
1896 detach();
1897
1898 // In case detach() ran out of memory
1899 if (!d)
1900 return;
1901
1902 QImage::Format originalFormat = d->format;
1903 // Inverting premultiplied pixels would produce invalid image data.
1904 if (hasAlphaChannel() && qPixelLayouts[d->format].premultiplied) {
1905 if (depth() > 32) {
1906 if (!d->convertInPlace(QImage::Format_RGBA64, { }))
1907 *this = convertToFormat(QImage::Format_RGBA64);
1908 } else {
1909 if (!d->convertInPlace(QImage::Format_ARGB32, { }))
1910 *this = convertToFormat(QImage::Format_ARGB32);
1911 }
1912 }
1913
1914 if (depth() < 32) {
1915 // This assumes no alpha-channel as the only formats with non-premultipled alpha are 32bit.
1916 qsizetype bpl = (qsizetype(d->width) * d->depth + 7) / 8;
1917 int pad = d->bytes_per_line - bpl;
1918 uchar *sl = d->data;
1919 for (int y=0; y<d->height; ++y) {
1920 for (qsizetype x=0; x<bpl; ++x)
1921 *sl++ ^= 0xff;
1922 sl += pad;
1923 }
1924 }
1925 else if (depth() == 64) {
1926 quint16 *p = (quint16*)d->data;
1927 quint16 *end = (quint16*)(d->data + d->nbytes);
1928 quint16 xorbits = 0xffff;
1929 while (p < end) {
1930 *p++ ^= xorbits;
1931 *p++ ^= xorbits;
1932 *p++ ^= xorbits;
1933 if (mode == InvertRgba)
1934 *p++ ^= xorbits;
1935 else
1936 p++;
1937 }
1938 } else {
1939 quint32 *p = (quint32*)d->data;
1940 quint32 *end = (quint32*)(d->data + d->nbytes);
1941 quint32 xorbits = 0xffffffff;
1942 switch (d->format) {
1943 case QImage::Format_RGBA8888:
1944 if (mode == InvertRgba)
1945 break;
1946 Q_FALLTHROUGH();
1947 case QImage::Format_RGBX8888:
1948#if Q_BYTE_ORDER == Q_BIG_ENDIAN
1949 xorbits = 0xffffff00;
1950 break;
1951#else
1952 xorbits = 0x00ffffff;
1953 break;
1954#endif
1955 case QImage::Format_ARGB32:
1956 if (mode == InvertRgba)
1957 break;
1958 Q_FALLTHROUGH();
1959 case QImage::Format_RGB32:
1960 xorbits = 0x00ffffff;
1961 break;
1962 case QImage::Format_BGR30:
1963 case QImage::Format_RGB30:
1964 xorbits = 0x3fffffff;
1965 break;
1966 default:
1967 Q_UNREACHABLE();
1968 xorbits = 0;
1969 break;
1970 }
1971 while (p < end)
1972 *p++ ^= xorbits;
1973 }
1974
1975 if (originalFormat != d->format) {
1976 if (!d->convertInPlace(originalFormat, { }))
1977 *this = convertToFormat(originalFormat);
1978 }
1979}
1980
1981// Windows defines these
1982#if defined(write)
1983# undef write
1984#endif
1985#if defined(close)
1986# undef close
1987#endif
1988#if defined(read)
1989# undef read
1990#endif
1991
1992/*!
1993 \since 4.6
1994 Resizes the color table to contain \a colorCount entries.
1995
1996 If the color table is expanded, all the extra colors will be set to
1997 transparent (i.e qRgba(0, 0, 0, 0)).
1998
1999 When the image is used, the color table must be large enough to
2000 have entries for all the pixel/index values present in the image,
2001 otherwise the results are undefined.
2002
2003 \sa colorCount(), colorTable(), setColor(), {QImage#Image
2004 Transformations}{Image Transformations}
2005*/
2006
2007void QImage::setColorCount(int colorCount)
2008{
2009 if (!d) {
2010 qWarning("QImage::setColorCount: null image");
2011 return;
2012 }
2013
2014 detach();
2015
2016 // In case detach() ran out of memory
2017 if (!d)
2018 return;
2019
2020 if (colorCount == d->colortable.size())
2021 return;
2022 if (colorCount <= 0) { // use no color table
2023 d->colortable.clear();
2024 return;
2025 }
2026 int nc = d->colortable.size();
2027 d->colortable.resize(colorCount);
2028 for (int i = nc; i < colorCount; ++i)
2029 d->colortable[i] = 0;
2030}
2031
2032/*!
2033 Returns the format of the image.
2034
2035 \sa {QImage#Image Formats}{Image Formats}
2036*/
2037QImage::Format QImage::format() const
2038{
2039 return d ? d->format : Format_Invalid;
2040}
2041
2042/*!
2043 \fn QImage QImage::convertToFormat(Format format, Qt::ImageConversionFlags flags) const &
2044 \fn QImage QImage::convertToFormat(Format format, Qt::ImageConversionFlags flags) &&
2045
2046 Returns a copy of the image in the given \a format.
2047
2048 The specified image conversion \a flags control how the image data
2049 is handled during the conversion process.
2050
2051 \sa convertTo(), {Image Formats}
2052*/
2053
2054/*!
2055 \fn QImage QImage::convertedTo(Format format, Qt::ImageConversionFlags flags) const &
2056 \fn QImage QImage::convertedTo(Format format, Qt::ImageConversionFlags flags) &&
2057 \since 6.0
2058
2059 Returns a copy of the image in the given \a format.
2060
2061 The specified image conversion \a flags control how the image data
2062 is handled during the conversion process.
2063
2064 \sa convertTo(), {Image Formats}
2065*/
2066
2067/*!
2068 \internal
2069*/
2070QImage QImage::convertToFormat_helper(Format format, Qt::ImageConversionFlags flags) const
2071{
2072 if (!d || d->format == format)
2073 return *this;
2074
2075 if (d->format == Format_Invalid || format <= Format_Invalid || format >= NImageFormats)
2076 return QImage();
2077
2078 const QPixelLayout *destLayout = &qPixelLayouts[format];
2079 Image_Converter converter = qimage_converter_map[d->format][format];
2080 if (!converter && format > QImage::Format_Indexed8 && d->format > QImage::Format_Indexed8) {
2081 if (qt_highColorPrecision(d->format, !destLayout->hasAlphaChannel)
2082 && qt_highColorPrecision(format, !hasAlphaChannel())) {
2083 converter = convert_generic_over_rgb64;
2084 } else
2085 converter = convert_generic;
2086 }
2087 if (converter) {
2088 QImage image(d->width, d->height, format);
2089
2090 QIMAGE_SANITYCHECK_MEMORY(image);
2091
2092 image.d->offset = offset();
2093 copyMetadata(image.d, d);
2094
2095 converter(image.d, d, flags);
2096 return image;
2097 }
2098
2099 // Convert indexed formats over ARGB32 or RGB32 to the final format.
2100 Q_ASSERT(format != QImage::Format_ARGB32 && format != QImage::Format_RGB32);
2101 Q_ASSERT(d->format != QImage::Format_ARGB32 && d->format != QImage::Format_RGB32);
2102
2103 if (!hasAlphaChannel())
2104 return convertToFormat(Format_RGB32, flags).convertToFormat(format, flags);
2105
2106 return convertToFormat(Format_ARGB32, flags).convertToFormat(format, flags);
2107}
2108
2109/*!
2110 \internal
2111*/
2112bool QImage::convertToFormat_inplace(Format format, Qt::ImageConversionFlags flags)
2113{
2114 return d && d->convertInPlace(format, flags);
2115}
2116
2117static inline int pixel_distance(QRgb p1, QRgb p2) {
2118 int r1 = qRed(p1);
2119 int g1 = qGreen(p1);
2120 int b1 = qBlue(p1);
2121 int a1 = qAlpha(p1);
2122
2123 int r2 = qRed(p2);
2124 int g2 = qGreen(p2);
2125 int b2 = qBlue(p2);
2126 int a2 = qAlpha(p2);
2127
2128 return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2) + abs(a1 - a2);
2129}
2130
2131static inline int closestMatch(QRgb pixel, const QList<QRgb> &clut) {
2132 int idx = 0;
2133 int current_distance = INT_MAX;
2134 for (int i=0; i<clut.size(); ++i) {
2135 int dist = pixel_distance(pixel, clut.at(i));
2136 if (dist < current_distance) {
2137 current_distance = dist;
2138 idx = i;
2139 }
2140 }
2141 return idx;
2142}
2143
2144static QImage convertWithPalette(const QImage &src, QImage::Format format,
2145 const QList<QRgb> &clut) {
2146 QImage dest(src.size(), format);
2147 dest.setColorTable(clut);
2148
2149 QImageData::get(dest)->text = QImageData::get(src)->text;
2150
2151 int h = src.height();
2152 int w = src.width();
2153
2154 QHash<QRgb, int> cache;
2155
2156 if (format == QImage::Format_Indexed8) {
2157 for (int y=0; y<h; ++y) {
2158 const QRgb *src_pixels = (const QRgb *) src.scanLine(y);
2159 uchar *dest_pixels = (uchar *) dest.scanLine(y);
2160 for (int x=0; x<w; ++x) {
2161 int src_pixel = src_pixels[x];
2162 int value = cache.value(src_pixel, -1);
2163 if (value == -1) {
2164 value = closestMatch(src_pixel, clut);
2165 cache.insert(src_pixel, value);
2166 }
2167 dest_pixels[x] = (uchar) value;
2168 }
2169 }
2170 } else {
2171 QList<QRgb> table = clut;
2172 table.resize(2);
2173 for (int y=0; y<h; ++y) {
2174 const QRgb *src_pixels = (const QRgb *) src.scanLine(y);
2175 for (int x=0; x<w; ++x) {
2176 int src_pixel = src_pixels[x];
2177 int value = cache.value(src_pixel, -1);
2178 if (value == -1) {
2179 value = closestMatch(src_pixel, table);
2180 cache.insert(src_pixel, value);
2181 }
2182 dest.setPixel(x, y, value);
2183 }
2184 }
2185 }
2186
2187 return dest;
2188}
2189
2190/*!
2191 \overload
2192
2193 Returns a copy of the image converted to the given \a format,
2194 using the specified \a colorTable.
2195
2196 Conversion from RGB formats to indexed formats is a slow operation
2197 and will use a straightforward nearest color approach, with no
2198 dithering.
2199*/
2200QImage QImage::convertToFormat(Format format, const QList<QRgb> &colorTable, Qt::ImageConversionFlags flags) const
2201{
2202 if (!d || d->format == format)
2203 return *this;
2204
2205 if (format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
2206 return QImage();
2207 if (format <= QImage::Format_Indexed8)
2208 return convertWithPalette(convertToFormat(QImage::Format_ARGB32, flags), format, colorTable);
2209
2210 return convertToFormat(format, flags);
2211}
2212
2213/*!
2214 \since 5.9
2215
2216 Changes the format of the image to \a format without changing the
2217 data. Only works between formats of the same depth.
2218
2219 Returns \c true if successful.
2220
2221 This function can be used to change images with alpha-channels to
2222 their corresponding opaque formats if the data is known to be opaque-only,
2223 or to change the format of a given image buffer before overwriting
2224 it with new data.
2225
2226 \warning The function does not check if the image data is valid in the
2227 new format and will still return \c true if the depths are compatible.
2228 Operations on an image with invalid data are undefined.
2229
2230 \warning If the image is not detached, this will cause the data to be
2231 copied.
2232
2233 \sa hasAlphaChannel(), convertToFormat()
2234*/
2235
2236bool QImage::reinterpretAsFormat(Format format)
2237{
2238 if (!d)
2239 return false;
2240 if (d->format == format)
2241 return true;
2242 if (qt_depthForFormat(format) != qt_depthForFormat(d->format))
2243 return false;
2244 if (!isDetached()) { // Detach only if shared, not for read-only data.
2245 QImageData *oldD = d;
2246 detach();
2247 // In case detach() ran out of memory
2248 if (!d) {
2249 d = oldD;
2250 return false;
2251 }
2252 }
2253
2254 d->format = format;
2255 return true;
2256}
2257
2258/*!
2259 \since 5.13
2260
2261 Converts the image to the given \a format in place, detaching if necessary.
2262
2263 The specified image conversion \a flags control how the image data
2264 is handled during the conversion process.
2265
2266 \sa convertedTo()
2267*/
2268
2269void QImage::convertTo(Format format, Qt::ImageConversionFlags flags)
2270{
2271 if (!d || format <= QImage::Format_Invalid || format >= QImage::NImageFormats)
2272 return;
2273
2274 if (d->format == format)
2275 return;
2276
2277 detach();
2278 if (convertToFormat_inplace(format, flags))
2279 return;
2280
2281 *this = convertToFormat_helper(format, flags);
2282}
2283
2284/*!
2285 \fn bool QImage::valid(const QPoint &pos) const
2286
2287 Returns \c true if \a pos is a valid coordinate pair within the
2288 image; otherwise returns \c false.
2289
2290 \sa rect(), QRect::contains()
2291*/
2292
2293/*!
2294 \overload
2295
2296 Returns \c true if QPoint(\a x, \a y) is a valid coordinate pair
2297 within the image; otherwise returns \c false.
2298*/
2299bool QImage::valid(int x, int y) const
2300{
2301 return d
2302 && x >= 0 && x < d->width
2303 && y >= 0 && y < d->height;
2304}
2305
2306/*!
2307 \fn int QImage::pixelIndex(const QPoint &position) const
2308
2309 Returns the pixel index at the given \a position.
2310
2311 If \a position is not valid, or if the image is not a paletted
2312 image (depth() > 8), the results are undefined.
2313
2314 \sa valid(), depth(), {QImage#Pixel Manipulation}{Pixel Manipulation}
2315*/
2316
2317/*!
2318 \overload
2319
2320 Returns the pixel index at (\a x, \a y).
2321*/
2322int QImage::pixelIndex(int x, int y) const
2323{
2324 if (!d || x < 0 || x >= d->width || y < 0 || y >= height()) {
2325 qWarning("QImage::pixelIndex: coordinate (%d,%d) out of range", x, y);
2326 return -12345;
2327 }
2328 const uchar * s = scanLine(y);
2329 switch(d->format) {
2330 case Format_Mono:
2331 return (*(s + (x >> 3)) >> (7- (x & 7))) & 1;
2332 case Format_MonoLSB:
2333 return (*(s + (x >> 3)) >> (x & 7)) & 1;
2334 case Format_Indexed8:
2335 return (int)s[x];
2336 default:
2337 qWarning("QImage::pixelIndex: Not applicable for %d-bpp images (no palette)", d->depth);
2338 }
2339 return 0;
2340}
2341
2342
2343/*!
2344 \fn QRgb QImage::pixel(const QPoint &position) const
2345
2346 Returns the color of the pixel at the given \a position.
2347
2348 If the \a position is not valid, the results are undefined.
2349
2350 \warning This function is expensive when used for massive pixel
2351 manipulations. Use constBits() or constScanLine() when many
2352 pixels needs to be read.
2353
2354 \sa setPixel(), valid(), constBits(), constScanLine(), {QImage#Pixel Manipulation}{Pixel
2355 Manipulation}
2356*/
2357
2358/*!
2359 \overload
2360
2361 Returns the color of the pixel at coordinates (\a x, \a y).
2362*/
2363QRgb QImage::pixel(int x, int y) const
2364{
2365 if (!d || x < 0 || x >= d->width || y < 0 || y >= d->height) {
2366 qWarning("QImage::pixel: coordinate (%d,%d) out of range", x, y);
2367 return 12345;
2368 }
2369
2370 const uchar *s = d->data + y * d->bytes_per_line;
2371
2372 int index = -1;
2373 switch (d->format) {
2374 case Format_Mono:
2375 index = (*(s + (x >> 3)) >> (~x & 7)) & 1;
2376 break;
2377 case Format_MonoLSB:
2378 index = (*(s + (x >> 3)) >> (x & 7)) & 1;
2379 break;
2380 case Format_Indexed8:
2381 index = s[x];
2382 break;
2383 default:
2384 break;
2385 }
2386 if (index >= 0) { // Indexed format
2387 if (index >= d->colortable.size()) {
2388 qWarning("QImage::pixel: color table index %d out of range.", index);
2389 return 0;
2390 }
2391 return d->colortable.at(index);
2392 }
2393
2394 switch (d->format) {
2395 case Format_RGB32:
2396 return 0xff000000 | reinterpret_cast<const QRgb *>(s)[x];
2397 case Format_ARGB32: // Keep old behaviour.
2398 case Format_ARGB32_Premultiplied:
2399 return reinterpret_cast<const QRgb *>(s)[x];
2400 case Format_RGBX8888:
2401 case Format_RGBA8888: // Match ARGB32 behavior.
2402 case Format_RGBA8888_Premultiplied:
2403 return RGBA2ARGB(reinterpret_cast<const quint32 *>(s)[x]);
2404 case Format_BGR30:
2405 case Format_A2BGR30_Premultiplied:
2406 return qConvertA2rgb30ToArgb32<PixelOrderBGR>(reinterpret_cast<const quint32 *>(s)[x]);
2407 case Format_RGB30:
2408 case Format_A2RGB30_Premultiplied:
2409 return qConvertA2rgb30ToArgb32<PixelOrderRGB>(reinterpret_cast<const quint32 *>(s)[x]);
2410 case Format_RGB16:
2411 return qConvertRgb16To32(reinterpret_cast<const quint16 *>(s)[x]);
2412 case Format_RGBX64:
2413 case Format_RGBA64: // Match ARGB32 behavior.
2414 case Format_RGBA64_Premultiplied:
2415 return reinterpret_cast<const QRgba64 *>(s)[x].toArgb32();
2416 default:
2417 break;
2418 }
2419 const QPixelLayout *layout = &qPixelLayouts[d->format];
2420 uint result;
2421 return *layout->fetchToARGB32PM(&result, s, x, 1, nullptr, nullptr);
2422}
2423
2424/*!
2425 \fn void QImage::setPixel(const QPoint &position, uint index_or_rgb)
2426
2427 Sets the pixel index or color at the given \a position to \a
2428 index_or_rgb.
2429
2430 If the image's format is either monochrome or paletted, the given \a
2431 index_or_rgb value must be an index in the image's color table,
2432 otherwise the parameter must be a QRgb value.
2433
2434 If \a position is not a valid coordinate pair in the image, or if
2435 \a index_or_rgb >= colorCount() in the case of monochrome and
2436 paletted images, the result is undefined.
2437
2438 \warning This function is expensive due to the call of the internal
2439 \c{detach()} function called within; if performance is a concern, we
2440 recommend the use of scanLine() or bits() to access pixel data directly.
2441
2442 \sa pixel(), {QImage#Pixel Manipulation}{Pixel Manipulation}
2443*/
2444
2445/*!
2446 \overload
2447
2448 Sets the pixel index or color at (\a x, \a y) to \a index_or_rgb.
2449*/
2450void QImage::setPixel(int x, int y, uint index_or_rgb)
2451{
2452 if (!d || x < 0 || x >= width() || y < 0 || y >= height()) {
2453 qWarning("QImage::setPixel: coordinate (%d,%d) out of range", x, y);
2454 return;
2455 }
2456 // detach is called from within scanLine
2457 uchar * s = scanLine(y);
2458 switch(d->format) {
2459 case Format_Mono:
2460 case Format_MonoLSB:
2461 if (index_or_rgb > 1) {
2462 qWarning("QImage::setPixel: Index %d out of range", index_or_rgb);
2463 } else if (format() == Format_MonoLSB) {
2464 if (index_or_rgb==0)
2465 *(s + (x >> 3)) &= ~(1 << (x & 7));
2466 else
2467 *(s + (x >> 3)) |= (1 << (x & 7));
2468 } else {
2469 if (index_or_rgb==0)
2470 *(s + (x >> 3)) &= ~(1 << (7-(x & 7)));
2471 else
2472 *(s + (x >> 3)) |= (1 << (7-(x & 7)));
2473 }
2474 return;
2475 case Format_Indexed8:
2476 if (index_or_rgb >= (uint)d->colortable.size()) {
2477 qWarning("QImage::setPixel: Index %d out of range", index_or_rgb);
2478 return;
2479 }
2480 s[x] = index_or_rgb;
2481 return;
2482 case Format_RGB32:
2483 //make sure alpha is 255, we depend on it in qdrawhelper for cases
2484 // when image is set as a texture pattern on a qbrush
2485 ((uint *)s)[x] = 0xff000000 | index_or_rgb;
2486 return;
2487 case Format_ARGB32:
2488 case Format_ARGB32_Premultiplied:
2489 ((uint *)s)[x] = index_or_rgb;
2490 return;
2491 case Format_RGB16:
2492 ((quint16 *)s)[x] = qConvertRgb32To16(index_or_rgb);
2493 return;
2494 case Format_RGBX8888:
2495 ((uint *)s)[x] = ARGB2RGBA(0xff000000 | index_or_rgb);
2496 return;
2497 case Format_RGBA8888:
2498 case Format_RGBA8888_Premultiplied:
2499 ((uint *)s)[x] = ARGB2RGBA(index_or_rgb);
2500 return;
2501 case Format_BGR30:
2502 ((uint *)s)[x] = qConvertRgb32ToRgb30<PixelOrderBGR>(index_or_rgb);
2503 return;
2504 case Format_A2BGR30_Premultiplied:
2505 ((uint *)s)[x] = qConvertArgb32ToA2rgb30<PixelOrderBGR>(index_or_rgb);
2506 return;
2507 case Format_RGB30:
2508 ((uint *)s)[x] = qConvertRgb32ToRgb30<PixelOrderRGB>(index_or_rgb);
2509 return;
2510 case Format_A2RGB30_Premultiplied:
2511 ((uint *)s)[x] = qConvertArgb32ToA2rgb30<PixelOrderRGB>(index_or_rgb);
2512 return;
2513 case Format_RGBA64:
2514 case Format_RGBA64_Premultiplied:
2515 ((QRgba64 *)s)[x] = QRgba64::fromArgb32(index_or_rgb);
2516 return;
2517 case Format_Invalid:
2518 case NImageFormats:
2519 Q_ASSERT(false);
2520 return;
2521 default:
2522 break;
2523 }
2524
2525 const QPixelLayout *layout = &qPixelLayouts[d->format];
2526 if (!hasAlphaChannel())
2527 layout->storeFromRGB32(s, &index_or_rgb, x, 1, nullptr, nullptr);
2528 else
2529 layout->storeFromARGB32PM(s, &index_or_rgb, x, 1, nullptr, nullptr);
2530}
2531
2532/*!
2533 \fn QColor QImage::pixelColor(const QPoint &position) const
2534 \since 5.6
2535
2536 Returns the color of the pixel at the given \a position as a QColor.
2537
2538 If the \a position is not valid, an invalid QColor is returned.
2539
2540 \warning This function is expensive when used for massive pixel
2541 manipulations. Use constBits() or constScanLine() when many
2542 pixels needs to be read.
2543
2544 \sa setPixel(), valid(), constBits(), constScanLine(), {QImage#Pixel Manipulation}{Pixel
2545 Manipulation}
2546*/
2547
2548/*!
2549 \overload
2550 \since 5.6
2551
2552 Returns the color of the pixel at coordinates (\a x, \a y) as a QColor.
2553*/
2554QColor QImage::pixelColor(int x, int y) const
2555{
2556 if (!d || x < 0 || x >= d->width || y < 0 || y >= height()) {
2557 qWarning("QImage::pixelColor: coordinate (%d,%d) out of range", x, y);
2558 return QColor();
2559 }
2560
2561 QRgba64 c;
2562 const uchar * s = constScanLine(y);
2563 switch (d->format) {
2564 case Format_BGR30:
2565 case Format_A2BGR30_Premultiplied:
2566 c = qConvertA2rgb30ToRgb64<PixelOrderBGR>(reinterpret_cast<const quint32 *>(s)[x]);
2567 break;
2568 case Format_RGB30:
2569 case Format_A2RGB30_Premultiplied:
2570 c = qConvertA2rgb30ToRgb64<PixelOrderRGB>(reinterpret_cast<const quint32 *>(s)[x]);
2571 break;
2572 case Format_RGBX64:
2573 case Format_RGBA64:
2574 case Format_RGBA64_Premultiplied:
2575 c = reinterpret_cast<const QRgba64 *>(s)[x];
2576 break;
2577 case Format_Grayscale16: {
2578 quint16 v = reinterpret_cast<const quint16 *>(s)[x];
2579 return QColor(qRgba64(v, v, v, 0xffff));
2580 }
2581 default:
2582 c = QRgba64::fromArgb32(pixel(x, y));
2583 break;
2584 }
2585 // QColor is always unpremultiplied
2586 if (hasAlphaChannel() && qPixelLayouts[d->format].premultiplied)
2587 c = c.unpremultiplied();
2588 return QColor(c);
2589}
2590
2591/*!
2592 \fn void QImage::setPixelColor(const QPoint &position, const QColor &color)
2593 \since 5.6
2594
2595 Sets the color at the given \a position to \a color.
2596
2597 If \a position is not a valid coordinate pair in the image, or
2598 the image's format is either monochrome or paletted, the result is undefined.
2599
2600 \warning This function is expensive due to the call of the internal
2601 \c{detach()} function called within; if performance is a concern, we
2602 recommend the use of scanLine() or bits() to access pixel data directly.
2603
2604 \sa pixel(), bits(), scanLine(), {QImage#Pixel Manipulation}{Pixel Manipulation}
2605*/
2606
2607/*!
2608 \overload
2609 \since 5.6
2610
2611 Sets the pixel color at (\a x, \a y) to \a color.
2612*/
2613void QImage::setPixelColor(int x, int y, const QColor &color)
2614{
2615 if (!d || x < 0 || x >= width() || y < 0 || y >= height()) {
2616 qWarning("QImage::setPixelColor: coordinate (%d,%d) out of range", x, y);
2617 return;
2618 }
2619
2620 if (!color.isValid()) {
2621 qWarning("QImage::setPixelColor: color is invalid");
2622 return;
2623 }
2624
2625 // QColor is always unpremultiplied
2626 QRgba64 c = color.rgba64();
2627 if (!hasAlphaChannel())
2628 c.setAlpha(65535);
2629 else if (qPixelLayouts[d->format].premultiplied)
2630 c = c.premultiplied();
2631 // detach is called from within scanLine
2632 uchar * s = scanLine(y);
2633 switch (d->format) {
2634 case Format_Mono:
2635 case Format_MonoLSB:
2636 case Format_Indexed8:
2637 qWarning("QImage::setPixelColor: called on monochrome or indexed format");
2638 return;
2639 case Format_BGR30:
2640 ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderBGR>(c) | 0xc0000000;
2641 return;
2642 case Format_A2BGR30_Premultiplied:
2643 ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderBGR>(c);
2644 return;
2645 case Format_RGB30:
2646 ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderRGB>(c) | 0xc0000000;
2647 return;
2648 case Format_A2RGB30_Premultiplied:
2649 ((uint *)s)[x] = qConvertRgb64ToRgb30<PixelOrderRGB>(c);
2650 return;
2651 case Format_RGBX64:
2652 case Format_RGBA64:
2653 case Format_RGBA64_Premultiplied:
2654 ((QRgba64 *)s)[x] = c;
2655 return;
2656 default:
2657 setPixel(x, y, c.toArgb32());
2658 return;
2659 }
2660}
2661
2662/*!
2663 Returns \c true if all the colors in the image are shades of gray
2664 (i.e. their red, green and blue components are equal); otherwise
2665 false.
2666
2667 Note that this function is slow for images without color table.
2668
2669 \sa isGrayscale()
2670*/
2671bool QImage::allGray() const
2672{
2673 if (!d)
2674 return true;
2675
2676 switch (d->format) {
2677 case Format_Mono:
2678 case Format_MonoLSB:
2679 case Format_Indexed8:
2680 for (int i = 0; i < d->colortable.size(); ++i) {
2681 if (!qIsGray(d->colortable.at(i)))
2682 return false;
2683 }
2684 return true;
2685 case Format_Alpha8:
2686 return false;
2687 case Format_Grayscale8:
2688 case Format_Grayscale16:
2689 return true;
2690 case Format_RGB32:
2691 case Format_ARGB32:
2692 case Format_ARGB32_Premultiplied:
2693#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
2694 case Format_RGBX8888:
2695 case Format_RGBA8888:
2696 case Format_RGBA8888_Premultiplied:
2697#endif
2698 for (int j = 0; j < d->height; ++j) {
2699 const QRgb *b = (const QRgb *)constScanLine(j);
2700 for (int i = 0; i < d->width; ++i) {
2701 if (!qIsGray(b[i]))
2702 return false;
2703 }
2704 }
2705 return true;
2706 case Format_RGB16:
2707 for (int j = 0; j < d->height; ++j) {
2708 const quint16 *b = (const quint16 *)constScanLine(j);
2709 for (int i = 0; i < d->width; ++i) {
2710 if (!qIsGray(qConvertRgb16To32(b[i])))
2711 return false;
2712 }
2713 }
2714 return true;
2715 default:
2716 break;
2717 }
2718
2719 uint buffer[BufferSize];
2720 const QPixelLayout *layout = &qPixelLayouts[d->format];
2721 const auto fetch = layout->fetchToARGB32PM;
2722 for (int j = 0; j < d->height; ++j) {
2723 const uchar *b = constScanLine(j);
2724 int x = 0;
2725 while (x < d->width) {
2726 int l = qMin(d->width - x, BufferSize);
2727 const uint *ptr = fetch(buffer, b, x, l, nullptr, nullptr);
2728 for (int i = 0; i < l; ++i) {
2729 if (!qIsGray(ptr[i]))
2730 return false;
2731 }
2732 x += l;
2733 }
2734 }
2735 return true;
2736}
2737
2738/*!
2739 For 32-bit images, this function is equivalent to allGray().
2740
2741 For color indexed images, this function returns \c true if
2742 color(i) is QRgb(i, i, i) for all indexes of the color table;
2743 otherwise returns \c false.
2744
2745 \sa allGray(), {QImage#Image Formats}{Image Formats}
2746*/
2747bool QImage::isGrayscale() const
2748{
2749 if (!d)
2750 return false;
2751
2752 if (d->format == QImage::Format_Alpha8)
2753 return false;
2754
2755 if (d->format == QImage::Format_Grayscale8 || d->format == QImage::Format_Grayscale16)
2756 return true;
2757
2758 switch (depth()) {
2759 case 32:
2760 case 24:
2761 case 16:
2762 return allGray();
2763 case 8: {
2764 Q_ASSERT(d->format == QImage::Format_Indexed8);
2765 for (int i = 0; i < colorCount(); i++)
2766 if (d->colortable.at(i) != qRgb(i,i,i))
2767 return false;
2768 return true;
2769 }
2770 }
2771 return false;
2772}
2773
2774/*!
2775 \fn QImage QImage::scaled(int width, int height, Qt::AspectRatioMode aspectRatioMode,
2776 Qt::TransformationMode transformMode) const
2777 \overload
2778
2779 Returns a copy of the image scaled to a rectangle with the given
2780 \a width and \a height according to the given \a aspectRatioMode
2781 and \a transformMode.
2782
2783 If either the \a width or the \a height is zero or negative, this
2784 function returns a null image.
2785*/
2786
2787/*!
2788 \fn QImage QImage::scaled(const QSize &size, Qt::AspectRatioMode aspectRatioMode,
2789 Qt::TransformationMode transformMode) const
2790
2791 Returns a copy of the image scaled to a rectangle defined by the
2792 given \a size according to the given \a aspectRatioMode and \a
2793 transformMode.
2794
2795 \image qimage-scaling.png
2796
2797 \list
2798 \li If \a aspectRatioMode is Qt::IgnoreAspectRatio, the image
2799 is scaled to \a size.
2800 \li If \a aspectRatioMode is Qt::KeepAspectRatio, the image is
2801 scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
2802 \li If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
2803 the image is scaled to a rectangle as small as possible
2804 outside \a size, preserving the aspect ratio.
2805 \endlist
2806
2807 If the given \a size is empty, this function returns a null image.
2808
2809 \sa isNull(), {QImage#Image Transformations}{Image
2810 Transformations}
2811*/
2812QImage QImage::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
2813{
2814 if (!d) {
2815 qWarning("QImage::scaled: Image is a null image");
2816 return QImage();
2817 }
2818 if (s.isEmpty())
2819 return QImage();
2820
2821 QSize newSize = size();
2822 newSize.scale(s, aspectMode);
2823 newSize.rwidth() = qMax(newSize.width(), 1);
2824 newSize.rheight() = qMax(newSize.height(), 1);
2825 if (newSize == size())
2826 return *this;
2827
2828 Q_TRACE_SCOPE(QImage_scaled, s, aspectMode, mode);
2829
2830 QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(), (qreal)newSize.height() / height());
2831 QImage img = transformed(wm, mode);
2832 return img;
2833}
2834
2835/*!
2836 \fn QImage QImage::scaledToWidth(int width, Qt::TransformationMode mode) const
2837
2838 Returns a scaled copy of the image. The returned image is scaled
2839 to the given \a width using the specified transformation \a
2840 mode.
2841
2842 This function automatically calculates the height of the image so
2843 that its aspect ratio is preserved.
2844
2845 If the given \a width is 0 or negative, a null image is returned.
2846
2847 \sa {QImage#Image Transformations}{Image Transformations}
2848*/
2849QImage QImage::scaledToWidth(int w, Qt::TransformationMode mode) const
2850{
2851 if (!d) {
2852 qWarning("QImage::scaleWidth: Image is a null image");
2853 return QImage();
2854 }
2855 if (w <= 0)
2856 return QImage();
2857
2858 Q_TRACE_SCOPE(QImage_scaledToWidth, w, mode);
2859
2860 qreal factor = (qreal) w / width();
2861 QTransform wm = QTransform::fromScale(factor, factor);
2862 return transformed(wm, mode);
2863}
2864
2865/*!
2866 \fn QImage QImage::scaledToHeight(int height, Qt::TransformationMode mode) const
2867
2868 Returns a scaled copy of the image. The returned image is scaled
2869 to the given \a height using the specified transformation \a
2870 mode.
2871
2872 This function automatically calculates the width of the image so that
2873 the ratio of the image is preserved.
2874
2875 If the given \a height is 0 or negative, a null image is returned.
2876
2877 \sa {QImage#Image Transformations}{Image Transformations}
2878*/
2879QImage QImage::scaledToHeight(int h, Qt::TransformationMode mode) const
2880{
2881 if (!d) {
2882 qWarning("QImage::scaleHeight: Image is a null image");
2883 return QImage();
2884 }
2885 if (h <= 0)
2886 return QImage();
2887
2888 Q_TRACE_SCOPE(QImage_scaledToHeight, h, mode);
2889
2890 qreal factor = (qreal) h / height();
2891 QTransform wm = QTransform::fromScale(factor, factor);
2892 return transformed(wm, mode);
2893}
2894
2895/*!
2896 Builds and returns a 1-bpp mask from the alpha buffer in this
2897 image. Returns a null image if the image's format is
2898 QImage::Format_RGB32.
2899
2900 The \a flags argument is a bitwise-OR of the
2901 Qt::ImageConversionFlags, and controls the conversion
2902 process. Passing 0 for flags sets all the default options.
2903
2904 The returned image has little-endian bit order (i.e. the image's
2905 format is QImage::Format_MonoLSB), which you can convert to
2906 big-endian (QImage::Format_Mono) using the convertToFormat()
2907 function.
2908
2909 \sa createHeuristicMask(), {QImage#Image Transformations}{Image
2910 Transformations}
2911*/
2912QImage QImage::createAlphaMask(Qt::ImageConversionFlags flags) const
2913{
2914 if (!d || d->format == QImage::Format_RGB32)
2915 return QImage();
2916
2917 if (d->depth == 1) {
2918 // A monochrome pixmap, with alpha channels on those two colors.
2919 // Pretty unlikely, so use less efficient solution.
2920 return convertToFormat(Format_Indexed8, flags).createAlphaMask(flags);
2921 }
2922
2923 QImage mask(d->width, d->height, Format_MonoLSB);
2924 if (!mask.isNull()) {
2925 dither_to_Mono(mask.d, d, flags, true);
2926 copyPhysicalMetadata(mask.d, d);
2927 }
2928 return mask;
2929}
2930
2931#ifndef QT_NO_IMAGE_HEURISTIC_MASK
2932/*!
2933 Creates and returns a 1-bpp heuristic mask for this image.
2934
2935 The function works by selecting a color from one of the corners,
2936 then chipping away pixels of that color starting at all the edges.
2937 The four corners vote for which color is to be masked away. In
2938 case of a draw (this generally means that this function is not
2939 applicable to the image), the result is arbitrary.
2940
2941 The returned image has little-endian bit order (i.e. the image's
2942 format is QImage::Format_MonoLSB), which you can convert to
2943 big-endian (QImage::Format_Mono) using the convertToFormat()
2944 function.
2945
2946 If \a clipTight is true (the default) the mask is just large
2947 enough to cover the pixels; otherwise, the mask is larger than the
2948 data pixels.
2949
2950 Note that this function disregards the alpha buffer.
2951
2952 \sa createAlphaMask(), {QImage#Image Transformations}{Image
2953 Transformations}
2954*/
2955
2956QImage QImage::createHeuristicMask(bool clipTight) const
2957{
2958 if (!d)
2959 return QImage();
2960
2961 if (d->depth != 32) {
2962 QImage img32 = convertToFormat(Format_RGB32);
2963 return img32.createHeuristicMask(clipTight);
2964 }
2965
2966#define PIX(x,y) (*((const QRgb*)scanLine(y)+x) & 0x00ffffff)
2967
2968 int w = width();
2969 int h = height();
2970 QImage m(w, h, Format_MonoLSB);
2971 QIMAGE_SANITYCHECK_MEMORY(m);
2972 m.setColorCount(2);
2973 m.setColor(0, QColor(Qt::color0).rgba());
2974 m.setColor(1, QColor(Qt::color1).rgba());
2975 m.fill(0xff);
2976
2977 QRgb background = PIX(0,0);
2978 if (background != PIX(w-1,0) &&
2979 background != PIX(0,h-1) &&
2980 background != PIX(w-1,h-1)) {
2981 background = PIX(w-1,0);
2982 if (background != PIX(w-1,h-1) &&
2983 background != PIX(0,h-1) &&
2984 PIX(0,h-1) == PIX(w-1,h-1)) {
2985 background = PIX(w-1,h-1);
2986 }
2987 }
2988
2989 int x,y;
2990 bool done = false;
2991 uchar *ypp, *ypc, *ypn;
2992 while(!done) {
2993 done = true;
2994 ypn = m.scanLine(0);
2995 ypc = nullptr;
2996 for (y = 0; y < h; y++) {
2997 ypp = ypc;
2998 ypc = ypn;
2999 ypn = (y == h-1) ? nullptr : m.scanLine(y+1);
3000 const QRgb *p = (const QRgb *)scanLine(y);
3001 for (x = 0; x < w; x++) {
3002 // slowness here - it's possible to do six of these tests
3003 // together in one go. oh well.
3004 if ((x == 0 || y == 0 || x == w-1 || y == h-1 ||
3005 !(*(ypc + ((x-1) >> 3)) & (1 << ((x-1) & 7))) ||
3006 !(*(ypc + ((x+1) >> 3)) & (1 << ((x+1) & 7))) ||
3007 !(*(ypp + (x >> 3)) & (1 << (x & 7))) ||
3008 !(*(ypn + (x >> 3)) & (1 << (x & 7)))) &&
3009 ( (*(ypc + (x >> 3)) & (1 << (x & 7)))) &&
3010 ((*p & 0x00ffffff) == background)) {
3011 done = false;
3012 *(ypc + (x >> 3)) &= ~(1 << (x & 7));
3013 }
3014 p++;
3015 }
3016 }
3017 }
3018
3019 if (!clipTight) {
3020 ypn = m.scanLine(0);
3021 ypc = nullptr;
3022 for (y = 0; y < h; y++) {
3023 ypp = ypc;
3024 ypc = ypn;
3025 ypn = (y == h-1) ? nullptr : m.scanLine(y+1);
3026 const QRgb *p = (const QRgb *)scanLine(y);
3027 for (x = 0; x < w; x++) {
3028 if ((*p & 0x00ffffff) != background) {
3029 if (x > 0)
3030 *(ypc + ((x-1) >> 3)) |= (1 << ((x-1) & 7));
3031 if (x < w-1)
3032 *(ypc + ((x+1) >> 3)) |= (1 << ((x+1) & 7));
3033 if (y > 0)
3034 *(ypp + (x >> 3)) |= (1 << (x & 7));
3035 if (y < h-1)
3036 *(ypn + (x >> 3)) |= (1 << (x & 7));
3037 }
3038 p++;
3039 }
3040 }
3041 }
3042
3043#undef PIX
3044
3045 copyPhysicalMetadata(m.d, d);
3046 return m;
3047}
3048#endif //QT_NO_IMAGE_HEURISTIC_MASK
3049
3050/*!
3051 Creates and returns a mask for this image based on the given \a
3052 color value. If the \a mode is MaskInColor (the default value),
3053 all pixels matching \a color will be opaque pixels in the mask. If
3054 \a mode is MaskOutColor, all pixels matching the given color will
3055 be transparent.
3056
3057 \sa createAlphaMask(), createHeuristicMask()
3058*/
3059
3060QImage QImage::createMaskFromColor(QRgb color, Qt::MaskMode mode) const
3061{
3062 if (!d)
3063 return QImage();
3064 QImage maskImage(size(), QImage::Format_MonoLSB);
3065 QIMAGE_SANITYCHECK_MEMORY(maskImage);
3066 maskImage.fill(0);
3067 uchar *s = maskImage.bits();
3068 if (!s)
3069 return QImage();
3070
3071 if (depth() == 32) {
3072 for (int h = 0; h < d->height; h++) {
3073 const uint *sl = (const uint *) scanLine(h);
3074 for (int w = 0; w < d->width; w++) {
3075 if (sl[w] == color)
3076 *(s + (w >> 3)) |= (1 << (w & 7));
3077 }
3078 s += maskImage.bytesPerLine();
3079 }
3080 } else {
3081 for (int h = 0; h < d->height; h++) {
3082 for (int w = 0; w < d->width; w++) {
3083 if ((uint) pixel(w, h) == color)
3084 *(s + (w >> 3)) |= (1 << (w & 7));
3085 }
3086 s += maskImage.bytesPerLine();
3087 }
3088 }
3089 if (mode == Qt::MaskOutColor)
3090 maskImage.invertPixels();
3091
3092 copyPhysicalMetadata(maskImage.d, d);
3093 return maskImage;
3094}
3095
3096/*!
3097 \fn QImage QImage::mirrored(bool horizontal = false, bool vertical = true) const &
3098 \fn QImage QImage::mirrored(bool horizontal = false, bool vertical = true) &&
3099
3100 Returns a mirror of the image, mirrored in the horizontal and/or
3101 the vertical direction depending on whether \a horizontal and \a
3102 vertical are set to true or false.
3103
3104 Note that the original image is not changed.
3105
3106 \sa mirror(), {QImage#Image Transformations}{Image Transformations}
3107*/
3108
3109/*!
3110 \fn void QImage::mirror(bool horizontal = false, bool vertical = true)
3111 \since 6.0
3112
3113 Mirrors of the image in the horizontal and/or the vertical direction depending
3114 on whether \a horizontal and \a vertical are set to true or false.
3115
3116 \sa mirrored(), {QImage#Image Transformations}{Image Transformations}
3117*/
3118
3119template<class T> inline void do_mirror_data(QImageData *dst, QImageData *src,
3120 int dstX0, int dstY0,
3121 int dstXIncr, int dstYIncr,
3122 int w, int h)
3123{
3124 if (dst == src) {
3125 // When mirroring in-place, stop in the middle for one of the directions, since we
3126 // are swapping the bytes instead of merely copying.
3127 const int srcXEnd = (dstX0 && !dstY0) ? w / 2 : w;
3128 const int srcYEnd = dstY0 ? h / 2 : h;
3129 for (int srcY = 0, dstY = dstY0; srcY < srcYEnd; ++srcY, dstY += dstYIncr) {
3130 T *srcPtr = (T *) (src->data + srcY * src->bytes_per_line);
3131 T *dstPtr = (T *) (dst->data + dstY * dst->bytes_per_line);
3132 for (int srcX = 0, dstX = dstX0; srcX < srcXEnd; ++srcX, dstX += dstXIncr)
3133 std::swap(srcPtr[srcX], dstPtr[dstX]);
3134 }
3135 // If mirroring both ways, the middle line needs to be mirrored horizontally only.
3136 if (dstX0 && dstY0 && (h & 1)) {
3137 int srcY = h / 2;
3138 int srcXEnd2 = w / 2;
3139 T *srcPtr = (T *) (src->data + srcY * src->bytes_per_line);
3140 for (int srcX = 0, dstX = dstX0; srcX < srcXEnd2; ++srcX, dstX += dstXIncr)
3141 std::swap(srcPtr[srcX], srcPtr[dstX]);
3142 }
3143 } else {
3144 for (int srcY = 0, dstY = dstY0; srcY < h; ++srcY, dstY += dstYIncr) {
3145 T *srcPtr = (T *) (src->data + srcY * src->bytes_per_line);
3146 T *dstPtr = (T *) (dst->data + dstY * dst->bytes_per_line);
3147 for (int srcX = 0, dstX = dstX0; srcX < w; ++srcX, dstX += dstXIncr)
3148 dstPtr[dstX] = srcPtr[srcX];
3149 }
3150 }
3151}
3152
3153inline void do_flip(QImageData *dst, QImageData *src, int w, int h, int depth)
3154{
3155 const int data_bytes_per_line = w * (depth / 8);
3156 if (dst == src) {
3157 uint *srcPtr = reinterpret_cast<uint *>(src->data);
3158 uint *dstPtr = reinterpret_cast<uint *>(dst->data + (h - 1) * dst->bytes_per_line);
3159 h = h / 2;
3160 const int uint_per_line = (data_bytes_per_line + 3) >> 2; // bytes per line must be a multiple of 4
3161 for (int y = 0; y < h; ++y) {
3162 // This is auto-vectorized, no need for SSE2 or NEON versions:
3163 for (int x = 0; x < uint_per_line; x++) {
3164 const uint d = dstPtr[x];
3165 const uint s = srcPtr[x];
3166 dstPtr[x] = s;
3167 srcPtr[x] = d;
3168 }
3169 srcPtr += src->bytes_per_line >> 2;
3170 dstPtr -= dst->bytes_per_line >> 2;
3171 }
3172
3173 } else {
3174 const uchar *srcPtr = src->data;
3175 uchar *dstPtr = dst->data + (h - 1) * dst->bytes_per_line;
3176 for (int y = 0; y < h; ++y) {
3177 memcpy(dstPtr, srcPtr, data_bytes_per_line);
3178 srcPtr += src->bytes_per_line;
3179 dstPtr -= dst->bytes_per_line;
3180 }
3181 }
3182}
3183
3184inline void do_mirror(QImageData *dst, QImageData *src, bool horizontal, bool vertical)
3185{
3186 Q_ASSERT(src->width == dst->width && src->height == dst->height && src->depth == dst->depth);
3187 int w = src->width;
3188 int h = src->height;
3189 int depth = src->depth;
3190
3191 if (src->depth == 1) {
3192 w = (w + 7) / 8; // byte aligned width
3193 depth = 8;
3194 }
3195
3196 if (vertical && !horizontal) {
3197 // This one is simple and common, so do it a little more optimized
3198 do_flip(dst, src, w, h, depth);
3199 return;
3200 }
3201
3202 int dstX0 = 0, dstXIncr = 1;
3203 int dstY0 = 0, dstYIncr = 1;
3204 if (horizontal) {
3205 // 0 -> w-1, 1 -> w-2, 2 -> w-3, ...
3206 dstX0 = w - 1;
3207 dstXIncr = -1;
3208 }
3209 if (vertical) {
3210 // 0 -> h-1, 1 -> h-2, 2 -> h-3, ...
3211 dstY0 = h - 1;
3212 dstYIncr = -1;
3213 }
3214
3215 switch (depth) {
3216 case 64:
3217 do_mirror_data<quint64>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3218 break;
3219 case 32:
3220 do_mirror_data<quint32>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3221 break;
3222 case 24:
3223 do_mirror_data<quint24>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3224 break;
3225 case 16:
3226 do_mirror_data<quint16>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3227 break;
3228 case 8:
3229 do_mirror_data<quint8>(dst, src, dstX0, dstY0, dstXIncr, dstYIncr, w, h);
3230 break;
3231 default:
3232 Q_ASSERT(false);
3233 break;
3234 }
3235
3236 // The bytes are now all in the correct place. In addition, the bits in the individual
3237 // bytes have to be flipped too when horizontally mirroring a 1 bit-per-pixel image.
3238 if (horizontal && dst->depth == 1) {
3239 Q_ASSERT(dst->format == QImage::Format_Mono || dst->format == QImage::Format_MonoLSB);
3240 const int shift = 8 - (dst->width % 8);
3241 const uchar *bitflip = qt_get_bitflip_array();
3242 for (int y = 0; y < h; ++y) {
3243 uchar *begin = dst->data + y * dst->bytes_per_line;
3244 uchar *end = begin + dst->bytes_per_line;
3245 for (uchar *p = begin; p < end; ++p) {
3246 *p = bitflip[*p];
3247 // When the data is non-byte aligned, an extra bit shift (of the number of
3248 // unused bits at the end) is needed for the entire scanline.
3249 if (shift != 8 && p != begin) {
3250 if (dst->format == QImage::Format_Mono) {
3251 for (int i = 0; i < shift; ++i) {
3252 p[-1] <<= 1;
3253 p[-1] |= (*p & (128 >> i)) >> (7 - i);
3254 }
3255 } else {
3256 for (int i = 0; i < shift; ++i) {
3257 p[-1] >>= 1;
3258 p[-1] |= (*p & (1 << i)) << (7 - i);
3259 }
3260 }
3261 }
3262 }
3263 if (shift != 8) {
3264 if (dst->format == QImage::Format_Mono)
3265 end[-1] <<= shift;
3266 else
3267 end[-1] >>= shift;
3268 }
3269 }
3270 }
3271}
3272
3273/*!
3274 \internal
3275*/
3276QImage QImage::mirrored_helper(bool horizontal, bool vertical) const
3277{
3278 if (!d)
3279 return QImage();
3280
3281 if ((d->width <= 1 && d->height <= 1) || (!horizontal && !vertical))
3282 return *this;
3283
3284 // Create result image, copy colormap
3285 QImage result(d->width, d->height, d->format);
3286 QIMAGE_SANITYCHECK_MEMORY(result);
3287
3288 // check if we ran out of of memory..
3289 if (!result.d)
3290 return QImage();
3291
3292 result.d->colortable = d->colortable;
3293 result.d->has_alpha_clut = d->has_alpha_clut;
3294 copyMetadata(result.d, d);
3295
3296 do_mirror(result.d, d, horizontal, vertical);
3297
3298 return result;
3299}
3300
3301/*!
3302 \internal
3303*/
3304void QImage::mirrored_inplace(bool horizontal, bool vertical)
3305{
3306 if (!d || (d->width <= 1 && d->height <= 1) || (!horizontal && !vertical))
3307 return;
3308
3309 detach();
3310 if (!d)
3311 return;
3312 if (!d->own_data)
3313 *this = copy();
3314
3315 do_mirror(d, d, horizontal, vertical);
3316}
3317
3318/*!
3319 \fn QImage QImage::rgbSwapped() const &
3320 \fn QImage QImage::rgbSwapped() &&
3321
3322 Returns a QImage in which the values of the red and blue
3323 components of all pixels have been swapped, effectively converting
3324 an RGB image to an BGR image.
3325
3326 The original QImage is not changed.
3327
3328 \sa rgbSwap(), {QImage#Image Transformations}{Image Transformations}
3329*/
3330
3331/*!
3332 \fn void QImage::rgbSwap()
3333 \since 6.0
3334
3335 Swaps the values of the red and blue components of all pixels, effectively converting
3336 an RGB image to an BGR image.
3337
3338 \sa rgbSwapped(), {QImage#Image Transformations}{Image Transformations}
3339*/
3340
3341static inline void rgbSwapped_generic(int width, int height, const QImage *src, QImage *dst, const QPixelLayout* layout)
3342{
3343 const RbSwapFunc func = layout->rbSwap;
3344 if (!func) {
3345 qWarning("Trying to rb-swap an image format where it doesn't make sense");
3346 if (src != dst)
3347 *dst = *src;
3348 return;
3349 }
3350
3351 for (int i = 0; i < height; ++i) {
3352 uchar *q = dst->scanLine(i);
3353 const uchar *p = src->constScanLine(i);
3354 func(q, p, width);
3355 }
3356}
3357
3358/*!
3359 \internal
3360*/
3361QImage QImage::rgbSwapped_helper() const
3362{
3363 if (isNull())
3364 return *this;
3365
3366 Q_TRACE_SCOPE(QImage_rgbSwapped_helper);
3367
3368 QImage res;
3369
3370 switch (d->format) {
3371 case Format_Invalid:
3372 case NImageFormats:
3373 Q_ASSERT(false);
3374 break;
3375 case Format_Alpha8:
3376 case Format_Grayscale8:
3377 case Format_Grayscale16:
3378 return *this;
3379 case Format_Mono:
3380 case Format_MonoLSB:
3381 case Format_Indexed8:
3382 res = copy();
3383 for (int i = 0; i < res.d->colortable.size(); i++) {
3384 QRgb c = res.d->colortable.at(i);
3385 res.d->colortable[i] = QRgb(((c << 16) & 0xff0000) | ((c >> 16) & 0xff) | (c & 0xff00ff00));
3386 }
3387 break;
3388 case Format_RGBX8888:
3389 case Format_RGBA8888:
3390 case Format_RGBA8888_Premultiplied:
3391#if Q_BYTE_ORDER == Q_BIG_ENDIAN
3392 res = QImage(d->width, d->height, d->format);
3393 QIMAGE_SANITYCHECK_MEMORY(res);
3394 for (int i = 0; i < d->height; i++) {
3395 uint *q = (uint*)res.scanLine(i);
3396 const uint *p = (const uint*)constScanLine(i);
3397 const uint *end = p + d->width;
3398 while (p < end) {
3399 uint c = *p;
3400 *q = ((c << 16) & 0xff000000) | ((c >> 16) & 0xff00) | (c & 0x00ff00ff);
3401 p++;
3402 q++;
3403 }
3404 }
3405 break;
3406#else
3407 // On little-endian rgba8888 is abgr32 and can use same rgb-swap as argb32
3408 Q_FALLTHROUGH();
3409#endif
3410 case Format_RGB32:
3411 case Format_ARGB32:
3412 case Format_ARGB32_Premultiplied:
3413 res = QImage(d->width, d->height, d->format);
3414 QIMAGE_SANITYCHECK_MEMORY(res);
3415 for (int i = 0; i < d->height; i++) {
3416 uint *q = (uint*)res.scanLine(i);
3417 const uint *p = (const uint*)constScanLine(i);
3418 const uint *end = p + d->width;
3419 while (p < end) {
3420 uint c = *p;
3421 *q = ((c << 16) & 0xff0000) | ((c >> 16) & 0xff) | (c & 0xff00ff00);
3422 p++;
3423 q++;
3424 }
3425 }
3426 break;
3427 case Format_RGB16:
3428 res = QImage(d->width, d->height, d->format);
3429 QIMAGE_SANITYCHECK_MEMORY(res);
3430 for (int i = 0; i < d->height; i++) {
3431 ushort *q = (ushort*)res.scanLine(i);
3432 const ushort *p = (const ushort*)constScanLine(i);
3433 const ushort *end = p + d->width;
3434 while (p < end) {
3435 ushort c = *p;
3436 *q = ((c << 11) & 0xf800) | ((c >> 11) & 0x1f) | (c & 0x07e0);
3437 p++;
3438 q++;
3439 }
3440 }
3441 break;
3442 default:
3443 res = QImage(d->width, d->height, d->format);
3444 QIMAGE_SANITYCHECK_MEMORY(res);
3445 rgbSwapped_generic(d->width, d->height, this, &res, &qPixelLayouts[d->format]);
3446 break;
3447 }
3448 copyMetadata(res.d, d);
3449 return res;
3450}
3451
3452/*!
3453 \internal
3454*/
3455void QImage::rgbSwapped_inplace()
3456{
3457 if (isNull())
3458 return;
3459
3460 detach();
3461 if (!d)
3462 return;
3463 if (!d->own_data)
3464 *this = copy();
3465
3466 switch (d->format) {
3467 case Format_Invalid:
3468 case NImageFormats:
3469 Q_ASSERT(false);
3470 break;
3471 case Format_Alpha8:
3472 case Format_Grayscale8:
3473 case Format_Grayscale16:
3474 return;
3475 case Format_Mono:
3476 case Format_MonoLSB:
3477 case Format_Indexed8:
3478 for (int i = 0; i < d->colortable.size(); i++) {
3479 QRgb c = d->colortable.at(i);
3480 d->colortable[i] = QRgb(((c << 16) & 0xff0000) | ((c >> 16) & 0xff) | (c & 0xff00ff00));
3481 }
3482 break;
3483 case Format_RGBX8888:
3484 case Format_RGBA8888:
3485 case Format_RGBA8888_Premultiplied:
3486#if Q_BYTE_ORDER == Q_BIG_ENDIAN
3487 for (int i = 0; i < d->height; i++) {
3488 uint *p = (uint*)scanLine(i);
3489 uint *end = p + d->width;
3490 while (p < end) {
3491 uint c = *p;
3492 *p = ((c << 16) & 0xff000000) | ((c >> 16) & 0xff00) | (c & 0x00ff00ff);
3493 p++;
3494 }
3495 }
3496 break;
3497#else
3498 // On little-endian rgba8888 is abgr32 and can use same rgb-swap as argb32
3499 Q_FALLTHROUGH();
3500#endif
3501 case Format_RGB32:
3502 case Format_ARGB32:
3503 case Format_ARGB32_Premultiplied:
3504 for (int i = 0; i < d->height; i++) {
3505 uint *p = (uint*)scanLine(i);
3506 uint *end = p + d->width;
3507 while (p < end) {
3508 uint c = *p;
3509 *p = ((c << 16) & 0xff0000) | ((c >> 16) & 0xff) | (c & 0xff00ff00);
3510 p++;
3511 }
3512 }
3513 break;
3514 case Format_RGB16:
3515 for (int i = 0; i < d->height; i++) {
3516 ushort *p = (ushort*)scanLine(i);
3517 ushort *end = p + d->width;
3518 while (p < end) {
3519 ushort c = *p;
3520 *p = ((c << 11) & 0xf800) | ((c >> 11) & 0x1f) | (c & 0x07e0);
3521 p++;
3522 }
3523 }
3524 break;
3525 case Format_BGR30:
3526 case Format_A2BGR30_Premultiplied:
3527 case Format_RGB30:
3528 case Format_A2RGB30_Premultiplied:
3529 for (int i = 0; i < d->height; i++) {
3530 uint *p = (uint*)scanLine(i);
3531 uint *end = p + d->width;
3532 while (p < end) {
3533 *p = qRgbSwapRgb30(*p);
3534 p++;
3535 }
3536 }
3537 break;
3538 default:
3539 rgbSwapped_generic(d->width, d->height, this, this, &qPixelLayouts[d->format]);
3540 break;
3541 }
3542}
3543
3544/*!
3545 Loads an image from the file with the given \a fileName. Returns \c true if
3546 the image was successfully loaded; otherwise invalidates the image
3547 and returns \c false.
3548
3549 The loader attempts to read the image using the specified \a format, e.g.,
3550 PNG or JPG. If \a format is not specified (which is the default), it is
3551 auto-detected based on the file's suffix and header. For details, see
3552 QImageReader::setAutoDetectImageFormat().
3553
3554 The file name can either refer to an actual file on disk or to one
3555 of the application's embedded resources. See the
3556 \l{resources.html}{Resource System} overview for details on how to
3557 embed images and other resource files in the application's
3558 executable.
3559
3560 \sa {QImage#Reading and Writing Image Files}{Reading and Writing Image Files}
3561*/
3562
3563bool QImage::load(const QString &fileName, const char* format)
3564{
3565 *this = QImageReader(fileName, format).read();
3566 return !isNull();
3567}
3568
3569/*!
3570 \overload
3571
3572 This function reads a QImage from the given \a device. This can,
3573 for example, be used to load an image directly into a QByteArray.
3574*/
3575
3576bool QImage::load(QIODevice* device, const char* format)
3577{
3578 *this = QImageReader(device, format).read();
3579 return !isNull();
3580}
3581
3582/*!
3583 \fn bool QImage::loadFromData(const uchar *data, int len, const char *format)
3584
3585 Loads an image from the first \a len bytes of the given binary \a
3586 data. Returns \c true if the image was successfully loaded; otherwise
3587 invalidates the image and returns \c false.
3588
3589 The loader attempts to read the image using the specified \a format, e.g.,
3590 PNG or JPG. If \a format is not specified (which is the default), the
3591 loader probes the file for a header to guess the file format.
3592
3593 \sa {QImage#Reading and Writing Image Files}{Reading and Writing Image Files}
3594*/
3595
3596bool QImage::loadFromData(const uchar *data, int len, const char *format)
3597{
3598 *this = fromData(data, len, format);
3599 return !isNull();
3600}
3601
3602/*!
3603 \fn bool QImage::loadFromData(const QByteArray &data, const char *format)
3604
3605 \overload
3606
3607 Loads an image from the given QByteArray \a data.
3608*/
3609
3610/*!
3611 \fn QImage QImage::fromData(const uchar *data, int size, const char *format)
3612
3613 Constructs a QImage from the first \a size bytes of the given
3614 binary \a data. The loader attempts to read the image using the
3615 specified \a format. If \a format is not specified (which is the default),
3616 the loader probes the data for a header to guess the file format.
3617
3618 If \a format is specified, it must be one of the values returned by
3619 QImageReader::supportedImageFormats().
3620
3621 If the loading of the image fails, the image returned will be a null image.
3622
3623 \sa load(), save(), {QImage#Reading and Writing Image Files}{Reading and Writing Image Files}
3624 */
3625
3626QImage QImage::fromData(const uchar *data, int size, const char *format)
3627{
3628 QByteArray a = QByteArray::fromRawData(reinterpret_cast<const char *>(data), size);
3629 QBuffer b;
3630 b.setData(a);
3631 b.open(QIODevice::ReadOnly);
3632 return QImageReader(&b, format).read();
3633}
3634
3635/*!
3636 \fn QImage QImage::fromData(const QByteArray &data, const char *format)
3637
3638 \overload
3639
3640 Loads an image from the given QByteArray \a data.
3641*/
3642
3643/*!
3644 Saves the image to the file with the given \a fileName, using the
3645 given image file \a format and \a quality factor. If \a format is
3646 \nullptr, QImage will attempt to guess the format by looking at
3647 \a fileName's suffix.
3648
3649 The \a quality factor must be in the range 0 to 100 or -1. Specify
3650 0 to obtain small compressed files, 100 for large uncompressed
3651 files, and -1 (the default) to use the default settings.
3652
3653 Returns \c true if the image was successfully saved; otherwise
3654 returns \c false.
3655
3656 \sa {QImage#Reading and Writing Image Files}{Reading and Writing
3657 Image Files}
3658*/
3659bool QImage::save(const QString &fileName, const char *format, int quality) const
3660{
3661 if (isNull())
3662 return false;
3663 QImageWriter writer(fileName, format);
3664 return d->doImageIO(this, &writer, quality);
3665}
3666
3667/*!
3668 \overload
3669
3670 This function writes a QImage to the given \a device.
3671
3672 This can, for example, be used to save an image directly into a
3673 QByteArray:
3674
3675 \snippet image/image.cpp 0
3676*/
3677
3678bool QImage::save(QIODevice* device, const char* format, int quality) const
3679{
3680 if (isNull())
3681 return false; // nothing to save
3682 QImageWriter writer(device, format);
3683 return d->doImageIO(this, &writer, quality);
3684}
3685
3686/* \internal
3687*/
3688
3689bool QImageData::doImageIO(const QImage *image, QImageWriter *writer, int quality) const
3690{
3691 if (quality > 100 || quality < -1)
3692 qWarning("QPixmap::save: Quality out of range [-1, 100]");
3693 if (quality >= 0)
3694 writer->setQuality(qMin(quality,100));
3695 return writer->write(*image);
3696}
3697
3698/*****************************************************************************
3699 QImage stream functions
3700 *****************************************************************************/
3701#if !defined(QT_NO_DATASTREAM)
3702/*!
3703 \fn QDataStream &operator<<(QDataStream &stream, const QImage &image)
3704 \relates QImage
3705
3706 Writes the given \a image to the given \a stream as a PNG image,
3707 or as a BMP image if the stream's version is 1. Note that writing
3708 the stream to a file will not produce a valid image file.
3709
3710 \sa QImage::save(), {Serializing Qt Data Types}
3711*/
3712
3713QDataStream &operator<<(QDataStream &s, const QImage &image)
3714{
3715 if (s.version() >= 5) {
3716 if (image.isNull()) {
3717 s << (qint32) 0; // null image marker
3718 return s;
3719 } else {
3720 s << (qint32) 1;
3721 // continue ...
3722 }
3723 }
3724 QImageWriter writer(s.device(), s.version() == 1 ? "bmp" : "png");
3725 writer.write(image);
3726 return s;
3727}
3728
3729/*!
3730 \fn QDataStream &operator>>(QDataStream &stream, QImage &image)
3731 \relates QImage
3732
3733 Reads an image from the given \a stream and stores it in the given
3734 \a image.
3735
3736 \sa QImage::load(), {Serializing Qt Data Types}
3737*/
3738
3739QDataStream &operator>>(QDataStream &s, QImage &image)
3740{
3741 if (s.version() >= 5) {
3742 qint32 nullMarker;
3743 s >> nullMarker;
3744 if (!nullMarker) {
3745 image = QImage(); // null image
3746 return s;
3747 }
3748 }
3749 image = QImageReader(s.device(), s.version() == 1 ? "bmp" : "png").read();
3750 if (image.isNull() && s.version() >= 5)
3751 s.setStatus(QDataStream::ReadPastEnd);
3752 return s;
3753}
3754#endif // QT_NO_DATASTREAM
3755
3756
3757
3758/*!
3759 \fn bool QImage::operator==(const QImage & image) const
3760
3761 Returns \c true if this image and the given \a image have the same
3762 contents; otherwise returns \c false.
3763
3764 The comparison can be slow, unless there is some obvious
3765 difference (e.g. different size or format), in which case the
3766 function will return quickly.
3767
3768 \sa operator=()
3769*/
3770
3771bool QImage::operator==(const QImage & i) const
3772{
3773 // same object, or shared?
3774 if (i.d == d)
3775 return true;
3776 if (!i.d || !d)
3777 return false;
3778
3779 // obviously different stuff?
3780 if (i.d->height != d->height || i.d->width != d->width || i.d->format != d->format)
3781 return false;
3782
3783 if (d->format != Format_RGB32) {
3784 if (d->format >= Format_ARGB32) { // all bits defined
3785 const int n = d->width * d->depth / 8;
3786 if (n == d->bytes_per_line && n == i.d->bytes_per_line) {
3787 if (memcmp(bits(), i.bits(), d->nbytes))
3788 return false;
3789 } else {
3790 for (int y = 0; y < d->height; ++y) {
3791 if (memcmp(scanLine(y), i.scanLine(y), n))
3792 return false;
3793 }
3794 }
3795 } else {
3796 const int w = width();
3797 const int h = height();
3798 const QList<QRgb> &colortable = d->colortable;
3799 const QList<QRgb> &icolortable = i.d->colortable;
3800 for (int y=0; y<h; ++y) {
3801 for (int x=0; x<w; ++x) {
3802 if (colortable[pixelIndex(x, y)] != icolortable[i.pixelIndex(x, y)])
3803 return false;
3804 }
3805 }
3806 }
3807 } else {
3808 //alpha channel undefined, so we must mask it out
3809 for(int l = 0; l < d->height; l++) {
3810 int w = d->width;
3811 const uint *p1 = reinterpret_cast<const uint*>(scanLine(l));
3812 const uint *p2 = reinterpret_cast<const uint*>(i.scanLine(l));
3813 while (w--) {
3814 if ((*p1++ & 0x00ffffff) != (*p2++ & 0x00ffffff))
3815 return false;
3816 }
3817 }
3818 }
3819 return true;
3820}
3821
3822
3823/*!
3824 \fn bool QImage::operator!=(const QImage & image) const
3825
3826 Returns \c true if this image and the given \a image have different
3827 contents; otherwise returns \c false.
3828
3829 The comparison can be slow, unless there is some obvious
3830 difference, such as different widths, in which case the function
3831 will return quickly.
3832
3833 \sa operator=()
3834*/
3835
3836bool QImage::operator!=(const QImage & i) const
3837{
3838 return !(*this == i);
3839}
3840
3841
3842
3843
3844/*!
3845 Returns the number of pixels that fit horizontally in a physical
3846 meter. Together with dotsPerMeterY(), this number defines the
3847 intended scale and aspect ratio of the image.
3848
3849 \sa setDotsPerMeterX(), {QImage#Image Information}{Image
3850 Information}
3851*/
3852int QImage::dotsPerMeterX() const
3853{
3854 return d ? qRound(d->dpmx) : 0;
3855}
3856
3857/*!
3858 Returns the number of pixels that fit vertically in a physical
3859 meter. Together with dotsPerMeterX(), this number defines the
3860 intended scale and aspect ratio of the image.
3861
3862 \sa setDotsPerMeterY(), {QImage#Image Information}{Image
3863 Information}
3864*/
3865int QImage::dotsPerMeterY() const
3866{
3867 return d ? qRound(d->dpmy) : 0;
3868}
3869
3870/*!
3871 Sets the number of pixels that fit horizontally in a physical
3872 meter, to \a x.
3873
3874 Together with dotsPerMeterY(), this number defines the intended
3875 scale and aspect ratio of the image, and determines the scale
3876 at which QPainter will draw graphics on the image. It does not
3877 change the scale or aspect ratio of the image when it is rendered
3878 on other paint devices.
3879
3880 \sa dotsPerMeterX(), {QImage#Image Information}{Image Information}
3881*/
3882void QImage::setDotsPerMeterX(int x)
3883{
3884 if (!d || !x)
3885 return;
3886 detach();
3887
3888 if (d)
3889 d->dpmx = x;
3890}
3891
3892/*!
3893 Sets the number of pixels that fit vertically in a physical meter,
3894 to \a y.
3895
3896 Together with dotsPerMeterX(), this number defines the intended
3897 scale and aspect ratio of the image, and determines the scale
3898 at which QPainter will draw graphics on the image. It does not
3899 change the scale or aspect ratio of the image when it is rendered
3900 on other paint devices.
3901
3902 \sa dotsPerMeterY(), {QImage#Image Information}{Image Information}
3903*/
3904void QImage::setDotsPerMeterY(int y)
3905{
3906 if (!d || !y)
3907 return;
3908 detach();
3909
3910 if (d)
3911 d->dpmy = y;
3912}
3913
3914/*!
3915 \fn QPoint QImage::offset() const
3916
3917 Returns the number of pixels by which the image is intended to be
3918 offset by when positioning relative to other images.
3919
3920 \sa setOffset(), {QImage#Image Information}{Image Information}
3921*/
3922QPoint QImage::offset() const
3923{
3924 return d ? d->offset : QPoint();
3925}
3926
3927
3928/*!
3929 \fn void QImage::setOffset(const QPoint& offset)
3930
3931 Sets the number of pixels by which the image is intended to be
3932 offset by when positioning relative to other images, to \a offset.
3933
3934 \sa offset(), {QImage#Image Information}{Image Information}
3935*/
3936void QImage::setOffset(const QPoint& p)
3937{
3938 if (!d)
3939 return;
3940 detach();
3941
3942 if (d)
3943 d->offset = p;
3944}
3945
3946/*!
3947 Returns the text keys for this image.
3948
3949 You can use these keys with text() to list the image text for a
3950 certain key.
3951
3952 \sa text()
3953*/
3954QStringList QImage::textKeys() const
3955{
3956 return d ? QStringList(d->text.keys()) : QStringList();
3957}
3958
3959/*!
3960 Returns the image text associated with the given \a key. If the
3961 specified \a key is an empty string, the whole image text is
3962 returned, with each key-text pair separated by a newline.
3963
3964 \sa setText(), textKeys()
3965*/
3966QString QImage::text(const QString &key) const
3967{
3968 if (!d)
3969 return QString();
3970
3971 if (!key.isEmpty())
3972 return d->text.value(key);
3973
3974 QString tmp;
3975 for (auto it = d->text.begin(), end = d->text.end(); it != end; ++it)
3976 tmp += it.key() + QLatin1String(": ") + it.value().simplified() + QLatin1String("\n\n");
3977 if (!tmp.isEmpty())
3978 tmp.chop(2); // remove final \n\n
3979 return tmp;
3980}
3981
3982/*!
3983 \fn void QImage::setText(const QString &key, const QString &text)
3984
3985 Sets the image text to the given \a text and associate it with the
3986 given \a key.
3987
3988 If you just want to store a single text block (i.e., a "comment"
3989 or just a description), you can either pass an empty key, or use a
3990 generic key like "Description".
3991
3992 The image text is embedded into the image data when you
3993 call save() or QImageWriter::write().
3994
3995 Not all image formats support embedded text. You can find out
3996 if a specific image or format supports embedding text
3997 by using QImageWriter::supportsOption(). We give an example:
3998
3999 \snippet image/supportedformat.cpp 0
4000
4001 You can use QImageWriter::supportedImageFormats() to find out
4002 which image formats are available to you.
4003
4004 \sa text(), textKeys()
4005*/
4006void QImage::setText(const QString &key, const QString &value)
4007{
4008 if (!d)
4009 return;
4010 detach();
4011
4012 if (d)
4013 d->text.insert(key, value);
4014}
4015
4016/*!
4017 \internal
4018
4019 Used by QPainter to retrieve a paint engine for the image.
4020*/
4021QPaintEngine *QImage::paintEngine() const
4022{
4023 if (!d)
4024 return nullptr;
4025
4026 if (!d->paintEngine) {
4027 QPaintDevice *paintDevice = const_cast<QImage *>(this);
4028 QPlatformIntegration *platformIntegration = QGuiApplicationPrivate::platformIntegration();
4029 if (platformIntegration)
4030 d->paintEngine = platformIntegration->createImagePaintEngine(paintDevice);
4031 if (!d->paintEngine)
4032 d->paintEngine = new QRasterPaintEngine(paintDevice);
4033 }
4034
4035 return d->paintEngine;
4036}
4037
4038
4039/*!
4040 \internal
4041
4042 Returns the size for the specified \a metric on the device.
4043*/
4044int QImage::metric(PaintDeviceMetric metric) const
4045{
4046 if (!d)
4047 return 0;
4048
4049 switch (metric) {
4050 case PdmWidth:
4051 return d->width;
4052
4053 case PdmHeight:
4054 return d->height;
4055
4056 case PdmWidthMM:
4057 return qRound(d->width * 1000 / d->dpmx);
4058
4059 case PdmHeightMM:
4060 return qRound(d->height * 1000 / d->dpmy);
4061
4062 case PdmNumColors:
4063 return d->colortable.size();
4064
4065 case PdmDepth:
4066 return d->depth;
4067
4068 case PdmDpiX:
4069 return qRound(d->dpmx * 0.0254);
4070 break;
4071
4072 case PdmDpiY:
4073 return qRound(d->dpmy * 0.0254);
4074 break;
4075
4076 case PdmPhysicalDpiX:
4077 return qRound(d->dpmx * 0.0254);
4078 break;
4079
4080 case PdmPhysicalDpiY:
4081 return qRound(d->dpmy * 0.0254);
4082 break;
4083
4084 case PdmDevicePixelRatio:
4085 return d->devicePixelRatio;
4086 break;
4087
4088 case PdmDevicePixelRatioScaled:
4089 return d->devicePixelRatio * QPaintDevice::devicePixelRatioFScale();
4090 break;
4091
4092 default:
4093 qWarning("QImage::metric(): Unhandled metric type %d", metric);
4094 break;
4095 }
4096 return 0;
4097}
4098
4099
4100
4101/*****************************************************************************
4102 QPixmap (and QImage) helper functions
4103 *****************************************************************************/
4104/*
4105 This internal function contains the common (i.e. platform independent) code
4106 to do a transformation of pixel data. It is used by QPixmap::transform() and by
4107 QImage::transform().
4108
4109 \a trueMat is the true transformation matrix (see QPixmap::trueMatrix()) and
4110 \a xoffset is an offset to the matrix.
4111
4112 \a msbfirst specifies for 1bpp images, if the MSB or LSB comes first and \a
4113 depth specifies the colordepth of the data.
4114
4115 \a dptr is a pointer to the destination data, \a dbpl specifies the bits per
4116 line for the destination data, \a p_inc is the offset that we advance for
4117 every scanline and \a dHeight is the height of the destination image.
4118
4119 \a sprt is the pointer to the source data, \a sbpl specifies the bits per
4120 line of the source data, \a sWidth and \a sHeight are the width and height of
4121 the source data.
4122*/
4123
4124#undef IWX_MSB
4125#define IWX_MSB(b) if (trigx < maxws && trigy < maxhs) { \
4126 if (*(sptr+sbpl*(trigy>>12)+(trigx>>15)) & \
4127 (1 << (7-((trigx>>12)&7)))) \
4128 *dptr |= b; \
4129 } \
4130 trigx += m11; \
4131 trigy += m12;
4132 // END OF MACRO
4133#undef IWX_LSB
4134#define IWX_LSB(b) if (trigx < maxws && trigy < maxhs) { \
4135 if (*(sptr+sbpl*(trigy>>12)+(trigx>>15)) & \
4136 (1 << ((trigx>>12)&7))) \
4137 *dptr |= b; \
4138 } \
4139 trigx += m11; \
4140 trigy += m12;
4141 // END OF MACRO
4142#undef IWX_PIX
4143#define IWX_PIX(b) if (trigx < maxws && trigy < maxhs) { \
4144 if ((*(sptr+sbpl*(trigy>>12)+(trigx>>15)) & \
4145 (1 << (7-((trigx>>12)&7)))) == 0) \
4146 *dptr &= ~b; \
4147 } \
4148 trigx += m11; \
4149 trigy += m12;
4150 // END OF MACRO
4151bool qt_xForm_helper(const QTransform &trueMat, int xoffset, int type, int depth,
4152 uchar *dptr, qsizetype dbpl, int p_inc, int dHeight,
4153 const uchar *sptr, qsizetype sbpl, int sWidth, int sHeight)
4154{
4155 int m11 = int(trueMat.m11()*4096.0);
4156 int m12 = int(trueMat.m12()*4096.0);
4157 int m21 = int(trueMat.m21()*4096.0);
4158 int m22 = int(trueMat.m22()*4096.0);
4159 int dx = qRound(trueMat.dx()*4096.0);
4160 int dy = qRound(trueMat.dy()*4096.0);
4161
4162 int m21ydx = dx + (xoffset<<16) + (m11 + m21) / 2;
4163 int m22ydy = dy + (m12 + m22) / 2;
4164 uint trigx;
4165 uint trigy;
4166 uint maxws = sWidth<<12;
4167 uint maxhs = sHeight<<12;
4168
4169 for (int y=0; y<dHeight; y++) { // for each target scanline
4170 trigx = m21ydx;
4171 trigy = m22ydy;
4172 uchar *maxp = dptr + dbpl;
4173 if (depth != 1) {
4174 switch (depth) {
4175 case 8: // 8 bpp transform
4176 while (dptr < maxp) {
4177 if (trigx < maxws && trigy < maxhs)
4178 *dptr = *(sptr+sbpl*(trigy>>12)+(trigx>>12));
4179