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