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