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