Coverage Report

Created: 2026-08-17 07:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qtbase/src/gui/image/qbmphandler.cpp
Line
Count
Source
1
// Copyright (C) 2016 The Qt Company Ltd.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
// Qt-Security score:critical reason:data-parser
4
5
#include "private/qbmphandler_p.h"
6
7
#ifndef QT_NO_IMAGEFORMAT_BMP
8
9
#include <qimage.h>
10
#include <qlist.h>
11
#include <qvariant.h>
12
13
QT_BEGIN_NAMESPACE
14
15
static void swapPixel01(QImage *image)        // 1-bpp: swap 0 and 1 pixels
16
119
{
17
119
    qsizetype i;
18
119
    if (image->depth() == 1 && image->colorCount() == 2) {
19
119
        uint *p = (uint *)image->bits();
20
119
        qsizetype nbytes = static_cast<qsizetype>(image->sizeInBytes());
21
38.7M
        for (i=0; i<nbytes/4; i++) {
22
38.7M
            *p = ~*p;
23
38.7M
            p++;
24
38.7M
        }
25
119
        uchar *p2 = (uchar *)p;
26
119
        for (i=0; i<(nbytes&3); i++) {
27
0
            *p2 = ~*p2;
28
0
            p2++;
29
0
        }
30
119
        QRgb t = image->color(0);                // swap color 0 and 1
31
119
        image->setColor(0, image->color(1));
32
119
        image->setColor(1, t);
33
119
    }
34
119
}
35
36
/*
37
    QImageIO::defineIOHandler("BMP", "^BM", 0,
38
                               read_bmp_image, write_bmp_image);
39
*/
40
41
/*****************************************************************************
42
  BMP (DIB) image read/write functions
43
 *****************************************************************************/
