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