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