44
45
const int BMP_FILEHDR_SIZE = 14;                // size of BMP_FILEHDR data
46
47
static QDataStream &operator>>(QDataStream &s, BMP_FILEHDR &bf)
48
2.98k
{                                                // read file header
49
2.98k
    s.readRawData(bf.bfType, 2);
50
2.98k
    s >> bf.bfSize >> bf.bfReserved1 >> bf.bfReserved2 >> bf.bfOffBits;
51
2.98k
    return s;
52
2.98k
}
53
54
static QDataStream &operator<<(QDataStream &s, const BMP_FILEHDR &bf)
55
0
{                                                // write file header
56
0
    s.writeRawData(bf.bfType, 2);
57
0
    s << bf.bfSize << bf.bfReserved1 << bf.bfReserved2 << bf.bfOffBits;
58
0
    return s;
59
0
}
60
61
62
const int BMP_OLD  = 12;                        // old Windows/OS2 BMP size
63
const int BMP_WIN  = 40;                        // Windows BMP v3 size
64
const int BMP_OS2  = 64;                        // new OS/2 BMP size
65
const int BMP_WIN4 = 108;                       // Windows BMP v4 size
66
const int BMP_WIN5 = 124;                       // Windows BMP v5 size
67
68
const int BMP_RGB  = 0;                                // no compression
69
const int BMP_RLE8 = 1;                                // run-length encoded, 8 bits
70
const int BMP_RLE4 = 2;                                // run-length encoded, 4 bits
71
const int BMP_BITFIELDS = 3;                        // RGB values encoded in data as bit-fields
72
const int BMP_ALPHABITFIELDS = 4;                   // RGBA values encoded in data as bit-fields
73
74
75
static QDataStream &operator>>(QDataStream &s, BMP_INFOHDR &bi)
76
2.91k
{
77
2.91k
    s >> bi.biSize;
78
2.91k
    if (bi.biSize == BMP_WIN || bi.biSize == BMP_OS2 || bi.biSize == BMP_WIN4 || bi.biSize == BMP_WIN5) {
79
1.87k
        s >> bi.biWidth >> bi.biHeight >> bi.biPlanes >> bi.biBitCount;
80
1.87k
        s >> bi.biCompression >> bi.biSizeImage;
81
1.87k
        s >> bi.biXPelsPerMeter >> bi.biYPelsPerMeter;
82
1.87k
        s >> bi.biClrUsed >> bi.biClrImportant;
83
1.87k
        if (bi.biSize >= BMP_WIN4) {
84
583
            s >> bi.biRedMask >> bi.biGreenMask >> bi.biBlueMask >> bi.biAlphaMask;
85
583
            s >> bi.biCSType;
86
5.83k
            for (int i = 0; i < 9; ++i)
87
5.24k
                s >> bi.biEndpoints[i];
88
583
            s >> bi.biGammaRed >> bi.biGammaGreen >> bi.biGammaBlue;
89
583
            if (bi.biSize == BMP_WIN5)
90
410
                s >> bi.biIntent >> bi.biProfileData >> bi.biProfileSize >> bi.biReserved;
91
583
        }
92
1.87k
    }
93
1.04k
    else {                                        // probably old Windows format
94
1.04k
        qint16 w, h;
95
1.04k
        s >> w >> h >> bi.biPlanes >> bi.biBitCount;
96
1.04k
        bi.biWidth  = w;
97
1.04k
        bi.biHeight = h;
98
1.04k
        bi.biCompression = BMP_RGB;                // no compression
99
1.04k
        bi.biSizeImage = 0;
100
1.04k
        bi.biXPelsPerMeter = bi.biYPelsPerMeter = 0;
101
1.04k
        bi.biClrUsed = bi.biClrImportant = 0;
102
1.04k
    }
103
2.91k
    return s;
104
2.91k
}
105
106
static QDataStream &operator<<(QDataStream &s, const BMP_INFOHDR &bi)
107
0
{
108
0
    s << bi.biSize;
109
0
    s << bi.biWidth << bi.biHeight;
110
0
    s << bi.biPlanes;
111
0
    s << bi.biBitCount;
112
0
    s << bi.biCompression;
113
0
    s << bi.biSizeImage;
114
0
    s << bi.biXPelsPerMeter << bi.biYPelsPerMeter;
115
0
    s << bi.biClrUsed << bi.biClrImportant;
116
117
0
    if (bi.biSize >= BMP_WIN4) {
118
0
        s << bi.biRedMask << bi.biGreenMask << bi.biBlueMask << bi.biAlphaMask;
119
0
        s << bi.biCSType;
120
121
0
        for (int i = 0; i < 9; i++)
122
0
            s << bi.biEndpoints[i];
123
124
0
        s << bi.biGammaRed;
125
0
        s << bi.biGammaGreen;
126
0
        s << bi.biGammaBlue;
127
0
    }
128
129
0
    if (bi.biSize >= BMP_WIN5) {
130
0
        s << bi.biIntent;
131
0
        s << bi.biProfileData;
132
0
        s << bi.biProfileSize;
133
0
        s << bi.biReserved;
134
0
    }
135
136
0
    return s;
137
0
}
138
139
static uint calc_shift(uint mask)
140
1.87k
{
141
1.87k
    uint result = 0;
142
31.5k
    while ((mask >= 0x100) || (!(mask & 1) && mask)) {
143
29.6k
        result++;
144
29.6k
        mask >>= 1;
145
29.6k
    }
146
1.87k
    return result;
147
1.87k
}
148
149
static uint calc_scale(uint low_mask)
150
1.87k
{
151
1.87k
    uint result = 8;
152
10.2k
    while (low_mask && result) {
153
8.34k
        result--;
154
8.34k
        low_mask >>= 1;
155
8.34k
    }
156
1.87k
    return result;
157
1.87k
}
158
159
static inline uint apply_scale(uint value, uint scale)
160
5.61M
{
161
5.61M
    if (!(scale & 0x07)) // return immediately if scale == 8 or 0
162
547k
        return value;
163
164
5.06M
    uint filled = 8 - scale;
165
5.06M
    uint result = value << scale;
166
167
5.67M
    do {
168
5.67M
        result |= result >> filled;
169
5.67M
        filled <<= 1;
170
5.67M
    } while (filled < 8);
171
172
5.06M
    return result;
173
5.61M
}
174
175
static bool read_dib_fileheader(QDataStream &s, BMP_FILEHDR &bf)
176
2.98k
{
177
    // read BMP file header
178
2.98k
    if (!(s >> bf))
179
69
        return false;
180
181
    // check header
182
2.91k
    if (qstrncmp(bf.bfType,"BM",2) != 0)
183
0
        return false;
184
185
2.91k
    return true;
186
2.91k
}
187
188
static bool read_dib_infoheader(QDataStream &s, BMP_INFOHDR &bi)
189
2.91k
{
190
2.91k
    if (!(s >> bi))                                       // read BMP info header
191
180
        return false;
192
193
2.73k
    int nbits = bi.biBitCount;
194
2.73k
    int comp = bi.biCompression;
195
2.73k
    if (!(nbits == 1 || nbits == 4 || nbits == 8 || nbits == 16 || nbits == 24 || nbits == 32) ||
196
2.60k
        bi.biPlanes != 1 || comp > BMP_BITFIELDS)
197
188
        return false;                                        // weird BMP image
198
2.54k
    if (!(comp == BMP_RGB || (nbits == 4 && comp == BMP_RLE4) ||
199
1.06k
        (nbits == 8 && comp == BMP_RLE8) || ((nbits == 16 || nbits == 32) && comp == BMP_BITFIELDS)))
200
184
         return false;                                // weird compression type
201
2.35k
    if (bi.biHeight == INT_MIN)
202
7
        return false; // out of range for positive int
203
2.35k
    if (bi.biWidth <= 0 || !bi.biHeight || quint64(bi.biWidth) * qAbs(bi.biHeight) > 16384 * 16384)
204
134
        return false;
205
206
2.21k
    return true;
207
2.35k
}
208
209
static bool read_dib_body(QDataStream &s, const BMP_INFOHDR &bi, qint64 datapos, qint64 startpos, QImage &image)
210
2.21k
{
211
2.21k
    QIODevice* d = s.device();
212
2.21k
    if (d->atEnd())                                // end of stream/file
213
32
        return false;
214
#if 0
215
    qDebug("offset...........%lld", datapos);
216
    qDebug("startpos.........%lld", startpos);
217
    qDebug("biSize...........%d", bi.biSize);
218
    qDebug("biWidth..........%d", bi.biWidth);
219
    qDebug("biHeight.........%d", bi.biHeight);
220
    qDebug("biPlanes.........%d", bi.biPlanes);
221
    qDebug("biBitCount.......%d", bi.biBitCount);
222
    qDebug("biCompression....%d", bi.biCompression);
223
    qDebug("biSizeImage......%d", bi.biSizeImage);
224
    qDebug("biXPelsPerMeter..%d", bi.biXPelsPerMeter);
225
    qDebug("biYPelsPerMeter..%d", bi.biYPelsPerMeter);
226
    qDebug("biClrUsed........%d", bi.biClrUsed);
227
    qDebug("biClrImportant...%d", bi.biClrImportant);
228
#endif
229
2.18k
    int w = bi.biWidth,         h = bi.biHeight,  nbits = bi.biBitCount;
230
2.18k
    int t = bi.biSize,         comp = bi.biCompression;
231
2.18k
    uint red_mask = 0;
232
2.18k
    uint green_mask = 0;
233
2.18k
    uint blue_mask = 0;
234
2.18k
    uint alpha_mask = 0;
235
2.18k
    uint red_shift = 0;
236
2.18k
    uint green_shift = 0;
237
2.18k
    uint blue_shift = 0;
238
2.18k
    uint alpha_shift = 0;
239
2.18k
    uint red_scale = 0;
240
2.18k
    uint green_scale = 0;
241
2.18k
    uint blue_scale = 0;
242
2.18k
    uint alpha_scale = 0;
243
2.18k
    bool bitfields = comp == BMP_BITFIELDS || comp == BMP_ALPHABITFIELDS;
244
245
2.18k
    if (!d->isSequential())
246
2.18k
        d->seek(startpos + bi.biSize); // goto start of colormap or masks
247
248
2.18k
    if (bi.biSize >= BMP_WIN4) {
249
645
        red_mask = bi.biRedMask;
250
645
        green_mask = bi.biGreenMask;
251
645
        blue_mask = bi.biBlueMask;
252
645
        alpha_mask = bi.biAlphaMask;
253
1.54k
    } else if (bitfields && (nbits == 16 || nbits == 32)) {
254
311
        if (d->read((char *)&red_mask, sizeof(red_mask)) != sizeof(red_mask))
255
16
            return false;
256
295
        if (d->read((char *)&green_mask, sizeof(green_mask)) != sizeof(green_mask))
257
14
            return false;
258
281
        if (d->read((char *)&blue_mask, sizeof(blue_mask)) != sizeof(blue_mask))
259
11
            return false;
260
270
        if (comp == BMP_ALPHABITFIELDS && d->read((char *)&alpha_mask, sizeof(alpha_mask)) != sizeof(alpha_mask))
261
0
            return false;
262
270
    }
263
264
2.14k
    bool transp = bitfields || (comp == BMP_RGB && nbits == 32 && alpha_mask == 0xff000000);
265
2.14k
    transp = transp && alpha_mask;
266
267
2.14k
    int ncols = 0;
268
2.14k
    int depth = 0;
269
2.14k
    QImage::Format format;
270
2.14k
    switch (nbits) {
271
373
        case 32:
272
399
        case 24:
273
699
        case 16:
274
699
            depth = 32;
275
699
            format = transp ? QImage::Format_ARGB32 : QImage::Format_RGB32;
276
699
            break;
277
447
        case 8:
278
993
        case 4:
279
993
            depth = 8;
280
993
            format = QImage::Format_Indexed8;
281
993
            break;
282
453
        case 1:
283
453
            depth = 1;
284
453
            format = QImage::Format_Mono;
285
453
            break;
286
0
        default:
287
0
            return false;
288
0
            break;
289
2.14k
    }
290
291
2.14k
    if (depth != 32) {
292
1.44k
        ncols = bi.biClrUsed ? bi.biClrUsed : 1 << nbits;
293
1.44k
        if (ncols < 1 || ncols > 256) // sanity check - don't run out of mem if color table is broken
294
95
            return false;
295
1.44k
    }
296
297
2.05k
    if (bi.biHeight < 0)
298
869
        h = -h;                  // support images with negative height
299
300
2.05k
    if (!QImageIOHandler::allocateImage(QSize(w, h), format, &image))
301
25
        return false;
302
2.02k
    image.fill(0);
303
2.02k
    if (ncols > 0) {                                // read color table
304
1.34k
        image.setColorCount(ncols);
305
1.34k
        uchar rgb[4];
306
1.34k
        int   rgb_len = t == BMP_OLD ? 3 : 4;
307
29.2k
        for (int i=0; i<ncols; i++) {
308
28.1k
            if (d->read((char *)rgb, rgb_len) != rgb_len)
309
203
                return false;
310
27.9k
            image.setColor(i, qRgb(rgb[2],rgb[1],rgb[0]));
311
27.9k
            if (d->atEnd())                        // truncated file
312
114
                return false;
313
27.9k
        }
314
1.34k
    } else if (bitfields && (nbits == 16 || nbits == 32)) {
315
467
        red_shift = calc_shift(red_mask);
316
467
        if (((red_mask >> red_shift) + 1) == 0)
317
0
            return false;
318
467
        red_scale = calc_scale(red_mask >> red_shift);
319
467
        green_shift = calc_shift(green_mask);
320
467
        if (((green_mask >> green_shift) + 1) == 0)
321
0
            return false;
322
467
        green_scale = calc_scale(green_mask >> green_shift);
323
467
        blue_shift = calc_shift(blue_mask);
324
467
        if (((blue_mask >> blue_shift) + 1) == 0)
325
0
            return false;
326
467
        blue_scale = calc_scale(blue_mask >> blue_shift);
327
467
        alpha_shift = calc_shift(alpha_mask);
328
467
        if (((alpha_mask >> alpha_shift) + 1) == 0)
329
0
            return false;
330
467
        alpha_scale = calc_scale(alpha_mask >> alpha_shift);
331
467
    } else if (comp == BMP_RGB && (nbits == 24 || nbits == 32)) {
332
168
        blue_mask = 0x000000ff;
333
168
        green_mask = 0x0000ff00;
334
168
        red_mask = 0x00ff0000;
335
168
        blue_shift = 0;
336
168
        green_shift = 8;
337
168
        red_shift = 16;
338
168
        blue_scale = green_scale = red_scale = 0;
339
168
        if (transp) {
340
7
            alpha_shift = calc_shift(alpha_mask);
341
7
            if (((alpha_mask >> alpha_shift) + 1) == 0)
342
0
                return false;
343
7
            alpha_scale = calc_scale(alpha_mask >> alpha_shift);
344
7
        }
345
168
    } else if (comp == BMP_RGB && nbits == 16) {
346
50
        blue_mask = 0x001f;
347
50
        green_mask = 0x03e0;
348
50
        red_mask = 0x7c00;
349
50
        blue_shift = 0;
350
50
        green_shift = 5;
351
50
        red_shift = 10;
352
50
        blue_scale = green_scale = red_scale = 3;
353
50
    }
354
355
1.70k
    image.setDotsPerMeterX(bi.biXPelsPerMeter);
356
1.70k
    image.setDotsPerMeterY(bi.biYPelsPerMeter);
357
358
#if 0
359
    qDebug("Rmask: %08x Rshift: %08x Rscale:%08x", red_mask, red_shift, red_scale);
360
    qDebug("Gmask: %08x Gshift: %08x Gscale:%08x", green_mask, green_shift, green_scale);
361
    qDebug("Bmask: %08x Bshift: %08x Bscale:%08x", blue_mask, blue_shift, blue_scale);
362
    qDebug("Amask: %08x Ashift: %08x Ascale:%08x", alpha_mask, alpha_shift, alpha_scale);
363
#endif
364
365
1.70k
    if (datapos >= 0 && datapos > d->pos()) {
366
465
        if (!d->isSequential())
367
465
            d->seek(datapos); // start of image data
368
465
    }
369
370
1.70k
    int             bpl = image.bytesPerLine();
371
1.70k
    uchar *data = image.bits();
372
373
1.70k
    if (nbits == 1) {                                // 1 bit BMP image
374
67.9k
        while (--h >= 0) {
375
67.9k
            if (d->read((char*)(data + h*bpl), bpl) != bpl)
376
208
                break;
377
67.9k
        }
378
222
        if (ncols == 2 && qGray(image.color(0)) < qGray(image.color(1)))
379
119
            swapPixel01(&image);                // pixel 0 is white!
380
222
    }
381
382
1.48k
    else if (nbits == 4) {                        // 4 bit BMP image
383
445
        int    buflen = ((w+7)/8)*4;
384
445
        uchar *buf    = new uchar[buflen];
385
445
        if (comp == BMP_RLE4) {                // run length compression
386
303
            int x=0, y=0, c, i;
387
303
            quint8 b;
388
303
            uchar *p = data + (h-1)*bpl;
389
303
            const uchar *endp = p + w;
390
712k
            while (y < h) {
391
712k
                if (!d->getChar((char *)&b))
392
245
                    break;
393
712k
                if (b == 0) {                        // escape code
394
11.4k
                    if (!d->getChar((char *)&b) || b == 1) {
395
46
                        y = h;                // exit loop
396
11.3k
                    } else switch (b) {
397
6.30k
                        case 0:                        // end of line
398
6.30k
                            x = 0;
399
6.30k
                            y++;
400
6.30k
                            p = data + (h-y-1)*bpl;
401
6.30k
                            break;
402
2.25k
                        case 2:                        // delta (jump)
403
2.25k
                        {
404
2.25k
                            quint8 tmp = 0;
405
2.25k
                            d->getChar((char *)&tmp);
406
2.25k
                            x += tmp;
407
2.25k
                            d->getChar((char *)&tmp);
408
2.25k
                            y += tmp;
409
2.25k
                        }
410
411
                            // Protection
412
2.25k
                            if ((uint)x >= (uint)w)
413
1.36k
                                x = w-1;
414
2.25k
                            if ((uint)y >= (uint)h)
415
417
                                y = h-1;
416
417
2.25k
                            p = data + (h-y-1)*bpl + x;
418
2.25k
                            break;
419
2.82k
                        default:                // absolute mode
420
                            // Protection
421
2.82k
                            if (p + b > endp)
422
900
                                b = endp-p;
423
424
2.82k
                            i = (c = b)/2;
425
57.9k
                            while (i--) {
426
55.1k
                                d->getChar((char *)&b);
427
55.1k
                                *p++ = b >> 4;
428
55.1k
                                *p++ = b & 0x0f;
429
55.1k
                            }
430
2.82k
                            if (c & 1) {
431
949
                                unsigned char tmp = 0;
432
949
                                d->getChar((char *)&tmp);
433
949
                                *p++ = tmp >> 4;
434
949
                            }
435
2.82k
                            if ((((c & 3) + 1) & 2) == 2)
436
693
                                d->getChar(nullptr);        // align on word boundary
437
2.82k
                            x += c;
438
11.3k
                    }
439
700k
                } else {                        // encoded mode
440
                    // Protection
441
700k
                    if (p + b > endp)
442
11.8k
                        b = endp-p;
443
444
700k
                    i = (c = b)/2;
445
700k
                    d->getChar((char *)&b);                // 2 pixels to be repeated
446
29.0M
                    while (i--) {
447
28.3M
                        *p++ = b >> 4;
448
28.3M
                        *p++ = b & 0x0f;
449
28.3M
                    }
450
700k
                    if (c & 1)
451
249k
                        *p++ = b >> 4;
452
700k
                    x += c;
453
700k
                }
454
712k
            }
455
303
        } else if (comp == BMP_RGB) {                // no compression
456
3.56k
            while (--h >= 0) {
457
3.54k
                if (d->read((char*)buf,buflen) != buflen)
458
125
                    break;
459
3.41k
                uchar *p = data + h*bpl;
460
3.41k
                uchar *b = buf;
461
38.0k
                for (int i=0; i<w/2; i++) {        // convert nibbles to bytes
462
34.6k
                    *p++ = *b >> 4;
463
34.6k
                    *p++ = *b++ & 0x0f;
464
34.6k
                }
465
3.41k
                if (w & 1)                        // the last nibble
466
2.22k
                    *p = *b >> 4;
467
3.41k
            }
468
142
        }
469
445
        delete [] buf;
470
445
    }
471
472
1.04k
    else if (nbits == 8) {                        // 8 bit BMP image
473
356
        if (comp == BMP_RLE8) {                // run length compression
474
291
            int x=0, y=0;
475
291
            quint8 b;
476
291
            uchar *p = data + (h-1)*bpl;
477
291
            const uchar *endp = p + w;
478
255k
            while (y < h) {
479
255k
                if (!d->getChar((char *)&b))
480
134
                    break;
481
255k
                if (b == 0) {                        // escape code
482
67.0k
                    if (!d->getChar((char *)&b) || b == 1) {
483
65
                            y = h;                // exit loop
484
66.9k
                    } else switch (b) {
485
54.6k
                        case 0:                        // end of line
486
54.6k
                            x = 0;
487
54.6k
                            y++;
488
54.6k
                            p = data + (h-y-1)*bpl;
489
54.6k
                            break;
490
2.53k
                        case 2:                        // delta (jump)
491
2.53k
                            {
492
2.53k
                                quint8 tmp = 0;
493
2.53k
                                d->getChar((char *)&tmp);
494
2.53k
                                x += tmp;
495
2.53k
                                d->getChar((char *)&tmp);
496
2.53k
                                y += tmp;
497
2.53k
                            }
498
499
                            // Protection
500
2.53k
                            if ((uint)x >= (uint)w)
501
1.61k
                                x = w-1;
502
2.53k
                            if ((uint)y >= (uint)h)
503
291
                                y = h-1;
504
505
2.53k
                            p = data + (h-y-1)*bpl + x;
506
2.53k
                            break;
507
9.81k
                        default:                // absolute mode
508
                            // Protection
509
9.81k
                            if (p + b > endp)
510
630
                                b = endp-p;
511
512
9.81k
                            if (d->read((char *)p, b) != b)
513
84
                                return false;
514
9.72k
                            if ((b & 1) == 1)
515
4.83k
                                d->getChar(nullptr);        // align on word boundary
516
9.72k
                            x += b;
517
9.72k
                            p += b;
518
66.9k
                    }
519
188k
                } else {                        // encoded mode
520
                    // Protection
521
188k
                    if (p + b > endp)
522
88.0k
                        b = endp-p;
523
524
188k
                    char tmp = 0;
525
188k
                    d->getChar(&tmp);
526
188k
                    memset(p, tmp, b); // repeat pixel
527
188k
                    x += b;
528
188k
                    p += b;
529
188k
                }
530
255k
            }
531
291
        } else if (comp == BMP_RGB) {                // uncompressed
532
700
            while (--h >= 0) {
533
692
                if (d->read((char *)data + h*bpl, bpl) != bpl)
534
57
                    break;
535
692
            }
536
65
        }
537
356
    }
538
539
685
    else if (nbits == 16 || nbits == 24 || nbits == 32) { // 16,24,32 bit BMP image
540
685
        QRgb *p;
541
685
        QRgb  *end;
542
685
        uchar *buf24 = new uchar[bpl];
543
685
        qint64 bpl24 = ((qint64(w)*nbits+31)/32)*4;
544
685
        uchar *b;
545
685
        int c;
546
547
112k
        while (--h >= 0) {
548
112k
            p = (QRgb *)(data + h*bpl);
549
112k
            end = p + w;
550
112k
            if (d->read((char *)buf24,bpl24) != bpl24)
551
671
                break;
552
111k
            b = buf24;
553
1.98M
            while (p < end) {
554
1.86M
                c = *(uchar*)b | (*(uchar*)(b+1)<<8);
555
1.86M
                if (nbits > 16)
556
7.86k
                    c |= *(uchar*)(b+2)<<16;
557
1.86M
                if (nbits > 24)
558
7.68k
                    c |= *(uchar*)(b+3)<<24;
559
1.86M
                *p++ = qRgba(apply_scale((c & red_mask) >> red_shift, red_scale),
560
1.86M
                             apply_scale((c & green_mask) >> green_shift, green_scale),
561
1.86M
                             apply_scale((c & blue_mask) >> blue_shift, blue_scale),
562
1.86M
                             transp ? apply_scale((c & alpha_mask) >> alpha_shift, alpha_scale) : 0xff);
563
1.86M
                b += nbits/8;
564
1.86M
            }
565
111k
        }
566
685
        delete[] buf24;
567
685
    }
568
569
1.62k
    if (bi.biHeight < 0) {
570
        // Flip the image
571
689
        uchar *buf = new uchar[bpl];
572
689
        h = -bi.biHeight;
573
997M
        for (int y = 0; y < h/2; ++y) {
574
997M
            memcpy(buf, data + y*bpl, bpl);
575
997M
            memcpy(data + y*bpl, data + (h-y-1)*bpl, bpl);
576
997M
            memcpy(data + (h-y-1)*bpl, buf, bpl);
577
997M
        }
578
689
        delete [] buf;
579
689
    }
580
581
1.62k
    return true;
582
1.70k
}
583
584
bool qt_write_dib(QDataStream &s, const QImage &image, int bpl, int bpl_bmp, int nbits)
585
0
{
586
0
    QIODevice* d = s.device();
587
0
    if (!d->isWritable())
588
0
        return false;
589
590
0
    BMP_INFOHDR bi = { };
591
0
    bi.biSize               = BMP_WIN;                // build info header
592
0
    bi.biWidth               = image.width();
593
0
    bi.biHeight               = image.height();
594
0
    bi.biPlanes               = 1;
595
0
    bi.biBitCount      = nbits;
596
0
    bi.biCompression   = BMP_RGB;
597
0
    bi.biSizeImage     = bpl_bmp*image.height();
598
0
    bi.biXPelsPerMeter = image.dotsPerMeterX() ? image.dotsPerMeterX()
599
0
                                                : 2834; // 72 dpi default
600
0
    bi.biYPelsPerMeter = image.dotsPerMeterY() ? image.dotsPerMeterY() : 2834;
601
0
    bi.biClrUsed       = image.colorCount();
602
0
    bi.biClrImportant  = image.colorCount();
603
0
    if (!(s << bi))                                        // write info header
604
0
        return false;
605
606
0
    if (image.depth() != 32) {                // write color table
607
0
        uchar *color_table = new uchar[4*image.colorCount()];
608
0
        uchar *rgb = color_table;
609
0
        const QList<QRgb> c = image.colorTable();
610
0
        for (int i = 0; i < image.colorCount(); i++) {
611
0
            *rgb++ = qBlue (c[i]);
612
0
            *rgb++ = qGreen(c[i]);
613
0
            *rgb++ = qRed  (c[i]);
614
0
            *rgb++ = 0;
615
0
        }
616
0
        if (d->write((char *)color_table, 4*image.colorCount()) == -1) {
617
0
            delete [] color_table;
618
0
            return false;
619
0
        }
620
0
        delete [] color_table;
621
0
    }
622
623
0
    int y;
624
625
0
    if (nbits == 1 || nbits == 8) {                // direct output
626
0
        for (y=image.height()-1; y>=0; y--) {
627
0
            if (d->write((const char*)image.constScanLine(y), bpl) == -1)
628
0
                return false;
629
0
        }
630
0
        return true;
631
0
    }
632
633
0
    uchar *buf        = new uchar[bpl_bmp];
634
0
    uchar *b, *end;
635
0
    const uchar *p;
636
637
0
    memset(buf, 0, bpl_bmp);
638
0
    for (y=image.height()-1; y>=0; y--) {        // write the image bits
639
0
        if (nbits == 4) {                        // convert 8 -> 4 bits
640
0
            p = image.constScanLine(y);
641
0
            b = buf;
642
0
            end = b + image.width()/2;
643
0
            while (b < end) {
644
0
                *b++ = (*p << 4) | (*(p+1) & 0x0f);
645
0
                p += 2;
646
0
            }
647
0
            if (image.width() & 1)
648
0
                *b = *p << 4;
649
0
        } else {                                // 32 bits
650
0
            const QRgb *p   = (const QRgb *)image.constScanLine(y);
651
0
            const QRgb *end = p + image.width();
652
0
            b = buf;
653
0
            while (p < end) {
654
0
                *b++ = qBlue(*p);
655
0
                *b++ = qGreen(*p);
656
0
                *b++ = qRed(*p);
657
0
                p++;
658
0
            }
659
0
        }
660
0
        if (bpl_bmp != d->write((char*)buf, bpl_bmp)) {
661
0
            delete[] buf;
662
0
            return false;
663
0
        }
664
0
    }
665
0
    delete[] buf;
666
0
    return true;
667
0
}
668
669
QBmpHandler::QBmpHandler(InternalFormat fmt) :
670
2.98k
    m_format(fmt), state(Ready)
