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