1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
45 #include "qplatformpixmap_qpa.h"
46 #include "qimagepixmapcleanuphooks_p.h"
51 #include "qdatastream.h"
53 #include <private/qguiapplication_p.h>
56 #include "qfileinfo.h"
57 #include "qpixmapcache.h"
58 #include "qdatetime.h"
59 #include "qimagereader.h"
60 #include "qimagewriter.h"
61 #include "qpaintengine.h"
66 # include "qplatformintegration_qpa.h"
68 #include "qpixmap_raster_p.h"
69 #include "private/qhexstring_p.h"
73 static bool qt_pixmap_thread_test()
75 if (!QCoreApplication::instance()) {
76 qFatal("QPixmap: Must construct a QApplication before a QPaintDevice");
80 if (qApp->thread() != QThread::currentThread()) {
82 if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedPixmaps)) {
83 printf("Lighthouse plugin does not support threaded pixmaps!\n");
87 qWarning("QPixmap: It is not safe to use pixmaps outside the GUI thread");
94 void QPixmap::doInit(int w, int h, int type)
96 if ((w > 0 && h > 0) || type == QPlatformPixmap::BitmapType)
97 data = QPlatformPixmap::create(w, h, (QPlatformPixmap::PixelType) type);
103 Constructs a null pixmap.
111 (void) qt_pixmap_thread_test();
112 doInit(0, 0, QPlatformPixmap::PixmapType);
116 \fn QPixmap::QPixmap(int width, int height)
118 Constructs a pixmap with the given \a width and \a height. If
119 either \a width or \a height is zero, a null pixmap is
122 \warning This will create a QPixmap with uninitialized data. Call
123 fill() to fill the pixmap with an appropriate color before drawing
124 onto it with QPainter.
129 QPixmap::QPixmap(int w, int h)
132 if (!qt_pixmap_thread_test())
133 doInit(0, 0, QPlatformPixmap::PixmapType);
135 doInit(w, h, QPlatformPixmap::PixmapType);
141 Constructs a pixmap of the given \a size.
143 \warning This will create a QPixmap with uninitialized data. Call
144 fill() to fill the pixmap with an appropriate color before drawing
145 onto it with QPainter.
148 QPixmap::QPixmap(const QSize &size)
151 if (!qt_pixmap_thread_test())
152 doInit(0, 0, QPlatformPixmap::PixmapType);
154 doInit(size.width(), size.height(), QPlatformPixmap::PixmapType);
160 QPixmap::QPixmap(const QSize &s, int type)
162 if (!qt_pixmap_thread_test())
163 doInit(0, 0, static_cast<QPlatformPixmap::PixelType>(type));
165 doInit(s.width(), s.height(), static_cast<QPlatformPixmap::PixelType>(type));
171 QPixmap::QPixmap(QPlatformPixmap *d)
172 : QPaintDevice(), data(d)
177 Constructs a pixmap from the file with the given \a fileName. If the
178 file does not exist or is of an unknown format, the pixmap becomes a
181 The loader attempts to read the pixmap using the specified \a
182 format. If the \a format is not specified (which is the default),
183 the loader probes the file for a header to guess the file format.
185 The file name can either refer to an actual file on disk or to
186 one of the application's embedded resources. See the
187 \l{resources.html}{Resource System} overview for details on how
188 to embed images and other resource files in the application's
191 If the image needs to be modified to fit in a lower-resolution
192 result (e.g. converting from 32-bit to 8-bit), use the \a
193 flags to control the conversion.
195 The \a fileName, \a format and \a flags parameters are
196 passed on to load(). This means that the data in \a fileName is
197 not compiled into the binary. If \a fileName contains a relative
198 path (e.g. the filename only) the relevant file must be found
199 relative to the runtime working directory.
201 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
205 QPixmap::QPixmap(const QString& fileName, const char *format, Qt::ImageConversionFlags flags)
208 doInit(0, 0, QPlatformPixmap::PixmapType);
209 if (!qt_pixmap_thread_test())
212 load(fileName, format, flags);
216 Constructs a pixmap that is a copy of the given \a pixmap.
221 QPixmap::QPixmap(const QPixmap &pixmap)
224 if (!qt_pixmap_thread_test()) {
225 doInit(0, 0, QPlatformPixmap::PixmapType);
228 if (pixmap.paintingActive()) { // make a deep copy
229 operator=(pixmap.copy());
236 Constructs a pixmap from the given \a xpm data, which must be a
239 Errors are silently ignored.
241 Note that it's possible to squeeze the XPM variable a little bit
242 by using an unusual declaration:
244 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 0
246 The extra \c const makes the entire definition read-only, which is
247 slightly more efficient (for example, when the code is in a shared
248 library) and ROMable when the application is to be stored in ROM.
250 #ifndef QT_NO_IMAGEFORMAT_XPM
251 QPixmap::QPixmap(const char * const xpm[])
254 doInit(0, 0, QPlatformPixmap::PixmapType);
259 if (!image.isNull()) {
260 if (data && data->pixelType() == QPlatformPixmap::BitmapType)
261 *this = QBitmap::fromImage(image);
263 *this = fromImage(image);
275 Q_ASSERT(!data || data->ref.load() >= 1); // Catch if ref-counting changes again
281 int QPixmap::devType() const
283 return QInternal::Pixmap;
287 \fn QPixmap QPixmap::copy(int x, int y, int width, int height) const
290 Returns a deep copy of the subset of the pixmap that is specified
291 by the rectangle QRect( \a x, \a y, \a width, \a height).
295 \fn QPixmap QPixmap::copy(const QRect &rectangle) const
297 Returns a deep copy of the subset of the pixmap that is specified
298 by the given \a rectangle. For more information on deep copies,
299 see the \l {Implicit Data Sharing} documentation.
301 If the given \a rectangle is empty, the whole image is copied.
303 \sa operator=(), QPixmap(), {QPixmap#Pixmap
304 Transformations}{Pixmap Transformations}
306 QPixmap QPixmap::copy(const QRect &rect) const
311 QRect r(0, 0, width(), height());
313 r = r.intersected(rect);
315 QPlatformPixmap *d = data->createCompatiblePlatformPixmap();
316 d->copy(data.data(), r);
321 \fn QPixmap::scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed)
324 This convenience function is equivalent to calling QPixmap::scroll(\a dx,
325 \a dy, QRect(\a x, \a y, \a width, \a height), \a exposed).
327 \sa QWidget::scroll(), QGraphicsItem::scroll()
333 Scrolls the area \a rect of this pixmap by (\a dx, \a dy). The exposed
334 region is left unchanged. You can optionally pass a pointer to an empty
335 QRegion to get the region that is \a exposed by the scroll operation.
337 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 2
339 You cannot scroll while there is an active painter on the pixmap.
341 \sa QWidget::scroll(), QGraphicsItem::scroll()
343 void QPixmap::scroll(int dx, int dy, const QRect &rect, QRegion *exposed)
345 if (isNull() || (dx == 0 && dy == 0))
347 QRect dest = rect & this->rect();
348 QRect src = dest.translated(-dx, -dy) & dest;
357 if (!data->scroll(dx, dy, src)) {
360 QPainter painter(&pix);
361 painter.setCompositionMode(QPainter::CompositionMode_Source);
362 painter.drawPixmap(src.translated(dx, dy), *this, src);
369 *exposed -= src.translated(dx, dy);
374 Assigns the given \a pixmap to this pixmap and returns a reference
377 \sa copy(), QPixmap()
380 QPixmap &QPixmap::operator=(const QPixmap &pixmap)
382 if (paintingActive()) {
383 qWarning("QPixmap::operator=: Cannot assign to pixmap during painting");
386 if (pixmap.paintingActive()) { // make a deep copy
387 *this = pixmap.copy();
395 \fn void QPixmap::swap(QPixmap &other)
398 Swaps pixmap \a other with this pixmap. This operation is very
399 fast and never fails.
403 Returns the pixmap as a QVariant.
405 QPixmap::operator QVariant() const
407 return QVariant(QVariant::Pixmap, this);
411 \fn bool QPixmap::operator!() const
413 Returns true if this is a null pixmap; otherwise returns false.
419 Converts the pixmap to a QImage. Returns a null image if the
422 If the pixmap has 1-bit depth, the returned image will also be 1
423 bit deep. Images with more bits will be returned in a format
424 closely represents the underlying system. Usually this will be
425 QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha and
426 QImage::Format_RGB32 or QImage::Format_RGB16 for pixmaps without
429 Note that for the moment, alpha masks on monochrome images are
432 \sa fromImage(), {QImage#Image Formats}{Image Formats}
434 QImage QPixmap::toImage() const
439 return data->toImage();
443 \fn QMatrix QPixmap::trueMatrix(const QTransform &matrix, int width, int height)
445 Returns the actual matrix used for transforming a pixmap with the
446 given \a width, \a height and \a matrix.
448 When transforming a pixmap using the transformed() function, the
449 transformation matrix is internally adjusted to compensate for
450 unwanted translation, i.e. transformed() returns the smallest
451 pixmap containing all transformed points of the original
452 pixmap. This function returns the modified matrix, which maps
453 points correctly from the original pixmap into the new pixmap.
455 \sa transformed(), {QPixmap#Pixmap Transformations}{Pixmap
458 QTransform QPixmap::trueMatrix(const QTransform &m, int w, int h)
460 return QImage::trueMatrix(m, w, h);
466 This convenience function loads the matrix \a m into a
467 QTransform and calls the overloaded function with the
468 QTransform and the width \a w and the height \a h.
470 QMatrix QPixmap::trueMatrix(const QMatrix &m, int w, int h)
472 return trueMatrix(QTransform(m), w, h).toAffine();
477 \fn bool QPixmap::isQBitmap() const
479 Returns true if this is a QBitmap; otherwise returns false.
482 bool QPixmap::isQBitmap() const
484 return data->type == QPlatformPixmap::BitmapType;
488 \fn bool QPixmap::isNull() const
490 Returns true if this is a null pixmap; otherwise returns false.
492 A null pixmap has zero width, zero height and no contents. You
493 cannot draw in a null pixmap.
495 bool QPixmap::isNull() const
497 return !data || data->isNull();
501 \fn int QPixmap::width() const
503 Returns the width of the pixmap.
505 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
507 int QPixmap::width() const
509 return data ? data->width() : 0;
513 \fn int QPixmap::height() const
515 Returns the height of the pixmap.
517 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
519 int QPixmap::height() const
521 return data ? data->height() : 0;
525 \fn QSize QPixmap::size() const
527 Returns the size of the pixmap.
529 \sa width(), height(), {QPixmap#Pixmap Information}{Pixmap
532 QSize QPixmap::size() const
534 return data ? QSize(data->width(), data->height()) : QSize(0, 0);
538 \fn QRect QPixmap::rect() const
540 Returns the pixmap's enclosing rectangle.
542 \sa {QPixmap#Pixmap Information}{Pixmap Information}
544 QRect QPixmap::rect() const
546 return data ? QRect(0, 0, data->width(), data->height()) : QRect();
550 \fn int QPixmap::depth() const
552 Returns the depth of the pixmap.
554 The pixmap depth is also called bits per pixel (bpp) or bit planes
555 of a pixmap. A null pixmap has depth 0.
557 \sa defaultDepth(), {QPixmap#Pixmap Information}{Pixmap
560 int QPixmap::depth() const
562 return data ? data->depth() : 0;
568 This function merges the \a mask with the pixmap's alpha channel. A pixel
569 value of 1 on the mask means the pixmap's pixel is unchanged; a value of 0
570 means the pixel is transparent. The mask must have the same size as this
573 Setting a null mask resets the mask, leaving the previously transparent
574 pixels black. The effect of this function is undefined when the pixmap is
577 \warning This is potentially an expensive operation.
579 \sa mask(), {QPixmap#Pixmap Transformations}{Pixmap Transformations},
582 void QPixmap::setMask(const QBitmap &mask)
584 if (paintingActive()) {
585 qWarning("QPixmap::setMask: Cannot set mask while pixmap is being painted on");
589 if (!mask.isNull() && mask.size() != size()) {
590 qWarning("QPixmap::setMask() mask size differs from pixmap size");
597 if (static_cast<const QPixmap &>(mask).data == data) // trying to selfmask
602 QImage image = data->toImage();
603 if (mask.size().isEmpty()) {
604 if (image.depth() != 1) { // hw: ????
605 image = image.convertToFormat(QImage::Format_RGB32);
608 const int w = image.width();
609 const int h = image.height();
611 switch (image.depth()) {
613 const QImage imageMask = mask.toImage().convertToFormat(image.format());
614 for (int y = 0; y < h; ++y) {
615 const uchar *mscan = imageMask.scanLine(y);
616 uchar *tscan = image.scanLine(y);
617 int bytesPerLine = image.bytesPerLine();
618 for (int i = 0; i < bytesPerLine; ++i)
619 tscan[i] &= mscan[i];
624 const QImage imageMask = mask.toImage().convertToFormat(QImage::Format_MonoLSB);
625 image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
626 for (int y = 0; y < h; ++y) {
627 const uchar *mscan = imageMask.scanLine(y);
628 QRgb *tscan = (QRgb *)image.scanLine(y);
629 for (int x = 0; x < w; ++x) {
630 if (!(mscan[x>>3] & (1 << (x&7))))
638 data->fromImage(image, Qt::AutoColor);
641 #ifndef QT_NO_IMAGE_HEURISTIC_MASK
643 Creates and returns a heuristic mask for this pixmap.
645 The function works by selecting a color from one of the corners
646 and then chipping away pixels of that color, starting at all the
647 edges. If \a clipTight is true (the default) the mask is just
648 large enough to cover the pixels; otherwise, the mask is larger
649 than the data pixels.
651 The mask may not be perfect but it should be reasonable, so you
652 can do things such as the following:
654 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 1
656 This function is slow because it involves converting to/from a
657 QImage, and non-trivial computations.
659 \sa QImage::createHeuristicMask(), createMaskFromColor()
661 QBitmap QPixmap::createHeuristicMask(bool clipTight) const
663 QBitmap m = QBitmap::fromImage(toImage().createHeuristicMask(clipTight));
669 Creates and returns a mask for this pixmap based on the given \a
670 maskColor. If the \a mode is Qt::MaskInColor, all pixels matching the
671 maskColor will be transparent. If \a mode is Qt::MaskOutColor, all pixels
672 matching the maskColor will be opaque.
674 This function is slow because it involves converting to/from a
677 \sa createHeuristicMask(), QImage::createMaskFromColor()
679 QBitmap QPixmap::createMaskFromColor(const QColor &maskColor, Qt::MaskMode mode) const
681 QImage image = toImage().convertToFormat(QImage::Format_ARGB32);
682 return QBitmap::fromImage(image.createMaskFromColor(maskColor.rgba(), mode));
686 Loads a pixmap from the file with the given \a fileName. Returns
687 true if the pixmap was successfully loaded; otherwise returns
690 The loader attempts to read the pixmap using the specified \a
691 format. If the \a format is not specified (which is the default),
692 the loader probes the file for a header to guess the file format.
694 The file name can either refer to an actual file on disk or to one
695 of the application's embedded resources. See the
696 \l{resources.html}{Resource System} overview for details on how to
697 embed pixmaps and other resource files in the application's
700 If the data needs to be modified to fit in a lower-resolution
701 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
702 control the conversion.
704 Note that QPixmaps are automatically added to the QPixmapCache
705 when loaded from a file; the key used is internal and can not
708 \sa loadFromData(), {QPixmap#Reading and Writing Image
709 Files}{Reading and Writing Image Files}
712 bool QPixmap::load(const QString &fileName, const char *format, Qt::ImageConversionFlags flags)
714 if (fileName.isEmpty())
717 QFileInfo info(fileName);
718 QString key = QLatin1Literal("qt_pixmap")
719 % info.absoluteFilePath()
720 % HexString<uint>(info.lastModified().toTime_t())
721 % HexString<quint64>(info.size())
722 % HexString<uint>(data ? data->pixelType() : QPlatformPixmap::PixmapType);
724 // Note: If no extension is provided, we try to match the
725 // file against known plugin extensions
726 if (!info.completeSuffix().isEmpty() && !info.exists())
729 if (QPixmapCache::find(key, *this))
732 QScopedPointer<QPlatformPixmap> tmp(QPlatformPixmap::create(0, 0, data ? data->type : QPlatformPixmap::PixmapType));
733 if (tmp->fromFile(fileName, format, flags)) {
735 QPixmapCache::insert(key, *this);
743 \fn bool QPixmap::loadFromData(const uchar *data, uint len, const char *format, Qt::ImageConversionFlags flags)
745 Loads a pixmap from the \a len first bytes of the given binary \a
746 data. Returns true if the pixmap was loaded successfully;
747 otherwise returns false.
749 The loader attempts to read the pixmap using the specified \a
750 format. If the \a format is not specified (which is the default),
751 the loader probes the file for a header to guess the file format.
753 If the data needs to be modified to fit in a lower-resolution
754 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
755 control the conversion.
757 \sa load(), {QPixmap#Reading and Writing Image Files}{Reading and
761 bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, Qt::ImageConversionFlags flags)
763 if (len == 0 || buf == 0)
767 data = QPlatformPixmap::create(0, 0, QPlatformPixmap::PixmapType);
769 return data->fromData(buf, len, format, flags);
773 \fn bool QPixmap::loadFromData(const QByteArray &data, const char *format, Qt::ImageConversionFlags flags)
777 Loads a pixmap from the binary \a data using the specified \a
778 format and conversion \a flags.
783 Saves the pixmap to the file with the given \a fileName using the
784 specified image file \a format and \a quality factor. Returns true
785 if successful; otherwise returns false.
787 The \a quality factor must be in the range [0,100] or -1. Specify
788 0 to obtain small compressed files, 100 for large uncompressed
789 files, and -1 to use the default settings.
791 If \a format is 0, an image format will be chosen from \a fileName's
794 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
798 bool QPixmap::save(const QString &fileName, const char *format, int quality) const
801 return false; // nothing to save
802 QImageWriter writer(fileName, format);
803 return doImageIO(&writer, quality);
809 This function writes a QPixmap to the given \a device using the
810 specified image file \a format and \a quality factor. This can be
811 used, for example, to save a pixmap directly into a QByteArray:
813 \snippet doc/src/snippets/image/image.cpp 1
816 bool QPixmap::save(QIODevice* device, const char* format, int quality) const
819 return false; // nothing to save
820 QImageWriter writer(device, format);
821 return doImageIO(&writer, quality);
826 bool QPixmap::doImageIO(QImageWriter *writer, int quality) const
828 if (quality > 100 || quality < -1)
829 qWarning("QPixmap::save: quality out of range [-1,100]");
831 writer->setQuality(qMin(quality,100));
832 return writer->write(toImage());
836 \fn void QPixmap::fill(const QPaintDevice *device, int x, int y)
841 Fills the pixmap with the \a device's background color or pixmap.
842 The given point, (\a x, \a y), defines an offset in widget
843 coordinates to which the pixmap's top-left pixel will be mapped
847 void QPixmap::fill(const QPaintDevice *, const QPoint &)
849 qWarning() << "QPixmap::fill(const QPaintDevice *device, const QPoint &offset) is deprecated, ignored";
854 Fills the pixmap with the given \a color.
856 The effect of this function is undefined when the pixmap is
859 \sa {QPixmap#Pixmap Transformations}{Pixmap Transformations}
862 void QPixmap::fill(const QColor &color)
867 // Some people are probably already calling fill while a painter is active, so to not break
868 // their programs, only print a warning and return when the fill operation could cause a crash.
869 if (paintingActive() && (color.alpha() != 255) && !hasAlphaChannel()) {
870 qWarning("QPixmap::fill: Cannot fill while pixmap is being painted on");
874 if (data->ref.load() == 1) {
875 // detach() will also remove this pixmap from caches, so
876 // it has to be called even when ref == 1.
879 // Don't bother to make a copy of the data object, since
880 // it will be filled with new pixel data anyway.
881 QPlatformPixmap *d = data->createCompatiblePlatformPixmap();
882 d->resize(data->width(), data->height());
889 Returns a number that identifies the contents of this QPixmap
890 object. Distinct QPixmap objects can only have the same serial
891 number if they refer to the same contents (but they don't have
894 Use cacheKey() instead.
896 \warning The serial number doesn't necessarily change when
897 the pixmap is altered. This means that it may be dangerous to use
898 it as a cache key. For caching pixmaps, we recommend using the
899 QPixmapCache class whenever possible.
901 int QPixmap::serialNumber() const
905 return data->serialNumber();
909 Returns a number that identifies this QPixmap. Distinct QPixmap
910 objects can only have the same cache key if they refer to the same
913 The cacheKey() will change when the pixmap is altered.
915 qint64 QPixmap::cacheKey() const
921 return data->cacheKey();
925 static void sendResizeEvents(QWidget *target)
927 QResizeEvent e(target->size(), QSize());
928 QApplication::sendEvent(target, &e);
930 const QObjectList children = target->children();
931 for (int i = 0; i < children.size(); ++i) {
932 QWidget *child = static_cast<QWidget*>(children.at(i));
933 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
934 sendResizeEvents(child);
939 QPixmap QPixmap::grabWidget(QObject *widget, const QRect &rectangle)
942 // ### Qt5: should we keep or remove this method?
943 // SC solution would be to install a callback form QtWidgets, but ugly.
944 qWarning("QPixmap::grabWidget is deprecated, use QWidget::grab() instead");
947 QMetaObject::invokeMethod(widget, "grab", Qt::DirectConnection,
948 Q_RETURN_ARG(QPixmap, pixmap),
949 Q_ARG(QRect, rectangle));
953 /*****************************************************************************
954 QPixmap stream functions
955 *****************************************************************************/
956 #if !defined(QT_NO_DATASTREAM)
960 Writes the given \a pixmap to the given \a stream as a PNG
961 image. Note that writing the stream to a file will not produce a
964 \sa QPixmap::save(), {Serializing Qt Data Types}
967 QDataStream &operator<<(QDataStream &stream, const QPixmap &pixmap)
969 return stream << pixmap.toImage();
975 Reads an image from the given \a stream into the given \a pixmap.
977 \sa QPixmap::load(), {Serializing Qt Data Types}
980 QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap)
985 if (image.isNull()) {
987 } else if (image.depth() == 1) {
988 pixmap = QBitmap::fromImage(image);
990 pixmap = QPixmap::fromImage(image);
995 #endif // QT_NO_DATASTREAM
1001 bool QPixmap::isDetached() const
1003 return data && data->ref.load() == 1;
1007 Replaces this pixmap's data with the given \a image using the
1008 specified \a flags to control the conversion. The \a flags
1009 argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1010 Passing 0 for \a flags sets all the default options. Returns true
1011 if the result is that this pixmap is not null.
1013 Note: this function was part of Qt 3 support in Qt 4.6 and earlier.
1014 It has been promoted to official API status in 4.7 to support updating
1015 the pixmap's image without creating a new QPixmap as fromImage() would.
1020 bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
1022 if (image.isNull() || !data)
1023 *this = QPixmap::fromImage(image, flags);
1025 data->fromImage(image, flags);
1030 \fn QPixmap QPixmap::scaled(int width, int height,
1031 Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode
1032 transformMode) const
1036 Returns a copy of the pixmap scaled to a rectangle with the given
1037 \a width and \a height according to the given \a aspectRatioMode and
1040 If either the \a width or the \a height is zero or negative, this
1041 function returns a null pixmap.
1045 \fn QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode
1046 aspectRatioMode, Qt::TransformationMode transformMode) const
1048 Scales the pixmap to the given \a size, using the aspect ratio and
1049 transformation modes specified by \a aspectRatioMode and \a
1052 \image qimage-scaling.png
1055 \li If \a aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap
1056 is scaled to \a size.
1057 \li If \a aspectRatioMode is Qt::KeepAspectRatio, the pixmap is
1058 scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
1059 \li If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
1060 the pixmap is scaled to a rectangle as small as possible
1061 outside \a size, preserving the aspect ratio.
1064 If the given \a size is empty, this function returns a null
1068 In some cases it can be more beneficial to draw the pixmap to a
1069 painter with a scale set rather than scaling the pixmap. This is
1070 the case when the painter is for instance based on OpenGL or when
1071 the scale factor changes rapidly.
1073 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1077 QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
1080 qWarning("QPixmap::scaled: Pixmap is a null pixmap");
1086 QSize newSize = size();
1087 newSize.scale(s, aspectMode);
1088 newSize.rwidth() = qMax(newSize.width(), 1);
1089 newSize.rheight() = qMax(newSize.height(), 1);
1090 if (newSize == size())
1093 QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(),
1094 (qreal)newSize.height() / height());
1095 QPixmap pix = transformed(wm, mode);
1100 \fn QPixmap QPixmap::scaledToWidth(int width, Qt::TransformationMode
1103 Returns a scaled copy of the image. The returned image is scaled
1104 to the given \a width using the specified transformation \a mode.
1105 The height of the pixmap is automatically calculated so that the
1106 aspect ratio of the pixmap is preserved.
1108 If \a width is 0 or negative, a null pixmap is returned.
1110 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1113 QPixmap QPixmap::scaledToWidth(int w, Qt::TransformationMode mode) const
1116 qWarning("QPixmap::scaleWidth: Pixmap is a null pixmap");
1122 qreal factor = (qreal) w / width();
1123 QTransform wm = QTransform::fromScale(factor, factor);
1124 return transformed(wm, mode);
1128 \fn QPixmap QPixmap::scaledToHeight(int height,
1129 Qt::TransformationMode mode) const
1131 Returns a scaled copy of the image. The returned image is scaled
1132 to the given \a height using the specified transformation \a mode.
1133 The width of the pixmap is automatically calculated so that the
1134 aspect ratio of the pixmap is preserved.
1136 If \a height is 0 or negative, a null pixmap is returned.
1138 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1141 QPixmap QPixmap::scaledToHeight(int h, Qt::TransformationMode mode) const
1144 qWarning("QPixmap::scaleHeight: Pixmap is a null pixmap");
1150 qreal factor = (qreal) h / height();
1151 QTransform wm = QTransform::fromScale(factor, factor);
1152 return transformed(wm, mode);
1156 Returns a copy of the pixmap that is transformed using the given
1157 transformation \a transform and transformation \a mode. The original
1158 pixmap is not changed.
1160 The transformation \a transform is internally adjusted to compensate
1161 for unwanted translation; i.e. the pixmap produced is the smallest
1162 pixmap that contains all the transformed points of the original
1163 pixmap. Use the trueMatrix() function to retrieve the actual
1164 matrix used for transforming the pixmap.
1166 This function is slow because it involves transformation to a
1167 QImage, non-trivial computations and a transformation back to a
1170 \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap
1173 QPixmap QPixmap::transformed(const QTransform &transform,
1174 Qt::TransformationMode mode) const
1176 if (isNull() || transform.type() <= QTransform::TxTranslate)
1179 return data->transformed(transform, mode);
1185 This convenience function loads the \a matrix into a
1186 QTransform and calls the overloaded function.
1188 QPixmap QPixmap::transformed(const QMatrix &matrix, Qt::TransformationMode mode) const
1190 return transformed(QTransform(matrix), mode);
1203 \brief The QPixmap class is an off-screen image representation
1204 that can be used as a paint device.
1210 Qt provides four classes for handling image data: QImage, QPixmap,
1211 QBitmap and QPicture. QImage is designed and optimized for I/O,
1212 and for direct pixel access and manipulation, while QPixmap is
1213 designed and optimized for showing images on screen. QBitmap is
1214 only a convenience class that inherits QPixmap, ensuring a depth
1215 of 1. The isQBitmap() function returns true if a QPixmap object is
1216 really a bitmap, otherwise returns false. Finally, the QPicture class
1217 is a paint device that records and replays QPainter commands.
1219 A QPixmap can easily be displayed on the screen using QLabel or
1220 one of QAbstractButton's subclasses (such as QPushButton and
1221 QToolButton). QLabel has a pixmap property, whereas
1222 QAbstractButton has an icon property.
1224 In addition to the ordinary constructors, a QPixmap can be
1225 constructed using the static grabWidget() and grabWindow()
1226 functions which creates a QPixmap and paints the given widget, or
1229 QPixmap objects can be passed around by value since the QPixmap
1230 class uses implicit data sharing. For more information, see the \l
1231 {Implicit Data Sharing} documentation. QPixmap objects can also be
1234 Note that the pixel data in a pixmap is internal and is managed by
1235 the underlying window system. Because QPixmap is a QPaintDevice
1236 subclass, QPainter can be used to draw directly onto pixmaps.
1237 Pixels can only be accessed through QPainter functions or by
1238 converting the QPixmap to a QImage. However, the fill() function
1239 is available for initializing the entire pixmap with a given color.
1241 There are functions to convert between QImage and
1242 QPixmap. Typically, the QImage class is used to load an image
1243 file, optionally manipulating the image data, before the QImage
1244 object is converted into a QPixmap to be shown on
1245 screen. Alternatively, if no manipulation is desired, the image
1246 file can be loaded directly into a QPixmap. On Windows, the
1247 QPixmap class also supports conversion between \c HBITMAP and
1250 QPixmap provides a collection of functions that can be used to
1251 obtain a variety of information about the pixmap. In addition,
1252 there are several functions that enables transformation of the
1257 \section1 Reading and Writing Image Files
1259 QPixmap provides several ways of reading an image file: The file
1260 can be loaded when constructing the QPixmap object, or by using
1261 the load() or loadFromData() functions later on. When loading an
1262 image, the file name can either refer to an actual file on disk or
1263 to one of the application's embedded resources. See \l{The Qt
1264 Resource System} overview for details on how to embed images and
1265 other resource files in the application's executable.
1267 Simply call the save() function to save a QPixmap object.
1269 The complete list of supported file formats are available through
1270 the QImageReader::supportedImageFormats() and
1271 QImageWriter::supportedImageFormats() functions. New file formats
1272 can be added as plugins. By default, Qt supports the following
1276 \header \li Format \li Description \li Qt's support
1277 \row \li BMP \li Windows Bitmap \li Read/write
1278 \row \li GIF \li Graphic Interchange Format (optional) \li Read
1279 \row \li JPG \li Joint Photographic Experts Group \li Read/write
1280 \row \li JPEG \li Joint Photographic Experts Group \li Read/write
1281 \row \li PNG \li Portable Network Graphics \li Read/write
1282 \row \li PBM \li Portable Bitmap \li Read
1283 \row \li PGM \li Portable Graymap \li Read
1284 \row \li PPM \li Portable Pixmap \li Read/write
1285 \row \li XBM \li X11 Bitmap \li Read/write
1286 \row \li XPM \li X11 Pixmap \li Read/write
1289 \section1 Pixmap Information
1291 QPixmap provides a collection of functions that can be used to
1292 obtain a variety of information about the pixmap:
1296 \li \li Available Functions
1300 The size(), width() and height() functions provide information
1301 about the pixmap's size. The rect() function returns the image's
1302 enclosing rectangle.
1308 The hasAlphaChannel() returns true if the pixmap has a format that
1309 respects the alpha channel, otherwise returns false. The hasAlpha(),
1310 setMask() and mask() functions are legacy and should not be used.
1311 They are potentially very slow.
1313 The createHeuristicMask() function creates and returns a 1-bpp
1314 heuristic mask (i.e. a QBitmap) for this pixmap. It works by
1315 selecting a color from one of the corners and then chipping away
1316 pixels of that color, starting at all the edges. The
1317 createMaskFromColor() function creates and returns a mask (i.e. a
1318 QBitmap) for the pixmap based on a given color.
1321 \li Low-level information
1324 The depth() function returns the depth of the pixmap. The
1325 defaultDepth() function returns the default depth, i.e. the depth
1326 used by the application on the given screen.
1328 The cacheKey() function returns a number that uniquely
1329 identifies the contents of the QPixmap object.
1331 The x11Info() function returns information about the configuration
1332 of the X display used by the screen to which the pixmap currently
1333 belongs. The x11PictureHandle() function returns the X11 Picture
1334 handle of the pixmap for XRender support. Note that the two latter
1335 functions are only available on x11.
1339 \section1 Pixmap Conversion
1341 A QPixmap object can be converted into a QImage using the
1342 toImage() function. Likewise, a QImage can be converted into a
1343 QPixmap using the fromImage(). If this is too expensive an
1344 operation, you can use QBitmap::fromImage() instead.
1346 In addition, on Windows, the QPixmap class supports conversion to
1347 and from HBITMAP: the toWinHBITMAP() function creates a HBITMAP
1348 equivalent to the QPixmap, based on the given HBitmapFormat, and
1349 returns the HBITMAP handle. The fromWinHBITMAP() function returns
1350 a QPixmap that is equivalent to the given bitmap which has the
1351 specified format. The QPixmap class also supports conversion to
1352 and from HICON: the toWinHICON() function creates a HICON equivalent
1353 to the QPixmap, and returns the HICON handle. The fromWinHICON()
1354 function returns a QPixmap that is equivalent to the given icon.
1356 \section1 Pixmap Transformations
1358 QPixmap supports a number of functions for creating a new pixmap
1359 that is a transformed version of the original:
1361 The scaled(), scaledToWidth() and scaledToHeight() functions
1362 return scaled copies of the pixmap, while the copy() function
1363 creates a QPixmap that is a plain copy of the original one.
1365 The transformed() function returns a copy of the pixmap that is
1366 transformed with the given transformation matrix and
1367 transformation mode: Internally, the transformation matrix is
1368 adjusted to compensate for unwanted translation,
1369 i.e. transformed() returns the smallest pixmap containing all
1370 transformed points of the original pixmap. The static trueMatrix()
1371 function returns the actual matrix used for transforming the
1374 \note When using the native X11 graphics system, the pixmap
1375 becomes invalid when the QApplication instance is destroyed.
1377 \sa QBitmap, QImage, QImageReader, QImageWriter
1382 \typedef QPixmap::DataPtr
1387 \fn DataPtr &QPixmap::data_ptr()
1392 Returns true if this pixmap has an alpha channel, \e or has a
1393 mask, otherwise returns false.
1395 \sa hasAlphaChannel(), mask()
1397 bool QPixmap::hasAlpha() const
1399 return data && data->hasAlphaChannel();
1403 Returns true if the pixmap has a format that respects the alpha
1404 channel, otherwise returns false.
1408 bool QPixmap::hasAlphaChannel() const
1410 return data && data->hasAlphaChannel();
1416 int QPixmap::metric(PaintDeviceMetric metric) const
1418 return data ? data->metric(metric) : 0;
1424 QPaintEngine *QPixmap::paintEngine() const
1426 return data ? data->paintEngine() : 0;
1430 \fn QBitmap QPixmap::mask() const
1432 Extracts a bitmap mask from the pixmap's alpha channel.
1434 \warning This is potentially an expensive operation. The mask of
1435 the pixmap is extracted dynamically from the pixeldata.
1437 \sa setMask(), {QPixmap#Pixmap Information}{Pixmap Information}
1439 QBitmap QPixmap::mask() const
1441 if (!data || !hasAlphaChannel())
1444 const QImage img = toImage();
1445 const QImage image = (img.depth() < 32 ? img.convertToFormat(QImage::Format_ARGB32_Premultiplied) : img);
1446 const int w = image.width();
1447 const int h = image.height();
1449 QImage mask(w, h, QImage::Format_MonoLSB);
1450 if (mask.isNull()) // allocation failed
1453 mask.setColorCount(2);
1454 mask.setColor(0, QColor(Qt::color0).rgba());
1455 mask.setColor(1, QColor(Qt::color1).rgba());
1457 const int bpl = mask.bytesPerLine();
1459 for (int y = 0; y < h; ++y) {
1460 const QRgb *src = reinterpret_cast<const QRgb*>(image.scanLine(y));
1461 uchar *dest = mask.scanLine(y);
1462 memset(dest, 0, bpl);
1463 for (int x = 0; x < w; ++x) {
1464 if (qAlpha(*src) > 0)
1465 dest[x >> 3] |= (1 << (x & 7));
1470 return QBitmap::fromImage(mask);
1474 Returns the default pixmap depth used by the application.
1476 On all platforms the depth of the primary screen will be returned.
1478 \sa depth(), QColormap::depth(), {QPixmap#Pixmap Information}{Pixmap Information}
1481 int QPixmap::defaultDepth()
1483 return QGuiApplication::primaryScreen()->depth();
1487 Detaches the pixmap from shared pixmap data.
1489 A pixmap is automatically detached by Qt whenever its contents are
1490 about to change. This is done in almost all QPixmap member
1491 functions that modify the pixmap (fill(), fromImage(),
1492 load(), etc.), and in QPainter::begin() on a pixmap.
1494 There are two exceptions in which detach() must be called
1495 explicitly, that is when calling the handle() or the
1496 x11PictureHandle() function (only available on X11). Otherwise,
1497 any modifications done using system calls, will be performed on
1500 The detach() function returns immediately if there is just a
1501 single reference or if the pixmap has not been initialized yet.
1503 void QPixmap::detach()
1508 // QPixmap.data member may be QRuntimePlatformPixmap so use handle() function to get
1509 // the actual underlaying runtime pixmap data.
1510 QPlatformPixmap *pd = handle();
1511 QPlatformPixmap::ClassId id = pd->classId();
1512 if (id == QPlatformPixmap::RasterClass) {
1513 QRasterPlatformPixmap *rasterData = static_cast<QRasterPlatformPixmap*>(pd);
1514 rasterData->image.detach();
1517 if (data->is_cached && data->ref.load() == 1)
1518 QImagePixmapCleanupHooks::executePlatformPixmapModificationHooks(data.data());
1520 if (data->ref.load() != 1) {
1527 \fn QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1529 Converts the given \a image to a pixmap using the specified \a
1530 flags to control the conversion. The \a flags argument is a
1531 bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a
1532 flags sets all the default options.
1534 In case of monochrome and 8-bit images, the image is first
1535 converted to a 32-bit pixmap and then filled with the colors in
1536 the color table. If this is too expensive an operation, you can
1537 use QBitmap::fromImage() instead.
1539 \sa fromImageReader(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1541 QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1546 QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1547 data->fromImage(image, flags);
1548 return QPixmap(data.take());
1552 \fn QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
1554 Create a QPixmap from an image read directly from an \a imageReader.
1555 The \a flags argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1556 Passing 0 for \a flags sets all the default options.
1558 On some systems, reading an image directly to QPixmap can use less memory than
1559 reading a QImage to convert it to QPixmap.
1561 \sa fromImage(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1563 QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
1565 QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1566 data->fromImageReader(imageReader, flags);
1567 return QPixmap(data.take());
1571 \fn QPixmap QPixmap::grabWindow(WId window, int x, int y, int
1574 Creates and returns a pixmap constructed by grabbing the contents
1575 of the given \a window restricted by QRect(\a x, \a y, \a width,
1578 The arguments (\a{x}, \a{y}) specify the offset in the window,
1579 whereas (\a{width}, \a{height}) specify the area to be copied. If
1580 \a width is negative, the function copies everything to the right
1581 border of the window. If \a height is negative, the function
1582 copies everything to the bottom of the window.
1584 The window system identifier (\c WId) can be retrieved using the
1585 QWidget::winId() function. The rationale for using a window
1586 identifier and not a QWidget, is to enable grabbing of windows
1587 that are not part of the application, window system frames, and so
1590 The grabWindow() function grabs pixels from the screen, not from
1591 the window, i.e. if there is another window partially or entirely
1592 over the one you grab, you get pixels from the overlying window,
1593 too. The mouse cursor is generally not grabbed.
1595 Note on X11 that if the given \a window doesn't have the same depth
1596 as the root window, and another window partially or entirely
1597 obscures the one you grab, you will \e not get pixels from the
1598 overlying window. The contents of the obscured areas in the
1599 pixmap will be undefined and uninitialized.
1601 On Windows Vista and above grabbing a layered window, which is
1602 created by setting the Qt::WA_TranslucentBackground attribute, will
1603 not work. Instead grabbing the desktop widget should work.
1605 \warning In general, grabbing an area outside the screen is not
1606 safe. This depends on the underlying window system.
1608 \warning The function is deprecated in Qt 5.0 since there might be
1609 platform plugins in which window system identifiers (\c WId)
1610 are local to a screen. Use QScreen::grabWindow() instead.
1612 \sa grabWidget(), {Screenshot Example}
1617 QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h)
1619 qWarning("%s is deprecated, use QScreen::grabWindow() instead."
1620 " Defaulting to primary screen.", Q_FUNC_INFO);
1621 return QGuiApplication::primaryScreen()->grabWindow(window, x, y, w, h);
1627 QPlatformPixmap* QPixmap::handle() const
1632 #ifndef QT_NO_DEBUG_STREAM
1633 QDebug operator<<(QDebug dbg, const QPixmap &r)
1635 dbg.nospace() << "QPixmap(" << r.size() << ')';