671
2.98k
{
672
2.98k
}
673
674
QByteArray QBmpHandler::formatName() const
675
1.88k
{
676
1.88k
    return m_format == BmpFormat ? "bmp" : "dib";
677
1.88k
}
678
679
bool QBmpHandler::readHeader()
680
2.98k
{
681
2.98k
    state = Error;
682
683
2.98k
    QIODevice *d = device();
684
2.98k
    QDataStream s(d);
685
2.98k
    startpos = d->pos();
686
687
    // Intel byte order
688
2.98k
    s.setByteOrder(QDataStream::LittleEndian);
689
690
    // read BMP file header
691
2.98k
    if (m_format == BmpFormat && !read_dib_fileheader(s, fileHeader))
692
69
        return false;
693
694
    // read BMP info header
695
2.91k
    if (!read_dib_infoheader(s, infoHeader))
696
693
        return false;
697
698
2.21k
    state = ReadHeader;
699
2.21k
    return true;
700
2.91k
}
701
702
bool QBmpHandler::canRead() const
703
1.88k
{
704
1.88k
    if (m_format == BmpFormat && state == Ready && !canRead(device()))
705
0
        return false;
706
707
1.88k
    if (state != Error) {
708
1.88k
        setFormat(formatName());
709
1.88k
        return true;
710
1.88k
    }
711
712
0
    return false;
713
1.88k
}
714
715
bool QBmpHandler::canRead(QIODevice *device)
716
74.8k
{
717
74.8k
    if (!device) {
718
0
        qWarning("QBmpHandler::canRead() called with 0 pointer");
719
0
        return false;
720
0
    }
721
722
74.8k
    char head[2];
723
74.8k
    if (device->peek(head, sizeof(head)) != sizeof(head))
724
20.4k
        return false;
725
726
54.4k
    return (qstrncmp(head, "BM", 2) == 0);
727
74.8k
}
728
729
bool QBmpHandler::read(QImage *image)
730
2.98k
{
731
2.98k
    if (state == Error)
732
0
        return false;
733
734
2.98k
    if (!image) {
735
0
        qWarning("QBmpHandler::read: cannot read into null pointer");
736
0
        return false;
737
0
    }
738
739
2.98k
    if (state == Ready && !readHeader()) {
740
762
        state = Error;
741
762
        return false;
742
762
    }
743
744
2.21k
    QIODevice *d = device();
745
2.21k
    QDataStream s(d);
746
747
    // Intel byte order
748
2.21k
    s.setByteOrder(QDataStream::LittleEndian);
749
750
    // read image
751
2.21k
    qint64 datapos = startpos;
752
2.21k
    if (m_format == BmpFormat) {
753
2.21k
        datapos += fileHeader.bfOffBits;
754
2.21k
    } else {
755
        // QTBUG-100351: We have no file header when reading dib format so we have to depend on the size of the
756
        // buffer and the biSizeImage value to find where the pixel data starts since there's sometimes optional
757
        // color mask values after biSize, like for example when pasting from the windows snipping tool.
758
0
        if (infoHeader.biSizeImage > 0 && infoHeader.biSizeImage < d->size()) {
759
0
            datapos = d->size() - infoHeader.biSizeImage;
760
0
        } else {
761
            // And sometimes biSizeImage is not filled in like when pasting from Microsoft Edge, so then we just
762
            // have to assume the optional color mask values are there.
763
0
            datapos += infoHeader.biSize;
764
765
0
            if (infoHeader.biBitCount == 16 || infoHeader.biBitCount == 32) {
766
0
                if (infoHeader.biCompression == BMP_BITFIELDS) {
767
0
                    datapos += 12;
768
0
                } else if (infoHeader.biCompression == BMP_ALPHABITFIELDS) {
769
0
                    datapos += 16;
770
0
                }
771
0
            }
772
0
        }
773
0
    }
774
2.21k
    const bool readSuccess = m_format == BmpFormat ?
775
2.21k
        read_dib_body(s, infoHeader, datapos, startpos + BMP_FILEHDR_SIZE, *image) :
776
2.21k
        read_dib_body(s, infoHeader, datapos, startpos, *image);
777
2.21k
    if (!readSuccess)
778
594
        return false;
779
780
1.62k
    state = Ready;
781
1.62k
    return true;
782
2.21k
}
783
784
bool QBmpHandler::write(const QImage &img)
785
0
{
786
0
    QImage image;
787
0
    switch (img.format()) {
788
0
    case QImage::Format_Mono:
789
0
    case QImage::Format_Indexed8:
790
0
    case QImage::Format_RGB32:
791
0
    case QImage::Format_ARGB32:
792
0
        image = img;
793
0
        break;
794
0
    case QImage::Format_MonoLSB:
795
0
        image = img.convertToFormat(QImage::Format_Mono);
796
0
        break;
797
0
    case QImage::Format_Alpha8:
798
0
    case QImage::Format_Grayscale8:
799
0
        image = img.convertToFormat(QImage::Format_Indexed8);
800
0
        break;
801
0
    default:
802
0
        if (img.hasAlphaChannel())
803
0
            image = img.convertToFormat(QImage::Format_ARGB32);
804
0
        else
805
0
            image = img.convertToFormat(QImage::Format_RGB32);
806
0
        break;
807
0
    }
808
809
0
    int nbits;
810
0
    qsizetype bpl_bmp;
811
    // Calculate a minimum bytes-per-line instead of using whatever value this QImage is using internally.
812
0
    qsizetype bpl = ((image.width() * image.depth() + 31) >> 5) << 2;
813
814
0
    if (image.depth() == 8 && image.colorCount() <= 16) {
815
0
        bpl_bmp = (((bpl+1)/2+3)/4)*4;
816
0
        nbits = 4;
817
0
   } else if (image.depth() == 32) {
818
0
        bpl_bmp = ((image.width()*24+31)/32)*4;
819
0
        nbits = 24;
820
0
    } else {
821
0
        bpl_bmp = bpl;
822
0
        nbits = image.depth();
823
0
    }
824
0
    if (qsizetype(int(bpl_bmp)) != bpl_bmp)
825
0
        return false;
826
827
0
    if (m_format == DibFormat) {
828
0
        QDataStream dibStream(device());
829
0
        dibStream.setByteOrder(QDataStream::LittleEndian); // Intel byte order
830
0
        return qt_write_dib(dibStream, img, bpl, bpl_bmp, nbits);
831
0
    }
832
833
0
    QIODevice *d = device();
834
0
    QDataStream s(d);
835
0
    BMP_FILEHDR bf;
836
837
    // Intel byte order
838
0
    s.setByteOrder(QDataStream::LittleEndian);
839
840
    // build file header
841
0
    memcpy(bf.bfType, "BM", 2);
842
843
    // write file header
844
0
    bf.bfReserved1 = 0;
845
0
    bf.bfReserved2 = 0;
846
0
    bf.bfOffBits = BMP_FILEHDR_SIZE + BMP_WIN + image.colorCount() * 4;
847
0
    bf.bfSize = bf.bfOffBits + bpl_bmp*image.height();
848
0
    if (qsizetype(bf.bfSize) != bf.bfOffBits + bpl_bmp*image.height())
849
0
        return false;
850
0
    s << bf;
851
852
    // write image
853
0
    return qt_write_dib(s, image, bpl, bpl_bmp, nbits);
854
0
}
855
856
bool QBmpHandler::supportsOption(ImageOption option) const
857
12.9k
{
858
12.9k
    return option == Size
859
12.9k
            || option == ImageFormat;
860
12.9k
}
861
862
QVariant QBmpHandler::option(ImageOption option) const
863
0
{
864
0
    if (option == Size) {
865
0
        if (state == Error)
866
0
            return QVariant();
867
0
        if (state == Ready && !const_cast<QBmpHandler*>(this)->readHeader())
868
0
            return QVariant();
869
0
        return QSize(infoHeader.biWidth, infoHeader.biHeight);
870
0
    } else if (option == ImageFormat) {
871
0
        if (state == Error)
872
0
            return QVariant();
873
0
        if (state == Ready && !const_cast<QBmpHandler*>(this)->readHeader())
874
0
            return QVariant();
875
0
        QImage::Format format;
876
0
        switch (infoHeader.biBitCount) {
877
0
            case 32:
878
0
            case 24:
879
0
            case 16:
880
0
                if ((infoHeader.biCompression == BMP_BITFIELDS || infoHeader.biCompression == BMP_ALPHABITFIELDS) && infoHeader.biSize >= BMP_WIN4 && infoHeader.biAlphaMask)
881
0
                    format = QImage::Format_ARGB32;
882
0
                else
883
0
                    format = QImage::Format_RGB32;
884
0
                break;
885
0
            case 8:
886
0
            case 4:
887
0
                format = QImage::Format_Indexed8;
888
0
                break;
889
0
            default:
890
0
                format = QImage::Format_Mono;
891
0
            }
892
0
        return format;
893
0
    }
894
0
    return QVariant();
895
0
}
896
897
void QBmpHandler::setOption(ImageOption option, const QVariant &value)
898
0
{
899
0
    Q_UNUSED(option);
900
    Q_UNUSED(value);
901
0
}
902
903
QT_END_NAMESPACE
904
905
#endif // QT_NO_IMAGEFORMAT_BMP