1/****************************************************************************
2**
3** Copyright (C) 2016 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 <qglobal.h>
41
42#include "qpixmap.h"
43#include <qpa/qplatformpixmap.h>
44#include "qimagepixmapcleanuphooks_p.h"
45
46#include "qbitmap.h"
47#include "qimage.h"
48#include "qpainter.h"
49#include "qdatastream.h"
50#include "qbuffer.h"
51#include <private/qguiapplication_p.h>
52#include "qevent.h"
53#include "qfile.h"
54#include "qfileinfo.h"
55#include "qpixmapcache.h"
56#include "qdatetime.h"
57#include "qimagereader.h"
58#include "qimagewriter.h"
59#include "qpaintengine.h"
60#include "qscreen.h"
61#include "qthread.h"
62#include "qdebug.h"
63
64#include <qpa/qplatformintegration.h>
65
66#include "qpixmap_raster_p.h"
67#include "private/qhexstring_p.h"
68
69QT_BEGIN_NAMESPACE
70
71static bool qt_pixmap_thread_test()
72{
73 if (Q_UNLIKELY(!QCoreApplication::instance())) {
74 qFatal("QPixmap: Must construct a QGuiApplication before a QPixmap");
75 return false;
76 }
77
78 if (qApp->thread() != QThread::currentThread()) {
79 bool fail = false;
80 if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedPixmaps)) {
81 printf("Lighthouse plugin does not support threaded pixmaps!\n");
82 fail = true;
83 }
84 if (fail) {
85 qWarning("QPixmap: It is not safe to use pixmaps outside the GUI thread");
86 return false;
87 }
88 }
89 return true;
90}
91
92void QPixmap::doInit(int w, int h, int type)
93{
94 if ((w > 0 && h > 0) || type == QPlatformPixmap::BitmapType)
95 data = QPlatformPixmap::create(w, h, (QPlatformPixmap::PixelType) type);
96 else
97 data = 0;
98}
99
100/*!
101 Constructs a null pixmap.
102
103 \sa isNull()
104*/
105
106QPixmap::QPixmap()
107 : QPaintDevice()
108{
109 (void) qt_pixmap_thread_test();
110 doInit(0, 0, QPlatformPixmap::PixmapType);
111}
112
113/*!
114 \fn QPixmap::QPixmap(int width, int height)
115
116 Constructs a pixmap with the given \a width and \a height. If
117 either \a width or \a height is zero, a null pixmap is
118 constructed.
119
120 \warning This will create a QPixmap with uninitialized data. Call
121 fill() to fill the pixmap with an appropriate color before drawing
122 onto it with QPainter.
123
124 \sa isNull()
125*/
126
127QPixmap::QPixmap(int w, int h)
128 : QPixmap(QSize(w, h))
129{
130}
131
132/*!
133 \overload
134
135 Constructs a pixmap of the given \a size.
136
137 \warning This will create a QPixmap with uninitialized data. Call
138 fill() to fill the pixmap with an appropriate color before drawing
139 onto it with QPainter.
140*/
141
142QPixmap::QPixmap(const QSize &size)
143 : QPixmap(size, QPlatformPixmap::PixmapType)
144{
145}
146
147/*!
148 \internal
149*/
150QPixmap::QPixmap(const QSize &s, int type)
151{
152 if (!qt_pixmap_thread_test())
153 doInit(0, 0, static_cast<QPlatformPixmap::PixelType>(type));
154 else
155 doInit(s.width(), s.height(), static_cast<QPlatformPixmap::PixelType>(type));
156}
157
158/*!
159 \internal
160*/
161QPixmap::QPixmap(QPlatformPixmap *d)
162 : QPaintDevice(), data(d)
163{
164}
165
166/*!
167 Constructs a pixmap from the file with the given \a fileName. If the
168 file does not exist or is of an unknown format, the pixmap becomes a
169 null pixmap.
170
171 The loader attempts to read the pixmap using the specified \a
172 format. If the \a format is not specified (which is the default),
173 the loader probes the file for a header to guess the file format.
174
175 The file name can either refer to an actual file on disk or to
176 one of the application's embedded resources. See the
177 \l{resources.html}{Resource System} overview for details on how
178 to embed images and other resource files in the application's
179 executable.
180
181 If the image needs to be modified to fit in a lower-resolution
182 result (e.g. converting from 32-bit to 8-bit), use the \a
183 flags to control the conversion.
184
185 The \a fileName, \a format and \a flags parameters are
186 passed on to load(). This means that the data in \a fileName is
187 not compiled into the binary. If \a fileName contains a relative
188 path (e.g. the filename only) the relevant file must be found
189 relative to the runtime working directory.
190
191 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
192 Image Files}
193*/
194
195QPixmap::QPixmap(const QString& fileName, const char *format, Qt::ImageConversionFlags flags)
196 : QPaintDevice()
197{
198 doInit(0, 0, QPlatformPixmap::PixmapType);
199 if (!qt_pixmap_thread_test())
200 return;
201
202 load(fileName, format, flags);
203}
204
205/*!
206 Constructs a pixmap that is a copy of the given \a pixmap.
207
208 \sa copy()
209*/
210
211QPixmap::QPixmap(const QPixmap &pixmap)
212 : QPaintDevice()
213{
214 if (!qt_pixmap_thread_test()) {
215 doInit(0, 0, QPlatformPixmap::PixmapType);
216 return;
217 }
218 if (pixmap.paintingActive()) { // make a deep copy
219 pixmap.copy().swap(*this);
220 } else {
221 data = pixmap.data;
222 }
223}
224
225/*!
226 Constructs a pixmap from the given \a xpm data, which must be a
227 valid XPM image.
228
229 Errors are silently ignored.
230
231 Note that it's possible to squeeze the XPM variable a little bit
232 by using an unusual declaration:
233
234 \snippet code/src_gui_image_qpixmap.cpp 0
235
236 The extra \c const makes the entire definition read-only, which is
237 slightly more efficient (for example, when the code is in a shared
238 library) and ROMable when the application is to be stored in ROM.
239*/
240#ifndef QT_NO_IMAGEFORMAT_XPM
241QPixmap::QPixmap(const char * const xpm[])
242 : QPaintDevice()
243{
244 doInit(0, 0, QPlatformPixmap::PixmapType);
245 if (!xpm)
246 return;
247
248 QImage image(xpm);
249 if (!image.isNull()) {
250 if (data && data->pixelType() == QPlatformPixmap::BitmapType)
251 *this = QBitmap::fromImage(std::move(image));
252 else
253 *this = fromImage(std::move(image));
254 }
255}
256#endif
257
258
259/*!
260 Destroys the pixmap.
261*/
262
263QPixmap::~QPixmap()
264{
265 Q_ASSERT(!data || data->ref.loadRelaxed() >= 1); // Catch if ref-counting changes again
266}
267
268/*!
269 \internal
270*/
271int QPixmap::devType() const
272{
273 return QInternal::Pixmap;
274}
275
276/*!
277 \fn QPixmap QPixmap::copy(int x, int y, int width, int height) const
278 \overload
279
280 Returns a deep copy of the subset of the pixmap that is specified
281 by the rectangle QRect( \a x, \a y, \a width, \a height).
282*/
283
284/*!
285 \fn QPixmap QPixmap::copy(const QRect &rectangle) const
286
287 Returns a deep copy of the subset of the pixmap that is specified
288 by the given \a rectangle. For more information on deep copies,
289 see the \l {Implicit Data Sharing} documentation.
290
291 If the given \a rectangle is empty, the whole image is copied.
292
293 \sa operator=(), QPixmap(), {QPixmap#Pixmap
294 Transformations}{Pixmap Transformations}
295*/
296QPixmap QPixmap::copy(const QRect &rect) const
297{
298 if (isNull())
299 return QPixmap();
300
301 QRect r(0, 0, width(), height());
302 if (!rect.isEmpty())
303 r = r.intersected(rect);
304
305 QPlatformPixmap *d = data->createCompatiblePlatformPixmap();
306 d->copy(data.data(), r);
307 return QPixmap(d);
308}
309
310/*!
311 \fn QPixmap::scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed)
312 \since 4.6
313
314 This convenience function is equivalent to calling QPixmap::scroll(\a dx,
315 \a dy, QRect(\a x, \a y, \a width, \a height), \a exposed).
316
317 \sa QWidget::scroll(), QGraphicsItem::scroll()
318*/
319
320/*!
321 \since 4.6
322
323 Scrolls the area \a rect of this pixmap by (\a dx, \a dy). The exposed
324 region is left unchanged. You can optionally pass a pointer to an empty
325 QRegion to get the region that is \a exposed by the scroll operation.
326
327 \snippet code/src_gui_image_qpixmap.cpp 2
328
329 You cannot scroll while there is an active painter on the pixmap.
330
331 \sa QWidget::scroll(), QGraphicsItem::scroll()
332*/
333void QPixmap::scroll(int dx, int dy, const QRect &rect, QRegion *exposed)
334{
335 if (isNull() || (dx == 0 && dy == 0))
336 return;
337 QRect dest = rect & this->rect();
338 QRect src = dest.translated(-dx, -dy) & dest;
339 if (src.isEmpty()) {
340 if (exposed)
341 *exposed += dest;
342 return;
343 }
344
345 detach();
346
347 if (!data->scroll(dx, dy, src)) {
348 // Fallback
349 QPixmap pix = *this;
350 QPainter painter(&pix);
351 painter.setCompositionMode(QPainter::CompositionMode_Source);
352 painter.drawPixmap(src.translated(dx, dy), *this, src);
353 painter.end();
354 *this = pix;
355 }
356
357 if (exposed) {
358 *exposed += dest;
359 *exposed -= src.translated(dx, dy);
360 }
361}
362
363/*!
364 Assigns the given \a pixmap to this pixmap and returns a reference
365 to this pixmap.
366
367 \sa copy(), QPixmap()
368*/
369
370QPixmap &QPixmap::operator=(const QPixmap &pixmap)
371{
372 if (paintingActive()) {
373 qWarning("QPixmap::operator=: Cannot assign to pixmap during painting");
374 return *this;
375 }
376 if (pixmap.paintingActive()) { // make a deep copy
377 pixmap.copy().swap(*this);
378 } else {
379 data = pixmap.data;
380 }
381 return *this;
382}
383
384/*!
385 \fn QPixmap &QPixmap::operator=(QPixmap &&other)
386
387 Move-assigns \a other to this QPixmap instance.
388
389 \since 5.2
390*/
391
392/*!
393 \fn void QPixmap::swap(QPixmap &other)
394 \since 4.8
395
396 Swaps pixmap \a other with this pixmap. This operation is very
397 fast and never fails.
398*/
399
400/*!
401 Returns the pixmap as a QVariant.
402*/
403QPixmap::operator QVariant() const
404{
405 return QVariant(QVariant::Pixmap, this);
406}
407
408/*!
409 \fn bool QPixmap::operator!() const
410
411 Returns \c true if this is a null pixmap; otherwise returns \c false.
412
413 \sa isNull()
414*/
415
416/*!
417 Converts the pixmap to a QImage. Returns a null image if the
418 conversion fails.
419
420 If the pixmap has 1-bit depth, the returned image will also be 1
421 bit deep. Images with more bits will be returned in a format
422 closely represents the underlying system. Usually this will be
423 QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha and
424 QImage::Format_RGB32 or QImage::Format_RGB16 for pixmaps without
425 alpha.
426
427 Note that for the moment, alpha masks on monochrome images are
428 ignored.
429
430 \sa fromImage(), {QImage#Image Formats}{Image Formats}
431*/
432QImage QPixmap::toImage() const
433{
434 if (isNull())
435 return QImage();
436
437 return data->toImage();
438}
439
440/*!
441 \fn QMatrix QPixmap::trueMatrix(const QTransform &matrix, int width, int height)
442
443 Returns the actual matrix used for transforming a pixmap with the
444 given \a width, \a height and \a matrix.
445
446 When transforming a pixmap using the transformed() function, the
447 transformation matrix is internally adjusted to compensate for
448 unwanted translation, i.e. transformed() returns the smallest
449 pixmap containing all transformed points of the original
450 pixmap. This function returns the modified matrix, which maps
451 points correctly from the original pixmap into the new pixmap.
452
453 \sa transformed(), {QPixmap#Pixmap Transformations}{Pixmap
454 Transformations}
455*/
456QTransform QPixmap::trueMatrix(const QTransform &m, int w, int h)
457{
458 return QImage::trueMatrix(m, w, h);
459}
460
461/*!
462 \overload
463
464 This convenience function loads the matrix \a m into a
465 QTransform and calls the overloaded function with the
466 QTransform and the width \a w and the height \a h.
467 */
468QMatrix QPixmap::trueMatrix(const QMatrix &m, int w, int h)
469{
470 return trueMatrix(QTransform(m), w, h).toAffine();
471}
472
473
474/*!
475 \fn bool QPixmap::isQBitmap() const
476
477 Returns \c true if this is a QBitmap; otherwise returns \c false.
478*/
479
480bool QPixmap::isQBitmap() const
481{
482 return data && data->type == QPlatformPixmap::BitmapType;
483}
484
485/*!
486 \fn bool QPixmap::isNull() const
487
488 Returns \c true if this is a null pixmap; otherwise returns \c false.
489
490 A null pixmap has zero width, zero height and no contents. You
491 cannot draw in a null pixmap.
492*/
493bool QPixmap::isNull() const
494{
495 return !data || data->isNull();
496}
497
498/*!
499 \fn int QPixmap::width() const
500
501 Returns the width of the pixmap.
502
503 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
504*/
505int QPixmap::width() const
506{
507 return data ? data->width() : 0;
508}
509
510/*!
511 \fn int QPixmap::height() const
512
513 Returns the height of the pixmap.
514
515 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
516*/
517int QPixmap::height() const
518{
519 return data ? data->height() : 0;
520}
521
522/*!
523 \fn QSize QPixmap::size() const
524
525 Returns the size of the pixmap.
526
527 \sa width(), height(), {QPixmap#Pixmap Information}{Pixmap
528 Information}
529*/
530QSize QPixmap::size() const
531{
532 return data ? QSize(data->width(), data->height()) : QSize(0, 0);
533}
534
535/*!
536 \fn QRect QPixmap::rect() const
537
538 Returns the pixmap's enclosing rectangle.
539
540 \sa {QPixmap#Pixmap Information}{Pixmap Information}
541*/
542QRect QPixmap::rect() const
543{
544 return data ? QRect(0, 0, data->width(), data->height()) : QRect();
545}
546
547/*!
548 \fn int QPixmap::depth() const
549
550 Returns the depth of the pixmap.
551
552 The pixmap depth is also called bits per pixel (bpp) or bit planes
553 of a pixmap. A null pixmap has depth 0.
554
555 \sa defaultDepth(), {QPixmap#Pixmap Information}{Pixmap
556 Information}
557*/
558int QPixmap::depth() const
559{
560 return data ? data->depth() : 0;
561}
562
563/*!
564 Sets a mask bitmap.
565
566 This function merges the \a mask with the pixmap's alpha channel. A pixel
567 value of 1 on the mask means the pixmap's pixel is unchanged; a value of 0
568 means the pixel is transparent. The mask must have the same size as this
569 pixmap.
570
571 Setting a null mask resets the mask, leaving the previously transparent
572 pixels black. The effect of this function is undefined when the pixmap is
573 being painted on.
574
575 \warning This is potentially an expensive operation.
576
577 \sa mask(), {QPixmap#Pixmap Transformations}{Pixmap Transformations},
578 QBitmap
579*/
580void QPixmap::setMask(const QBitmap &mask)
581{
582 if (paintingActive()) {
583 qWarning("QPixmap::setMask: Cannot set mask while pixmap is being painted on");
584 return;
585 }
586
587 if (!mask.isNull() && mask.size() != size()) {
588 qWarning("QPixmap::setMask() mask size differs from pixmap size");
589 return;
590 }
591
592 if (isNull())
593 return;
594
595 if (static_cast<const QPixmap &>(mask).data == data) // trying to selfmask
596 return;
597
598 detach();
599 data->setMask(mask);
600}
601
602/*!
603 Returns the device pixel ratio for the pixmap. This is the
604 ratio between \e{device pixels} and \e{device independent pixels}.
605
606 Use this function when calculating layout geometry based on
607 the pixmap size: QSize layoutSize = image.size() / image.devicePixelRatio()
608
609 The default value is 1.0.
610
611 \sa setDevicePixelRatio(), QImageReader
612*/
613qreal QPixmap::devicePixelRatio() const
614{
615 if (!data)
616 return qreal(1.0);
617 return data->devicePixelRatio();
618}
619
620/*!
621 Sets the device pixel ratio for the pixmap. This is the
622 ratio between image pixels and device-independent pixels.
623
624 The default \a scaleFactor is 1.0. Setting it to something else has
625 two effects:
626
627 QPainters that are opened on the pixmap will be scaled. For
628 example, painting on a 200x200 image if with a ratio of 2.0
629 will result in effective (device-independent) painting bounds
630 of 100x100.
631
632 Code paths in Qt that calculate layout geometry based on the
633 pixmap size will take the ratio into account:
634 QSize layoutSize = pixmap.size() / pixmap.devicePixelRatio()
635 The net effect of this is that the pixmap is displayed as
636 high-DPI pixmap rather than a large pixmap
637 (see \l{Drawing High Resolution Versions of Pixmaps and Images}).
638
639 \sa devicePixelRatio()
640*/
641void QPixmap::setDevicePixelRatio(qreal scaleFactor)
642{
643 if (isNull())
644 return;
645
646 if (scaleFactor == data->devicePixelRatio())
647 return;
648
649 detach();
650 data->setDevicePixelRatio(scaleFactor);
651}
652
653#ifndef QT_NO_IMAGE_HEURISTIC_MASK
654/*!
655 Creates and returns a heuristic mask for this pixmap.
656
657 The function works by selecting a color from one of the corners
658 and then chipping away pixels of that color, starting at all the
659 edges. If \a clipTight is true (the default) the mask is just
660 large enough to cover the pixels; otherwise, the mask is larger
661 than the data pixels.
662
663 The mask may not be perfect but it should be reasonable, so you
664 can do things such as the following:
665
666 \snippet code/src_gui_image_qpixmap.cpp 1
667
668 This function is slow because it involves converting to/from a
669 QImage, and non-trivial computations.
670
671 \sa QImage::createHeuristicMask(), createMaskFromColor()
672*/
673QBitmap QPixmap::createHeuristicMask(bool clipTight) const
674{
675 QBitmap m = QBitmap::fromImage(toImage().createHeuristicMask(clipTight));
676 return m;
677}
678#endif
679
680/*!
681 Creates and returns a mask for this pixmap based on the given \a
682 maskColor. If the \a mode is Qt::MaskInColor, all pixels matching the
683 maskColor will be transparent. If \a mode is Qt::MaskOutColor, all pixels
684 matching the maskColor will be opaque.
685
686 This function is slow because it involves converting to/from a
687 QImage.
688
689 \sa createHeuristicMask(), QImage::createMaskFromColor()
690*/
691QBitmap QPixmap::createMaskFromColor(const QColor &maskColor, Qt::MaskMode mode) const
692{
693 QImage image = toImage().convertToFormat(QImage::Format_ARGB32);
694 return QBitmap::fromImage(std::move(image).createMaskFromColor(maskColor.rgba(), mode));
695}
696
697/*!
698 Loads a pixmap from the file with the given \a fileName. Returns
699 true if the pixmap was successfully loaded; otherwise invalidates
700 the pixmap and returns \c false.
701
702 The loader attempts to read the pixmap using the specified \a
703 format. If the \a format is not specified (which is the default),
704 the loader probes the file for a header to guess the file format.
705
706 The file name can either refer to an actual file on disk or to one
707 of the application's embedded resources. See the
708 \l{resources.html}{Resource System} overview for details on how to
709 embed pixmaps and other resource files in the application's
710 executable.
711
712 If the data needs to be modified to fit in a lower-resolution
713 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
714 control the conversion.
715
716 Note that QPixmaps are automatically added to the QPixmapCache
717 when loaded from a file in main thread; the key used is internal
718 and cannot be acquired.
719
720 \sa loadFromData(), {QPixmap#Reading and Writing Image
721 Files}{Reading and Writing Image Files}
722*/
723
724bool QPixmap::load(const QString &fileName, const char *format, Qt::ImageConversionFlags flags)
725{
726 if (!fileName.isEmpty()) {
727
728 QFileInfo info(fileName);
729 // Note: If no extension is provided, we try to match the
730 // file against known plugin extensions
731 if (info.completeSuffix().isEmpty() || info.exists()) {
732 const bool inGuiThread = qApp->thread() == QThread::currentThread();
733
734 QString key = QLatin1String("qt_pixmap")
735 % info.absoluteFilePath()
736 % HexString<uint>(info.lastModified().toSecsSinceEpoch())
737 % HexString<quint64>(info.size())
738 % HexString<uint>(data ? data->pixelType() : QPlatformPixmap::PixmapType);
739
740 if (inGuiThread && QPixmapCache::find(key, this))
741 return true;
742
743 data = QPlatformPixmap::create(0, 0, data ? data->pixelType() : QPlatformPixmap::PixmapType);
744
745 if (data->fromFile(fileName, format, flags)) {
746 if (inGuiThread)
747 QPixmapCache::insert(key, *this);
748 return true;
749 }
750 }
751 }
752
753 if (!isNull()) {
754 if (isQBitmap())
755 *this = QBitmap();
756 else
757 data.reset();
758 }
759 return false;
760}
761
762/*!
763 \fn bool QPixmap::loadFromData(const uchar *data, uint len, const char *format, Qt::ImageConversionFlags flags)
764
765 Loads a pixmap from the \a len first bytes of the given binary \a
766 data. Returns \c true if the pixmap was loaded successfully;
767 otherwise invalidates the pixmap and returns \c false.
768
769 The loader attempts to read the pixmap using the specified \a
770 format. If the \a format is not specified (which is the default),
771 the loader probes the file for a header to guess the file format.
772
773 If the data needs to be modified to fit in a lower-resolution
774 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
775 control the conversion.
776
777 \sa load(), {QPixmap#Reading and Writing Image Files}{Reading and
778 Writing Image Files}
779*/
780
781bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, Qt::ImageConversionFlags flags)
782{
783 if (len == 0 || buf == 0) {
784 data.reset();
785 return false;
786 }
787
788 data = QPlatformPixmap::create(0, 0, QPlatformPixmap::PixmapType);
789
790 if (data->fromData(buf, len, format, flags))
791 return true;
792
793 data.reset();
794 return false;
795}
796
797/*!
798 \fn bool QPixmap::loadFromData(const QByteArray &data, const char *format, Qt::ImageConversionFlags flags)
799
800 \overload
801
802 Loads a pixmap from the binary \a data using the specified \a
803 format and conversion \a flags.
804*/
805
806
807/*!
808 Saves the pixmap to the file with the given \a fileName using the
809 specified image file \a format and \a quality factor. Returns \c true
810 if successful; otherwise returns \c false.
811
812 The \a quality factor must be in the range [0,100] or -1. Specify
813 0 to obtain small compressed files, 100 for large uncompressed
814 files, and -1 to use the default settings.
815
816 If \a format is 0, an image format will be chosen from \a fileName's
817 suffix.
818
819 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
820 Image Files}
821*/
822
823bool QPixmap::save(const QString &fileName, const char *format, int quality) const
824{
825 if (isNull())
826 return false; // nothing to save
827 QImageWriter writer(fileName, format);
828 return doImageIO(&writer, quality);
829}
830
831/*!
832 \overload
833
834 This function writes a QPixmap to the given \a device using the
835 specified image file \a format and \a quality factor. This can be
836 used, for example, to save a pixmap directly into a QByteArray:
837
838 \snippet image/image.cpp 1
839*/
840
841bool QPixmap::save(QIODevice* device, const char* format, int quality) const
842{
843 if (isNull())
844 return false; // nothing to save
845 QImageWriter writer(device, format);
846 return doImageIO(&writer, quality);
847}
848
849/*! \internal
850*/
851bool QPixmap::doImageIO(QImageWriter *writer, int quality) const
852{
853 if (quality > 100 || quality < -1)
854 qWarning("QPixmap::save: quality out of range [-1,100]");
855 if (quality >= 0)
856 writer->setQuality(qMin(quality,100));
857 return writer->write(toImage());
858}
859
860
861#if QT_DEPRECATED_SINCE(5, 13)
862/*!
863 \obsolete
864
865 Use QPainter or the fill(QColor) overload instead.
866*/
867
868void QPixmap::fill(const QPaintDevice *device, const QPoint &p)
869{
870 Q_UNUSED(device)
871 Q_UNUSED(p)
872 qWarning("this function is deprecated, ignored");
873}
874
875
876/*!
877 \fn void QPixmap::fill(const QPaintDevice *device, int x, int y)
878 \obsolete
879
880 Use QPainter or the fill(QColor) overload instead.
881*/
882void QPixmap::fill(const QPaintDevice *device, int xofs, int yofs)
883{
884 Q_UNUSED(device)
885 Q_UNUSED(xofs)
886 Q_UNUSED(yofs)
887 qWarning("this function is deprecated, ignored");
888}
889#endif
890
891
892/*!
893 Fills the pixmap with the given \a color.
894
895 The effect of this function is undefined when the pixmap is
896 being painted on.
897
898 \sa {QPixmap#Pixmap Transformations}{Pixmap Transformations}
899*/
900
901void QPixmap::fill(const QColor &color)
902{
903 if (isNull())
904 return;
905
906 // Some people are probably already calling fill while a painter is active, so to not break
907 // their programs, only print a warning and return when the fill operation could cause a crash.
908 if (paintingActive() && (color.alpha() != 255) && !hasAlphaChannel()) {
909 qWarning("QPixmap::fill: Cannot fill while pixmap is being painted on");
910 return;
911 }
912
913 if (data->ref.loadRelaxed() == 1) {
914 // detach() will also remove this pixmap from caches, so
915 // it has to be called even when ref == 1.
916 detach();
917 } else {
918 // Don't bother to make a copy of the data object, since
919 // it will be filled with new pixel data anyway.
920 QPlatformPixmap *d = data->createCompatiblePlatformPixmap();
921 d->resize(data->width(), data->height());
922 data = d;
923 }
924 data->fill(color);
925}
926
927/*! \fn int QPixmap::serialNumber() const
928 \obsolete
929 Returns a number that identifies the contents of this QPixmap
930 object. Distinct QPixmap objects can only have the same serial
931 number if they refer to the same contents (but they don't have
932 to).
933
934 Use cacheKey() instead.
935
936 \warning The serial number doesn't necessarily change when
937 the pixmap is altered. This means that it may be dangerous to use
938 it as a cache key. For caching pixmaps, we recommend using the
939 QPixmapCache class whenever possible.
940*/
941
942/*!
943 Returns a number that identifies this QPixmap. Distinct QPixmap
944 objects can only have the same cache key if they refer to the same
945 contents.
946
947 The cacheKey() will change when the pixmap is altered.
948*/
949qint64 QPixmap::cacheKey() const
950{
951 if (isNull())
952 return 0;
953
954 Q_ASSERT(data);
955 return data->cacheKey();
956}
957
958#if 0
959static void sendResizeEvents(QWidget *target)
960{
961 QResizeEvent e(target->size(), QSize());
962 QApplication::sendEvent(target, &e);
963
964 const QObjectList children = target->children();
965 for (int i = 0; i < children.size(); ++i) {
966 QWidget *child = static_cast<QWidget*>(children.at(i));
967 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
968 sendResizeEvents(child);
969 }
970}
971#endif
972
973#if QT_DEPRECATED_SINCE(5, 13)
974/*!
975 \obsolete
976
977 Use QWidget::grab() instead.
978*/
979QPixmap QPixmap::grabWidget(QObject *widget, const QRect &rectangle)
980{
981 QPixmap pixmap;
982 qWarning("QPixmap::grabWidget is deprecated, use QWidget::grab() instead");
983 if (!widget)
984 return pixmap;
985 QMetaObject::invokeMethod(widget, "grab", Qt::DirectConnection,
986 Q_RETURN_ARG(QPixmap, pixmap),
987 Q_ARG(QRect, rectangle));
988 return pixmap;
989}
990
991/*!
992 \fn QPixmap QPixmap::grabWidget(QObject *widget, int x, int y, int w, int h)
993 \obsolete
994
995 Use QWidget::grab() instead.
996*/
997QPixmap QPixmap::grabWidget(QObject *widget, int x, int y, int w, int h)
998{
999QT_WARNING_PUSH
1000QT_WARNING_DISABLE_DEPRECATED
1001 return grabWidget(widget, QRect(x, y, w, h));
1002QT_WARNING_POP
1003}
1004#endif
1005
1006/*****************************************************************************
1007 QPixmap stream functions
1008 *****************************************************************************/
1009#if !defined(QT_NO_DATASTREAM)
1010/*!
1011 \relates QPixmap
1012
1013 Writes the given \a pixmap to the given \a stream as a PNG
1014 image. Note that writing the stream to a file will not produce a
1015 valid image file.
1016
1017 \sa QPixmap::save(), {Serializing Qt Data Types}
1018*/
1019
1020QDataStream &operator<<(QDataStream &stream, const QPixmap &pixmap)
1021{
1022 return stream << pixmap.toImage();
1023}
1024
1025/*!
1026 \relates QPixmap
1027
1028 Reads an image from the given \a stream into the given \a pixmap.
1029
1030 \sa QPixmap::load(), {Serializing Qt Data Types}
1031*/
1032
1033QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap)
1034{
1035 QImage image;
1036 stream >> image;
1037
1038 if (image.isNull()) {
1039 pixmap = QPixmap();
1040 } else if (image.depth() == 1) {
1041 pixmap = QBitmap::fromImage(std::move(image));
1042 } else {
1043 pixmap = QPixmap::fromImage(std::move(image));
1044 }
1045 return stream;
1046}
1047
1048#endif // QT_NO_DATASTREAM
1049
1050/*!
1051 \internal
1052*/
1053
1054bool QPixmap::isDetached() const
1055{
1056 return data && data->ref.loadRelaxed() == 1;
1057}
1058
1059/*!
1060 Replaces this pixmap's data with the given \a image using the
1061 specified \a flags to control the conversion. The \a flags
1062 argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1063 Passing 0 for \a flags sets all the default options. Returns \c true
1064 if the result is that this pixmap is not null.
1065
1066 Note: this function was part of Qt 3 support in Qt 4.6 and earlier.
1067 It has been promoted to official API status in 4.7 to support updating
1068 the pixmap's image without creating a new QPixmap as fromImage() would.
1069
1070 \sa fromImage()
1071 \since 4.7
1072*/
1073bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
1074{
1075 detach();
1076 if (image.isNull() || !data)
1077 *this = QPixmap::fromImage(image, flags);
1078 else
1079 data->fromImage(image, flags);
1080 return !isNull();
1081}
1082
1083/*!
1084 \fn QPixmap QPixmap::scaled(int width, int height,
1085 Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode
1086 transformMode) const
1087
1088 \overload
1089
1090 Returns a copy of the pixmap scaled to a rectangle with the given
1091 \a width and \a height according to the given \a aspectRatioMode and
1092 \a transformMode.
1093
1094 If either the \a width or the \a height is zero or negative, this
1095 function returns a null pixmap.
1096*/
1097
1098/*!
1099 \fn QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode
1100 aspectRatioMode, Qt::TransformationMode transformMode) const
1101
1102 Scales the pixmap to the given \a size, using the aspect ratio and
1103 transformation modes specified by \a aspectRatioMode and \a
1104 transformMode.
1105
1106 \image qimage-scaling.png
1107
1108 \list
1109 \li If \a aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap
1110 is scaled to \a size.
1111 \li If \a aspectRatioMode is Qt::KeepAspectRatio, the pixmap is
1112 scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
1113 \li If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
1114 the pixmap is scaled to a rectangle as small as possible
1115 outside \a size, preserving the aspect ratio.
1116 \endlist
1117
1118 If the given \a size is empty, this function returns a null
1119 pixmap.
1120
1121
1122 In some cases it can be more beneficial to draw the pixmap to a
1123 painter with a scale set rather than scaling the pixmap. This is
1124 the case when the painter is for instance based on OpenGL or when
1125 the scale factor changes rapidly.
1126
1127 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1128 Transformations}
1129
1130*/
1131QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
1132{
1133 if (isNull()) {
1134 qWarning("QPixmap::scaled: Pixmap is a null pixmap");
1135 return QPixmap();
1136 }
1137 if (s.isEmpty())
1138 return QPixmap();
1139
1140 QSize newSize = size();
1141 newSize.scale(s, aspectMode);
1142 newSize.rwidth() = qMax(newSize.width(), 1);
1143 newSize.rheight() = qMax(newSize.height(), 1);
1144 if (newSize == size())
1145 return *this;
1146
1147 QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(),
1148 (qreal)newSize.height() / height());
1149 QPixmap pix = transformed(wm, mode);
1150 return pix;
1151}
1152
1153/*!
1154 \fn QPixmap QPixmap::scaledToWidth(int width, Qt::TransformationMode
1155 mode) const
1156
1157 Returns a scaled copy of the image. The returned image is scaled
1158 to the given \a width using the specified transformation \a mode.
1159 The height of the pixmap is automatically calculated so that the
1160 aspect ratio of the pixmap is preserved.
1161
1162 If \a width is 0 or negative, a null pixmap is returned.
1163
1164 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1165 Transformations}
1166*/
1167QPixmap QPixmap::scaledToWidth(int w, Qt::TransformationMode mode) const
1168{
1169 if (isNull()) {
1170 qWarning("QPixmap::scaleWidth: Pixmap is a null pixmap");
1171 return copy();
1172 }
1173 if (w <= 0)
1174 return QPixmap();
1175
1176 qreal factor = (qreal) w / width();
1177 QTransform wm = QTransform::fromScale(factor, factor);
1178 return transformed(wm, mode);
1179}
1180
1181/*!
1182 \fn QPixmap QPixmap::scaledToHeight(int height,
1183 Qt::TransformationMode mode) const
1184
1185 Returns a scaled copy of the image. The returned image is scaled
1186 to the given \a height using the specified transformation \a mode.
1187 The width of the pixmap is automatically calculated so that the
1188 aspect ratio of the pixmap is preserved.
1189
1190 If \a height is 0 or negative, a null pixmap is returned.
1191
1192 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1193 Transformations}
1194*/
1195QPixmap QPixmap::scaledToHeight(int h, Qt::TransformationMode mode) const
1196{
1197 if (isNull()) {
1198 qWarning("QPixmap::scaleHeight: Pixmap is a null pixmap");
1199 return copy();
1200 }
1201 if (h <= 0)
1202 return QPixmap();
1203
1204 qreal factor = (qreal) h / height();
1205 QTransform wm = QTransform::fromScale(factor, factor);
1206 return transformed(wm, mode);
1207}
1208
1209/*!
1210 Returns a copy of the pixmap that is transformed using the given
1211 transformation \a transform and transformation \a mode. The original
1212 pixmap is not changed.
1213
1214 The transformation \a transform is internally adjusted to compensate
1215 for unwanted translation; i.e. the pixmap produced is the smallest
1216 pixmap that contains all the transformed points of the original
1217 pixmap. Use the trueMatrix() function to retrieve the actual
1218 matrix used for transforming the pixmap.
1219
1220 This function is slow because it involves transformation to a
1221 QImage, non-trivial computations and a transformation back to a
1222 QPixmap.
1223
1224 \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap
1225 Transformations}
1226*/
1227QPixmap QPixmap::transformed(const QTransform &transform,
1228 Qt::TransformationMode mode) const
1229{
1230 if (isNull() || transform.type() <= QTransform::TxTranslate)
1231 return *this;
1232
1233 return data->transformed(transform, mode);
1234}
1235
1236/*!
1237 \overload
1238
1239 This convenience function loads the \a matrix into a
1240 QTransform and calls the overloaded function.
1241 */
1242QPixmap QPixmap::transformed(const QMatrix &matrix, Qt::TransformationMode mode) const
1243{
1244 return transformed(QTransform(matrix), mode);
1245}
1246
1247
1248
1249
1250
1251
1252
1253
1254/*!
1255 \class QPixmap
1256 \inmodule QtGui
1257
1258 \brief The QPixmap class is an off-screen image representation
1259 that can be used as a paint device.
1260
1261 \ingroup painting
1262 \ingroup shared
1263
1264
1265 Qt provides four classes for handling image data: QImage, QPixmap,
1266 QBitmap and QPicture. QImage is designed and optimized for I/O,
1267 and for direct pixel access and manipulation, while QPixmap is
1268 designed and optimized for showing images on screen. QBitmap is
1269 only a convenience class that inherits QPixmap, ensuring a depth
1270 of 1. The isQBitmap() function returns \c true if a QPixmap object is
1271 really a bitmap, otherwise returns \c false. Finally, the QPicture class
1272 is a paint device that records and replays QPainter commands.
1273
1274 A QPixmap can easily be displayed on the screen using QLabel or
1275 one of QAbstractButton's subclasses (such as QPushButton and
1276 QToolButton). QLabel has a pixmap property, whereas
1277 QAbstractButton has an icon property.
1278
1279 QPixmap objects can be passed around by value since the QPixmap
1280 class uses implicit data sharing. For more information, see the \l
1281 {Implicit Data Sharing} documentation. QPixmap objects can also be
1282 streamed.
1283
1284 Note that the pixel data in a pixmap is internal and is managed by
1285 the underlying window system. Because QPixmap is a QPaintDevice
1286 subclass, QPainter can be used to draw directly onto pixmaps.
1287 Pixels can only be accessed through QPainter functions or by
1288 converting the QPixmap to a QImage. However, the fill() function
1289 is available for initializing the entire pixmap with a given color.
1290
1291 There are functions to convert between QImage and
1292 QPixmap. Typically, the QImage class is used to load an image
1293 file, optionally manipulating the image data, before the QImage
1294 object is converted into a QPixmap to be shown on
1295 screen. Alternatively, if no manipulation is desired, the image
1296 file can be loaded directly into a QPixmap.
1297
1298 QPixmap provides a collection of functions that can be used to
1299 obtain a variety of information about the pixmap. In addition,
1300 there are several functions that enables transformation of the
1301 pixmap.
1302
1303 \tableofcontents
1304
1305 \section1 Reading and Writing Image Files
1306
1307 QPixmap provides several ways of reading an image file: The file
1308 can be loaded when constructing the QPixmap object, or by using
1309 the load() or loadFromData() functions later on. When loading an
1310 image, the file name can either refer to an actual file on disk or
1311 to one of the application's embedded resources. See \l{The Qt
1312 Resource System} overview for details on how to embed images and
1313 other resource files in the application's executable.
1314
1315 Simply call the save() function to save a QPixmap object.
1316
1317 The complete list of supported file formats are available through
1318 the QImageReader::supportedImageFormats() and
1319 QImageWriter::supportedImageFormats() functions. New file formats
1320 can be added as plugins. By default, Qt supports the following
1321 formats:
1322
1323 \table
1324 \header \li Format \li Description \li Qt's support
1325 \row \li BMP \li Windows Bitmap \li Read/write
1326 \row \li GIF \li Graphic Interchange Format (optional) \li Read
1327 \row \li JPG \li Joint Photographic Experts Group \li Read/write
1328 \row \li JPEG \li Joint Photographic Experts Group \li Read/write
1329 \row \li PNG \li Portable Network Graphics \li Read/write
1330 \row \li PBM \li Portable Bitmap \li Read
1331 \row \li PGM \li Portable Graymap \li Read
1332 \row \li PPM \li Portable Pixmap \li Read/write
1333 \row \li XBM \li X11 Bitmap \li Read/write
1334 \row \li XPM \li X11 Pixmap \li Read/write
1335 \endtable
1336
1337 \section1 Pixmap Information
1338
1339 QPixmap provides a collection of functions that can be used to
1340 obtain a variety of information about the pixmap:
1341
1342 \table
1343 \header
1344 \li \li Available Functions
1345 \row
1346 \li Geometry
1347 \li
1348 The size(), width() and height() functions provide information
1349 about the pixmap's size. The rect() function returns the image's
1350 enclosing rectangle.
1351
1352 \row
1353 \li Alpha component
1354 \li
1355
1356 The hasAlphaChannel() returns \c true if the pixmap has a format that
1357 respects the alpha channel, otherwise returns \c false. The hasAlpha(),
1358 setMask() and mask() functions are legacy and should not be used.
1359 They are potentially very slow.
1360
1361 The createHeuristicMask() function creates and returns a 1-bpp
1362 heuristic mask (i.e. a QBitmap) for this pixmap. It works by
1363 selecting a color from one of the corners and then chipping away
1364 pixels of that color, starting at all the edges. The
1365 createMaskFromColor() function creates and returns a mask (i.e. a
1366 QBitmap) for the pixmap based on a given color.
1367
1368 \row
1369 \li Low-level information
1370 \li
1371
1372 The depth() function returns the depth of the pixmap. The
1373 defaultDepth() function returns the default depth, i.e. the depth
1374 used by the application on the given screen.
1375
1376 The cacheKey() function returns a number that uniquely
1377 identifies the contents of the QPixmap object.
1378
1379 \endtable
1380
1381 \section1 Pixmap Conversion
1382
1383 A QPixmap object can be converted into a QImage using the
1384 toImage() function. Likewise, a QImage can be converted into a
1385 QPixmap using the fromImage(). If this is too expensive an
1386 operation, you can use QBitmap::fromImage() instead.
1387
1388 To convert a QPixmap to and from HICON you can use the QtWinExtras
1389 functions QtWin::toHICON() and QtWin::fromHICON() respectively.
1390
1391 \section1 Pixmap Transformations
1392
1393 QPixmap supports a number of functions for creating a new pixmap
1394 that is a transformed version of the original:
1395
1396 The scaled(), scaledToWidth() and scaledToHeight() functions
1397 return scaled copies of the pixmap, while the copy() function
1398 creates a QPixmap that is a plain copy of the original one.
1399
1400 The transformed() function returns a copy of the pixmap that is
1401 transformed with the given transformation matrix and
1402 transformation mode: Internally, the transformation matrix is
1403 adjusted to compensate for unwanted translation,
1404 i.e. transformed() returns the smallest pixmap containing all
1405 transformed points of the original pixmap. The static trueMatrix()
1406 function returns the actual matrix used for transforming the
1407 pixmap.
1408
1409 \sa QBitmap, QImage, QImageReader, QImageWriter
1410*/
1411
1412
1413/*!
1414 \typedef QPixmap::DataPtr
1415 \internal
1416*/
1417
1418/*!
1419 \fn DataPtr &QPixmap::data_ptr()
1420 \internal
1421*/
1422
1423/*!
1424 Returns \c true if this pixmap has an alpha channel, \e or has a
1425 mask, otherwise returns \c false.
1426
1427 \sa hasAlphaChannel(), mask()
1428*/
1429bool QPixmap::hasAlpha() const
1430{
1431 return data && data->hasAlphaChannel();
1432}
1433
1434/*!
1435 Returns \c true if the pixmap has a format that respects the alpha
1436 channel, otherwise returns \c false.
1437
1438 \sa hasAlpha()
1439*/
1440bool QPixmap::hasAlphaChannel() const
1441{
1442 return data && data->hasAlphaChannel();
1443}
1444
1445/*!
1446 \internal
1447*/
1448int QPixmap::metric(PaintDeviceMetric metric) const
1449{
1450 return data ? data->metric(metric) : 0;
1451}
1452
1453/*!
1454 \internal
1455*/
1456QPaintEngine *QPixmap::paintEngine() const
1457{
1458 return data ? data->paintEngine() : 0;
1459}
1460
1461/*!
1462 \fn QBitmap QPixmap::mask() const
1463
1464 Extracts a bitmap mask from the pixmap's alpha channel.
1465
1466 \warning This is potentially an expensive operation. The mask of
1467 the pixmap is extracted dynamically from the pixeldata.
1468
1469 \sa setMask(), {QPixmap#Pixmap Information}{Pixmap Information}
1470*/
1471QBitmap QPixmap::mask() const
1472{
1473 return data ? data->mask() : QBitmap();
1474}
1475
1476/*!
1477 Returns the default pixmap depth used by the application.
1478
1479 On all platforms the depth of the primary screen will be returned.
1480
1481 \note QGuiApplication must be created before calling this function.
1482
1483 \sa depth(), QColormap::depth(), {QPixmap#Pixmap Information}{Pixmap Information}
1484
1485*/
1486int QPixmap::defaultDepth()
1487{
1488 QScreen *primary = QGuiApplication::primaryScreen();
1489 if (Q_LIKELY(primary))
1490 return primary->depth();
1491 qWarning("QPixmap: QGuiApplication must be created before calling defaultDepth().");
1492 return 0;
1493}
1494
1495/*!
1496 Detaches the pixmap from shared pixmap data.
1497
1498 A pixmap is automatically detached by Qt whenever its contents are
1499 about to change. This is done in almost all QPixmap member
1500 functions that modify the pixmap (fill(), fromImage(),
1501 load(), etc.), and in QPainter::begin() on a pixmap.
1502
1503 There are two exceptions in which detach() must be called
1504 explicitly, that is when calling the handle() or the
1505 x11PictureHandle() function (only available on X11). Otherwise,
1506 any modifications done using system calls, will be performed on
1507 the shared data.
1508
1509 The detach() function returns immediately if there is just a
1510 single reference or if the pixmap has not been initialized yet.
1511*/
1512void QPixmap::detach()
1513{
1514 if (!data)
1515 return;
1516
1517 // QPixmap.data member may be QRuntimePlatformPixmap so use handle() function to get
1518 // the actual underlaying runtime pixmap data.
1519 QPlatformPixmap *pd = handle();
1520 QPlatformPixmap::ClassId id = pd->classId();
1521 if (id == QPlatformPixmap::RasterClass) {
1522 QRasterPlatformPixmap *rasterData = static_cast<QRasterPlatformPixmap*>(pd);
1523 rasterData->image.detach();
1524 }
1525
1526 if (data->is_cached && data->ref.loadRelaxed() == 1)
1527 QImagePixmapCleanupHooks::executePlatformPixmapModificationHooks(data.data());
1528
1529 if (data->ref.loadRelaxed() != 1) {
1530 *this = copy();
1531 }
1532 ++data->detach_no;
1533}
1534
1535/*!
1536 \fn QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1537
1538 Converts the given \a image to a pixmap using the specified \a
1539 flags to control the conversion. The \a flags argument is a
1540 bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a
1541 flags sets all the default options.
1542
1543 In case of monochrome and 8-bit images, the image is first
1544 converted to a 32-bit pixmap and then filled with the colors in
1545 the color table. If this is too expensive an operation, you can
1546 use QBitmap::fromImage() instead.
1547
1548 \sa fromImageReader(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1549*/
1550QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1551{
1552 if (image.isNull())
1553 return QPixmap();
1554
1555 if (Q_UNLIKELY(!qobject_cast<QGuiApplication *>(QCoreApplication::instance()))) {
1556 qWarning("QPixmap::fromImage: QPixmap cannot be created without a QGuiApplication");
1557 return QPixmap();
1558 }
1559
1560 QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1561 data->fromImage(image, flags);
1562 return QPixmap(data.take());
1563}
1564
1565/*!
1566 \fn QPixmap QPixmap::fromImage(QImage &&image, Qt::ImageConversionFlags flags)
1567 \since 5.3
1568 \overload
1569
1570 Converts the given \a image to a pixmap without copying if possible.
1571*/
1572
1573
1574/*!
1575 \internal
1576*/
1577QPixmap QPixmap::fromImageInPlace(QImage &image, Qt::ImageConversionFlags flags)
1578{
1579 if (image.isNull())
1580 return QPixmap();
1581
1582 if (Q_UNLIKELY(!qobject_cast<QGuiApplication *>(QCoreApplication::instance()))) {
1583 qWarning("QPixmap::fromImageInPlace: QPixmap cannot be created without a QGuiApplication");
1584 return QPixmap();
1585 }
1586
1587 QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1588 data->fromImageInPlace(image, flags);
1589 return QPixmap(data.take());
1590}
1591
1592/*!
1593 \fn QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
1594
1595 Create a QPixmap from an image read directly from an \a imageReader.
1596 The \a flags argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1597 Passing 0 for \a flags sets all the default options.
1598
1599 On some systems, reading an image directly to QPixmap can use less memory than
1600 reading a QImage to convert it to QPixmap.
1601
1602 \sa fromImage(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1603*/
1604QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
1605{
1606 if (Q_UNLIKELY(!qobject_cast<QGuiApplication *>(QCoreApplication::instance()))) {
1607 qWarning("QPixmap::fromImageReader: QPixmap cannot be created without a QGuiApplication");
1608 return QPixmap();
1609 }
1610
1611 QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1612 data->fromImageReader(imageReader, flags);
1613 return QPixmap(data.take());
1614}
1615
1616#if QT_DEPRECATED_SINCE(5, 13)
1617/*!
1618 \fn QPixmap QPixmap::grabWindow(WId window, int x, int y, int
1619 width, int height)
1620
1621 Creates and returns a pixmap constructed by grabbing the contents
1622 of the given \a window restricted by QRect(\a x, \a y, \a width,
1623 \a height).
1624
1625 The arguments (\a{x}, \a{y}) specify the offset in the window,
1626 whereas (\a{width}, \a{height}) specify the area to be copied. If
1627 \a width is negative, the function copies everything to the right
1628 border of the window. If \a height is negative, the function
1629 copies everything to the bottom of the window.
1630
1631 The window system identifier (\c WId) can be retrieved using the
1632 QWidget::winId() function. The rationale for using a window
1633 identifier and not a QWidget, is to enable grabbing of windows
1634 that are not part of the application, window system frames, and so
1635 on.
1636
1637 The grabWindow() function grabs pixels from the screen, not from
1638 the window, i.e. if there is another window partially or entirely
1639 over the one you grab, you get pixels from the overlying window,
1640 too. The mouse cursor is generally not grabbed.
1641
1642 Note on X11 that if the given \a window doesn't have the same depth
1643 as the root window, and another window partially or entirely
1644 obscures the one you grab, you will \e not get pixels from the
1645 overlying window. The contents of the obscured areas in the
1646 pixmap will be undefined and uninitialized.
1647
1648 On Windows Vista and above grabbing a layered window, which is
1649 created by setting the Qt::WA_TranslucentBackground attribute, will
1650 not work. Instead grabbing the desktop widget should work.
1651
1652 \warning In general, grabbing an area outside the screen is not
1653 safe. This depends on the underlying window system.
1654
1655 \warning The function is deprecated in Qt 5.0 since there might be
1656 platform plugins in which window system identifiers (\c WId)
1657 are local to a screen. Use QScreen::grabWindow() instead.
1658
1659 \sa grabWidget(), {Screenshot Example}
1660 \sa QScreen
1661 \deprecated
1662*/
1663
1664QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h)
1665{
1666 qWarning("this function is deprecated, use QScreen::grabWindow() instead."
1667 " Defaulting to primary screen.");
1668 return QGuiApplication::primaryScreen()->grabWindow(window, x, y, w, h);
1669}
1670#endif
1671
1672/*!
1673 \internal
1674*/
1675QPlatformPixmap* QPixmap::handle() const
1676{
1677 return data.data();
1678}
1679
1680#ifndef QT_NO_DEBUG_STREAM
1681QDebug operator<<(QDebug dbg, const QPixmap &r)
1682{
1683 QDebugStateSaver saver(dbg);
1684 dbg.resetFormat();
1685 dbg.nospace();
1686 dbg << "QPixmap(";
1687 if (r.isNull()) {
1688 dbg << "null";
1689 } else {
1690 dbg << r.size() << ",depth=" << r.depth()
1691 << ",devicePixelRatio=" << r.devicePixelRatio()
1692 << ",cacheKey=" << Qt::showbase << Qt::hex << r.cacheKey() << Qt::dec << Qt::noshowbase;
1693 }
1694 dbg << ')';
1695 return dbg;
1696}
1697#endif
1698
1699/*!
1700 \fn QPixmap QPixmap::alphaChannel() const
1701
1702 Most use cases for this can be achieved using a QPainter and QPainter::CompositionMode instead.
1703*/
1704
1705/*!
1706 \fn void QPixmap::setAlphaChannel(const QPixmap &p)
1707
1708 Most use cases for this can be achieved using \a p with QPainter and QPainter::CompositionMode instead.
1709*/
1710
1711QT_END_NAMESPACE
1712