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