Debian Codegraph @

src/plugins/imageformats/tiff/qtiffhandler.cpp

raw symbols SCIP
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 plugins 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 "qtiffhandler_p.h"
41 #include <qvariant.h>
42 #include <qcolorspace.h>
43 #include <qdebug.h>
44 #include <qimage.h>
45 #include <qglobal.h>
46 #include <qbuffer.h>
47 #include <qfiledevice.h>
48
49 extern "C" {
50 #include "tiffio.h"
51 }
52
53 #include <memory>
54
55 QT_BEGIN_NAMESPACE
56
57 tsize_t qtiffReadProc(thandle_t fd, tdata_t buf, tsize_t size)
58 {
59 QIODevice *device = static_cast<QIODevice *>(fd);
60 return device->isReadable() ? device->read(static_cast<char *>(buf), size) : -1;
61 }
62
63 tsize_t qtiffWriteProc(thandle_t fd, tdata_t buf, tsize_t size)
64 {
65 return static_cast<QIODevice *>(fd)->write(static_cast<char *>(buf), size);
66 }
67
68 toff_t qtiffSeekProc(thandle_t fd, toff_t off, int whence)
69 {
70 QIODevice *device = static_cast<QIODevice *>(fd);
71 switch (whence) {
72 case SEEK_SET:
73 device->seek(off);
74 break;
75 case SEEK_CUR:
76 device->seek(device->pos() + off);
77 break;
78 case SEEK_END:
79 device->seek(device->size() + off);
80 break;
81 }
82
83 return device->pos();
84 }
85
86 int qtiffCloseProc(thandle_t /*fd*/)
87 {
88 return 0;
89 }
90
91 toff_t qtiffSizeProc(thandle_t fd)
92 {
93 return static_cast<QIODevice *>(fd)->size();
94 }
95
96 int qtiffMapProc(thandle_t fd, void **base, toff_t *size)
97 {
98 QIODevice *device = static_cast<QIODevice *>(fd);
99
100 QFileDevice *file = qobject_cast<QFileDevice *>(device);
101 if (file) {
102 *base = file->map(0, file->size());
103 if (*base != nullptr) {
104 *size = file->size();
105 return 1;
106 }
107 } else {
108 QBuffer *buf = qobject_cast<QBuffer *>(device);
109 if (buf) {
110 *base = const_cast<char *>(buf->data().constData());
111 *size = buf->size();
112 return 1;
113 }
114 }
115 return 0;
116 }
117
118 void qtiffUnmapProc(thandle_t fd, void *base, toff_t /*size*/)
119 {
120 QFileDevice *file = qobject_cast<QFileDevice *>(static_cast<QIODevice *>(fd));
121 if (file && base)
122 file->unmap(static_cast<uchar *>(base));
123 }
124
125
126 class QTiffHandlerPrivate
127 {
128 public:
129 QTiffHandlerPrivate();
130 ~QTiffHandlerPrivate();
131
132 static bool canRead(QIODevice *device);
133 bool openForRead(QIODevice *device);
134 bool readHeaders(QIODevice *device);
135 void close();
136
137 TIFF *tiff;
138 int compression;
139 QImageIOHandler::Transformations transformation;
140 QImage::Format format;
141 QSize size;
142 uint16_t photometric;
143 bool grayscale;
144 bool headersRead;
145 int currentDirectory;
146 int directoryCount;
147 };
148
149 static QImageIOHandler::Transformations exif2Qt(int exifOrientation)
150 {
151 switch (exifOrientation) {
152 case 1: // normal
153 return QImageIOHandler::TransformationNone;
154 case 2: // mirror horizontal
155 return QImageIOHandler::TransformationMirror;
156 case 3: // rotate 180
157 return QImageIOHandler::TransformationRotate180;
158 case 4: // mirror vertical
159 return QImageIOHandler::TransformationFlip;
160 case 5: // mirror horizontal and rotate 270 CW
161 return QImageIOHandler::TransformationFlipAndRotate90;
162 case 6: // rotate 90 CW
163 return QImageIOHandler::TransformationRotate90;
164 case 7: // mirror horizontal and rotate 90 CW
165 return QImageIOHandler::TransformationMirrorAndRotate90;
166 case 8: // rotate 270 CW
167 return QImageIOHandler::TransformationRotate270;
168 }
169 qWarning("Invalid EXIF orientation");
170 return QImageIOHandler::TransformationNone;
171 }
172
173 static int qt2Exif(QImageIOHandler::Transformations transformation)
174 {
175 switch (transformation) {
176 case QImageIOHandler::TransformationNone:
177 return 1;
178 case QImageIOHandler::TransformationMirror:
179 return 2;
180 case QImageIOHandler::TransformationRotate180:
181 return 3;
182 case QImageIOHandler::TransformationFlip:
183 return 4;
184 case QImageIOHandler::TransformationFlipAndRotate90:
185 return 5;
186 case QImageIOHandler::TransformationRotate90:
187 return 6;
188 case QImageIOHandler::TransformationMirrorAndRotate90:
189 return 7;
190 case QImageIOHandler::TransformationRotate270:
191 return 8;
192 }
193 qWarning("Invalid Qt image transformation");
194 return 1;
195 }
196
197 QTiffHandlerPrivate::QTiffHandlerPrivate()
198 : tiff(0)
199 , compression(QTiffHandler::NoCompression)
200 , transformation(QImageIOHandler::TransformationNone)
201 , format(QImage::Format_Invalid)
202 , photometric(false)
203 , grayscale(false)
204 , headersRead(false)
205 , currentDirectory(0)
206 , directoryCount(0)
207 {
208 }
209
210 QTiffHandlerPrivate::~QTiffHandlerPrivate()
211 {
212 close();
213 }
214
215 void QTiffHandlerPrivate::close()
216 {
217 if (tiff)
218 TIFFClose(tiff);
219 tiff = 0;
220 }
221
222 bool QTiffHandlerPrivate::canRead(QIODevice *device)
223 {
224 if (!device) {
225 qWarning("QTiffHandler::canRead() called with no device");
226 return false;
227 }
228
229 // current implementation uses TIFFClientOpen which needs to be
230 // able to seek, so sequential devices are not supported
231 char h[4];
232 if (device->peek(h, 4) != 4)
233 return false;
234 if ((h[0] == 0x49 && h[1] == 0x49) && (h[2] == 0x2a || h[2] == 0x2b) && h[3] == 0)
235 return true; // Little endian, classic or bigtiff
236 if ((h[0] == 0x4d && h[1] == 0x4d) && h[2] == 0 && (h[3] == 0x2a || h[3] == 0x2b))
237 return true; // Big endian, classic or bigtiff
238 return false;
239 }
240
241 bool QTiffHandlerPrivate::openForRead(QIODevice *device)
242 {
243 if (tiff)
244 return true;
245
246 if (!canRead(device))
247 return false;
248
249 tiff = TIFFClientOpen("foo",
250 "r",
251 device,
252 qtiffReadProc,
253 qtiffWriteProc,
254 qtiffSeekProc,
255 qtiffCloseProc,
256 qtiffSizeProc,
257 qtiffMapProc,
258 qtiffUnmapProc);
259
260 if (!tiff) {
261 return false;
262 }
263 return true;
264 }
265
266 bool QTiffHandlerPrivate::readHeaders(QIODevice *device)
267 {
268 if (headersRead)
269 return true;
270
271 if (!openForRead(device))
272 return false;
273
274 TIFFSetDirectory(tiff, currentDirectory);
275
276 uint32_t width;
277 uint32_t height;
278 if (!TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width)
279 || !TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height)
280 || !TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric)) {
281 close();
282 return false;
283 }
284 size = QSize(width, height);
285
286 uint16_t orientationTag;
287 if (TIFFGetField(tiff, TIFFTAG_ORIENTATION, &orientationTag))
288 transformation = exif2Qt(orientationTag);
289
290 // BitsPerSample defaults to 1 according to the TIFF spec.
291 uint16_t bitPerSample;
292 if (!TIFFGetField(tiff, TIFFTAG_BITSPERSAMPLE, &bitPerSample))
293 bitPerSample = 1;
294 uint16_t samplesPerPixel; // they may be e.g. grayscale with 2 samples per pixel
295 if (!TIFFGetField(tiff, TIFFTAG_SAMPLESPERPIXEL, &samplesPerPixel))
296 samplesPerPixel = 1;
297
298 grayscale = photometric == PHOTOMETRIC_MINISBLACK || photometric == PHOTOMETRIC_MINISWHITE;
299
300 if (grayscale && bitPerSample == 1 && samplesPerPixel == 1)
301 format = QImage::Format_Mono;
302 else if (photometric == PHOTOMETRIC_MINISBLACK && bitPerSample == 8 && samplesPerPixel == 1)
303 format = QImage::Format_Grayscale8;
304 else if (photometric == PHOTOMETRIC_MINISBLACK && bitPerSample == 16 && samplesPerPixel == 1)
305 format = QImage::Format_Grayscale16;
306 else if ((grayscale || photometric == PHOTOMETRIC_PALETTE) && bitPerSample == 8 && samplesPerPixel == 1)
307 format = QImage::Format_Indexed8;
308 else if (samplesPerPixel < 4)
309 if (bitPerSample == 16 && photometric == PHOTOMETRIC_RGB)
310 format = QImage::Format_RGBX64;
311 else
312 format = QImage::Format_RGB32;
313 else {
314 uint16_t count;
315 uint16_t *extrasamples;
316 // If there is any definition of the alpha-channel, libtiff will return premultiplied
317 // data to us. If there is none, libtiff will not touch it and we assume it to be
318 // non-premultiplied, matching behavior of tested image editors, and how older Qt
319 // versions used to save it.
320 bool premultiplied = true;
321 bool gotField = TIFFGetField(tiff, TIFFTAG_EXTRASAMPLES, &count, &extrasamples);
322 if (!gotField || !count || extrasamples[0] == EXTRASAMPLE_UNSPECIFIED)
323 premultiplied = false;
324
325 if (bitPerSample == 16 && photometric == PHOTOMETRIC_RGB) {
326 // We read 64-bit raw, so unassoc remains unpremultiplied.
327 if (gotField && count && extrasamples[0] == EXTRASAMPLE_UNASSALPHA)
328 premultiplied = false;
329 if (premultiplied)
330 format = QImage::Format_RGBA64_Premultiplied;
331 else
332 format = QImage::Format_RGBA64;
333 } else {
334 if (premultiplied)
335 format = QImage::Format_ARGB32_Premultiplied;
336 else
337 format = QImage::Format_ARGB32;
338 }
339 }
340
341 headersRead = true;
342 return true;
343 }
344
345 QTiffHandler::QTiffHandler()
346 : QImageIOHandler()
347 , d(new QTiffHandlerPrivate)
348 {
349 }
350
351 bool QTiffHandler::canRead() const
352 {
353 if (d->tiff)
354 return true;
355 if (QTiffHandlerPrivate::canRead(device())) {
356 setFormat("tiff");
357 return true;
358 }
359 return false;
360 }
361
362 bool QTiffHandler::canRead(QIODevice *device)
363 {
364 return QTiffHandlerPrivate::canRead(device);
365 }
366
367 bool QTiffHandler::read(QImage *image)
368 {
369 // Open file and read headers if it hasn't already been done.
370 if (!d->readHeaders(device()))
371 return false;
372
373 QImage::Format format = d->format;
374
375 if (image->size() == d->size && image->format() != format)
376 image->reinterpretAsFormat(format);
377
378 if (image->size() != d->size || image->format() != format)
379 *image = QImage(d->size, format);
380
381 if (image->isNull()) {
382 d->close();
383 return false;
384 }
385
386 TIFF *const tiff = d->tiff;
387 if (TIFFIsTiled(tiff) && TIFFTileSize64(tiff) > uint64_t(image->sizeInBytes())) // Corrupt image
388 return false;
389 const quint32 width = d->size.width();
390 const quint32 height = d->size.height();
391
392 // Setup color tables
393 if (format == QImage::Format_Mono || format == QImage::Format_Indexed8) {
394 if (format == QImage::Format_Mono) {
395 QVector<QRgb> colortable(2);
396 if (d->photometric == PHOTOMETRIC_MINISBLACK) {
397 colortable[0] = 0xff000000;
398 colortable[1] = 0xffffffff;
399 } else {
400 colortable[0] = 0xffffffff;
401 colortable[1] = 0xff000000;
402 }
403 image->setColorTable(colortable);
404 } else if (format == QImage::Format_Indexed8) {
405 const uint16_t tableSize = 256;
406 QVector<QRgb> qtColorTable(tableSize);
407 if (d->grayscale) {
408 for (int i = 0; i<tableSize; ++i) {
409 const int c = (d->photometric == PHOTOMETRIC_MINISBLACK) ? i : (255 - i);
410 qtColorTable[i] = qRgb(c, c, c);
411 }
412 } else {
413 // create the color table
414 uint16_t *redTable = 0;
415 uint16_t *greenTable = 0;
416 uint16_t *blueTable = 0;
417 if (!TIFFGetField(tiff, TIFFTAG_COLORMAP, &redTable, &greenTable, &blueTable)) {
418 d->close();
419 return false;
420 }
421 if (!redTable || !greenTable || !blueTable) {
422 d->close();
423 return false;
424 }
425
426 for (int i = 0; i<tableSize ;++i) {
427 // emulate libtiff behavior for 16->8 bit color map conversion: just ignore the lower 8 bits
428 const int red = redTable[i] >> 8;
429 const int green = greenTable[i] >> 8;
430 const int blue = blueTable[i] >> 8;
431 qtColorTable[i] = qRgb(red, green, blue);
432 }
433 }
434 image->setColorTable(qtColorTable);
435 // free redTable, greenTable and greenTable done by libtiff
436 }
437 }
438 bool format8bit = (format == QImage::Format_Mono || format == QImage::Format_Indexed8 || format == QImage::Format_Grayscale8);
439 bool format16bit = (format == QImage::Format_Grayscale16);
440 bool format64bit = (format == QImage::Format_RGBX64 || format == QImage::Format_RGBA64 || format == QImage::Format_RGBA64_Premultiplied);
441
442 // Formats we read directly, instead of over RGBA32:
443 if (format8bit || format16bit || format64bit) {
444 int bytesPerPixel = image->depth() / 8;
445 if (format == QImage::Format_RGBX64)
446 bytesPerPixel = 6;
447 if (TIFFIsTiled(tiff)) {
448 quint32 tileWidth, tileLength;
449 TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tileWidth);
450 TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tileLength);
451 if (!tileWidth || !tileLength || tileWidth % 16 || tileLength % 16) {
452 d->close();
453 return false;
454 }
455 quint32 byteWidth = (format == QImage::Format_Mono) ? (width + 7)/8 : (width * bytesPerPixel);
456 quint32 byteTileWidth = (format == QImage::Format_Mono) ? tileWidth/8 : (tileWidth * bytesPerPixel);
457 tmsize_t byteTileSize = TIFFTileSize(tiff);
458 uchar *buf = (uchar *)_TIFFmalloc(byteTileSize);
459 if (!buf || byteTileSize / tileLength < byteTileWidth) {
460 _TIFFfree(buf);
461 d->close();
462 return false;
463 }
464 for (quint32 y = 0; y < height; y += tileLength) {
465 for (quint32 x = 0; x < width; x += tileWidth) {
466 if (TIFFReadTile(tiff, buf, x, y, 0, 0) < 0) {
467 _TIFFfree(buf);
468 d->close();
469 return false;
470 }
471 quint32 linesToCopy = qMin(tileLength, height - y);
472 quint32 byteOffset = (format == QImage::Format_Mono) ? x/8 : (x * bytesPerPixel);
473 quint32 widthToCopy = qMin(byteTileWidth, byteWidth - byteOffset);
474 for (quint32 i = 0; i < linesToCopy; i++) {
475 ::memcpy(image->scanLine(y + i) + byteOffset, buf + (i * byteTileWidth), widthToCopy);
476 }
477 }
478 }
479 _TIFFfree(buf);
480 } else {
481 if (image->bytesPerLine() < TIFFScanlineSize(tiff)) {
482 d->close();
483 return false;
484 }
485 for (uint32_t y=0; y<height; ++y) {
486 if (TIFFReadScanline(tiff, image->scanLine(y), y, 0) < 0) {
487 d->close();
488 return false;
489 }
490 }
491 }
492 if (format == QImage::Format_RGBX64)
493 rgb48fixup(image);
494 } else {
495 const int stopOnError = 1;
496 if (TIFFReadRGBAImageOriented(tiff, width, height, reinterpret_cast<uint32_t *>(image->bits()), qt2Exif(d->transformation), stopOnError)) {
497 for (uint32_t y=0; y<height; ++y)
498 convert32BitOrder(image->scanLine(y), width);
499 } else {
500 d->close();
501 return false;
502 }
503 }
504
505
506 float resX = 0;
507 float resY = 0;
508 uint16_t resUnit;
509 if (!TIFFGetField(tiff, TIFFTAG_RESOLUTIONUNIT, &resUnit))
510 resUnit = RESUNIT_INCH;
511
512 if (TIFFGetField(tiff, TIFFTAG_XRESOLUTION, &resX)
513 && TIFFGetField(tiff, TIFFTAG_YRESOLUTION, &resY)) {
514
515 switch(resUnit) {
516 case RESUNIT_CENTIMETER:
517 image->setDotsPerMeterX(qRound(resX * 100));
518 image->setDotsPerMeterY(qRound(resY * 100));
519 break;
520 case RESUNIT_INCH:
521 image->setDotsPerMeterX(qRound(resX * (100 / 2.54)));
522 image->setDotsPerMeterY(qRound(resY * (100 / 2.54)));
523 break;
524 default:
525 // do nothing as defaults have already
526 // been set within the QImage class
527 break;
528 }
529 }
530
531 uint32_t count;
532 void *profile;
533 if (TIFFGetField(tiff, TIFFTAG_ICCPROFILE, &count, &profile)) {
534 QByteArray iccProfile(reinterpret_cast<const char *>(profile), count);
535 image->setColorSpace(QColorSpace::fromIccProfile(iccProfile));
536 }
537 // We do not handle colorimetric metadat not on ICC profile form, it seems to be a lot
538 // less common, and would need additional API in QColorSpace.
539
540 return true;
541 }
542
543 static bool checkGrayscale(const QVector<QRgb> &colorTable)
544 {
545 if (colorTable.size() != 256)
546 return false;
547
548 const bool increasing = (colorTable.at(0) == 0xff000000);
549 for (int i = 0; i < 256; ++i) {
550 if ((increasing && colorTable.at(i) != qRgb(i, i, i))
551 || (!increasing && colorTable.at(i) != qRgb(255 - i, 255 - i, 255 - i)))
552 return false;
553 }
554 return true;
555 }
556
557 static QVector<QRgb> effectiveColorTable(const QImage &image)
558 {
559 QVector<QRgb> colors;
560 switch (image.format()) {
561 case QImage::Format_Indexed8:
562 colors = image.colorTable();
563 break;
564 case QImage::Format_Alpha8:
565 colors.resize(256);
566 for (int i = 0; i < 256; ++i)
567 colors[i] = qRgba(0, 0, 0, i);
568 break;
569 case QImage::Format_Grayscale8:
570 case QImage::Format_Grayscale16:
571 colors.resize(256);
572 for (int i = 0; i < 256; ++i)
573 colors[i] = qRgb(i, i, i);
574 break;
575 default:
576 Q_UNREACHABLE();
577 }
578 return colors;
579 }
580
581 static quint32 defaultStripSize(TIFF *tiff)
582 {
583 // Aim for 4MB strips
584 qint64 scanSize = qMax(qint64(1), qint64(TIFFScanlineSize(tiff)));
585 qint64 numRows = (4 * 1024 * 1024) / scanSize;
586 quint32 reqSize = static_cast<quint32>(qBound(qint64(1), numRows, qint64(UINT_MAX)));
587 return TIFFDefaultStripSize(tiff, reqSize);
588 }
589
590 bool QTiffHandler::write(const QImage &image)
591 {
592 if (!device()->isWritable())
593 return false;
594
595 TIFF *const tiff = TIFFClientOpen("foo",
596 "wB",
597 device(),
598 qtiffReadProc,
599 qtiffWriteProc,
600 qtiffSeekProc,
601 qtiffCloseProc,
602 qtiffSizeProc,
603 qtiffMapProc,
604 qtiffUnmapProc);
605 if (!tiff)
606 return false;
607
608 const int width = image.width();
609 const int height = image.height();
610 const int compression = d->compression;
611
612 if (!TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, width)
613 || !TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, height)
614 || !TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) {
615 TIFFClose(tiff);
616 return false;
617 }
618
619 // set the resolution
620 bool resolutionSet = false;
621 const int dotPerMeterX = image.dotsPerMeterX();
622 const int dotPerMeterY = image.dotsPerMeterY();
623 if ((dotPerMeterX % 100) == 0
624 && (dotPerMeterY % 100) == 0) {
625 resolutionSet = TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER)
626 && TIFFSetField(tiff, TIFFTAG_XRESOLUTION, dotPerMeterX/100.0)
627 && TIFFSetField(tiff, TIFFTAG_YRESOLUTION, dotPerMeterY/100.0);
628 } else {
629 resolutionSet = TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH)
630 && TIFFSetField(tiff, TIFFTAG_XRESOLUTION, static_cast<float>(image.logicalDpiX()))
631 && TIFFSetField(tiff, TIFFTAG_YRESOLUTION, static_cast<float>(image.logicalDpiY()));
632 }
633 if (!resolutionSet) {
634 TIFFClose(tiff);
635 return false;
636 }
637 // set the orienataion
638 bool orientationSet = false;
639 orientationSet = TIFFSetField(tiff, TIFFTAG_ORIENTATION, qt2Exif(d->transformation));
640 if (!orientationSet) {
641 TIFFClose(tiff);
642 return false;
643 }
644 // set color space
645 if (image.colorSpace().isValid()) {
646 QByteArray iccProfile = image.colorSpace().iccProfile();
647 if (!TIFFSetField(tiff, TIFFTAG_ICCPROFILE, iccProfile.size(), reinterpret_cast<const void *>(iccProfile.constData()))) {
648 TIFFClose(tiff);
649 return false;
650 }
651 }
652 // configure image depth
653 const QImage::Format format = image.format();
654 if (format == QImage::Format_Mono || format == QImage::Format_MonoLSB) {
655 uint16_t photometric = PHOTOMETRIC_MINISBLACK;
656 if (image.colorTable().at(0) == 0xffffffff)
657 photometric = PHOTOMETRIC_MINISWHITE;
658 if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric)
659 || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW)
660 || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 1)
661 || !TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, defaultStripSize(tiff))) {
662 TIFFClose(tiff);
663 return false;
664 }
665
666 // try to do the conversion in chunks no greater than 16 MB
667 const int chunks = int(image.sizeInBytes() / (1024 * 1024 * 16)) + 1;
668 const int chunkHeight = qMax(height / chunks, 1);
669
670 int y = 0;
671 while (y < height) {
672 QImage chunk = image.copy(0, y, width, qMin(chunkHeight, height - y)).convertToFormat(QImage::Format_Mono);
673
674 int chunkStart = y;
675 int chunkEnd = y + chunk.height();
676 while (y < chunkEnd) {
677 if (TIFFWriteScanline(tiff, reinterpret_cast<uint32_t *>(chunk.scanLine(y - chunkStart)), y) != 1) {
678 TIFFClose(tiff);
679 return false;
680 }
681 ++y;
682 }
683 }
684 TIFFClose(tiff);
685 } else if (format == QImage::Format_Indexed8
686 || format == QImage::Format_Grayscale8
687 || format == QImage::Format_Grayscale16
688 || format == QImage::Format_Alpha8) {
689 QVector<QRgb> colorTable = effectiveColorTable(image);
690 bool isGrayscale = checkGrayscale(colorTable);
691 if (isGrayscale) {
692 uint16_t photometric = PHOTOMETRIC_MINISBLACK;
693 if (colorTable.at(0) == 0xffffffff)
694 photometric = PHOTOMETRIC_MINISWHITE;
695 if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric)
696 || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW)
697 || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, image.depth())
698 || !TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, defaultStripSize(tiff))) {
699 TIFFClose(tiff);
700 return false;
701 }
702 } else {
703 if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE)
704 || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW)
705 || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)
706 || !TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, defaultStripSize(tiff))) {
707 TIFFClose(tiff);
708 return false;
709 }
710 //// write the color table
711 // allocate the color tables
712 const int tableSize = colorTable.size();
713 Q_ASSERT(tableSize <= 256);
714 QVarLengthArray<uint16_t> redTable(tableSize);
715 QVarLengthArray<uint16_t> greenTable(tableSize);
716 QVarLengthArray<uint16_t> blueTable(tableSize);
717
718 // set the color table
719 for (int i = 0; i<tableSize; ++i) {
720 const QRgb color = colorTable.at(i);
721 redTable[i] = qRed(color) * 257;
722 greenTable[i] = qGreen(color) * 257;
723 blueTable[i] = qBlue(color) * 257;
724 }
725
726 const bool setColorTableSuccess = TIFFSetField(tiff, TIFFTAG_COLORMAP, redTable.data(), greenTable.data(), blueTable.data());
727
728 if (!setColorTableSuccess) {
729 TIFFClose(tiff);
730 return false;
731 }
732 }
733
734 //// write the data
735 for (int y = 0; y < height; ++y) {
736 if (TIFFWriteScanline(tiff, const_cast<uchar *>(image.scanLine(y)), y) != 1) {
737 TIFFClose(tiff);
738 return false;
739 }
740 }
741 TIFFClose(tiff);
742 } else if (format == QImage::Format_RGBX64) {
743 if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB)
744 || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW)
745 || !TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 3)
746 || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 16)
747 || !TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tiff, 0))) {
748 TIFFClose(tiff);
749 return false;
750 }
751 std::unique_ptr<quint16[]> rgb48line(new quint16[width * 3]);
752 for (int y = 0; y < height; ++y) {
753 const quint16 *srcLine = reinterpret_cast<const quint16 *>(image.constScanLine(y));
754 for (int x = 0; x < width; ++x) {
755 rgb48line[x * 3 + 0] = srcLine[x * 4 + 0];
756 rgb48line[x * 3 + 1] = srcLine[x * 4 + 1];
757 rgb48line[x * 3 + 2] = srcLine[x * 4 + 2];
758 }
759
760 if (TIFFWriteScanline(tiff, (void*)rgb48line.get(), y) != 1) {
761 TIFFClose(tiff);
762 return false;
763 }
764 }
765 TIFFClose(tiff);
766 } else if (format == QImage::Format_RGBA64
767 || format == QImage::Format_RGBA64_Premultiplied) {
768 const bool premultiplied = image.format() != QImage::Format_RGBA64;
769 const uint16_t extrasamples = premultiplied ? EXTRASAMPLE_ASSOCALPHA : EXTRASAMPLE_UNASSALPHA;
770 if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB)
771 || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW)
772 || !TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 4)
773 || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 16)
774 || !TIFFSetField(tiff, TIFFTAG_EXTRASAMPLES, 1, &extrasamples)
775 || !TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tiff, 0))) {
776 TIFFClose(tiff);
777 return false;
778 }
779 for (int y = 0; y < height; ++y) {
780 if (TIFFWriteScanline(tiff, (void*)image.scanLine(y), y) != 1) {
781 TIFFClose(tiff);
782 return false;
783 }
784 }
785 TIFFClose(tiff);
786 } else if (!image.hasAlphaChannel()) {
787 if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB)
788 || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW)
789 || !TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 3)
790 || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)
791 || !TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, defaultStripSize(tiff))) {
792 TIFFClose(tiff);
793 return false;
794 }
795 // try to do the RGB888 conversion in chunks no greater than 16 MB
796 const int chunks = int(image.sizeInBytes() / (1024 * 1024 * 16)) + 1;
797 const int chunkHeight = qMax(height / chunks, 1);
798
799 int y = 0;
800 while (y < height) {
801 const QImage chunk = image.copy(0, y, width, qMin(chunkHeight, height - y)).convertToFormat(QImage::Format_RGB888);
802
803 int chunkStart = y;
804 int chunkEnd = y + chunk.height();
805 while (y < chunkEnd) {
806 if (TIFFWriteScanline(tiff, (void*)chunk.scanLine(y - chunkStart), y) != 1) {
807 TIFFClose(tiff);
808 return false;
809 }
810 ++y;
811 }
812 }
813 TIFFClose(tiff);
814 } else {
815 const bool premultiplied = image.format() != QImage::Format_ARGB32
816 && image.format() != QImage::Format_RGBA8888;
817 const uint16_t extrasamples = premultiplied ? EXTRASAMPLE_ASSOCALPHA : EXTRASAMPLE_UNASSALPHA;
818 if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB)
819 || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW)
820 || !TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 4)
821 || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)
822 || !TIFFSetField(tiff, TIFFTAG_EXTRASAMPLES, 1, &extrasamples)
823 || !TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, defaultStripSize(tiff))) {
824 TIFFClose(tiff);
825 return false;
826 }
827 // try to do the RGBA8888 conversion in chunks no greater than 16 MB
828 const int chunks = int(image.sizeInBytes() / (1024 * 1024 * 16)) + 1;
829 const int chunkHeight = qMax(height / chunks, 1);
830
831 const QImage::Format format = premultiplied ? QImage::Format_RGBA8888_Premultiplied
832 : QImage::Format_RGBA8888;
833 int y = 0;
834 while (y < height) {
835 const QImage chunk = image.copy(0, y, width, qMin(chunkHeight, height - y)).convertToFormat(format);
836
837 int chunkStart = y;
838 int chunkEnd = y + chunk.height();
839 while (y < chunkEnd) {
840 if (TIFFWriteScanline(tiff, (void*)chunk.scanLine(y - chunkStart), y) != 1) {
841 TIFFClose(tiff);
842 return false;
843 }
844 ++y;
845 }
846 }
847 TIFFClose(tiff);
848 }
849
850 return true;
851 }
852
853 QVariant QTiffHandler::option(ImageOption option) const
854 {
855 if (option == Size && canRead()) {
856 if (d->readHeaders(device()))
857 return d->size;
858 } else if (option == CompressionRatio) {
859 return d->compression;
860 } else if (option == ImageFormat) {
861 if (d->readHeaders(device()))
862 return d->format;
863 } else if (option == ImageTransformation) {
864 if (d->readHeaders(device()))
865 return int(d->transformation);
866 }
867 return QVariant();
868 }
869
870 void QTiffHandler::setOption(ImageOption option, const QVariant &value)
871 {
872 if (option == CompressionRatio && value.type() == QVariant::Int)
873 d->compression = qBound(0, value.toInt(), 1);
874 if (option == ImageTransformation) {
875 int transformation = value.toInt();
876 if (transformation > 0 && transformation < 8)
877 d->transformation = QImageIOHandler::Transformations(transformation);
878 }
879 }
880
881 bool QTiffHandler::supportsOption(ImageOption option) const
882 {
883 return option == CompressionRatio
884 || option == Size
885 || option == ImageFormat
886 || option == ImageTransformation
887 || option == TransformedByDefault;
888 }
889
890 bool QTiffHandler::jumpToNextImage()
891 {
892 if (!ensureHaveDirectoryCount())
893 return false;
894 if (d->currentDirectory >= d->directoryCount - 1)
895 return false;
896
897 d->headersRead = false;
898 ++d->currentDirectory;
899 return true;
900 }
901
902 bool QTiffHandler::jumpToImage(int imageNumber)
903 {
904 if (!ensureHaveDirectoryCount())
905 return false;
906 if (imageNumber < 0 || imageNumber >= d->directoryCount)
907 return false;
908
909 if (d->currentDirectory != imageNumber) {
910 d->headersRead = false;
911 d->currentDirectory = imageNumber;
912 }
913 return true;
914 }
915
916 int QTiffHandler::imageCount() const
917 {
918 if (!ensureHaveDirectoryCount())
919 return 1;
920
921 return d->directoryCount;
922 }
923
924 int QTiffHandler::currentImageNumber() const
925 {
926 return d->currentDirectory;
927 }
928
929 void QTiffHandler::convert32BitOrder(void *buffer, int width)
930 {
931 uint32_t *target = reinterpret_cast<uint32_t *>(buffer);
932 for (int32_t x=0; x<width; ++x) {
933 uint32_t p = target[x];
934 // convert between ARGB and ABGR
935 target[x] = (p & 0xff000000)
936 | ((p & 0x00ff0000) >> 16)
937 | (p & 0x0000ff00)
938 | ((p & 0x000000ff) << 16);
939 }
940 }
941
942 void QTiffHandler::rgb48fixup(QImage *image)
943 {
944 Q_ASSERT(image->depth() == 64);
945 const int h = image->height();
946 const int w = image->width();
947 uchar *scanline = image->bits();
948 const qsizetype bpl = image->bytesPerLine();
949 for (int y = 0; y < h; ++y) {
950 quint16 *dst = reinterpret_cast<uint16_t *>(scanline);
951 for (int x = w - 1; x >= 0; --x) {
952 dst[x * 4 + 3] = 0xffff;
953 dst[x * 4 + 2] = dst[x * 3 + 2];
954 dst[x * 4 + 1] = dst[x * 3 + 1];
955 dst[x * 4 + 0] = dst[x * 3 + 0];
956 }
957 scanline += bpl;
958 }
959 }
960
961 bool QTiffHandler::ensureHaveDirectoryCount() const
962 {
963 if (d->directoryCount > 0)
964 return true;
965
966 TIFF *tiff = TIFFClientOpen("foo",
967 "r",
968 device(),
969 qtiffReadProc,
970 qtiffWriteProc,
971 qtiffSeekProc,
972 qtiffCloseProc,
973 qtiffSizeProc,
974 qtiffMapProc,
975 qtiffUnmapProc);
976 if (!tiff) {
977 device()->reset();
978 return false;
979 }
980
981 do {
982 ++d->directoryCount;
983 } while (TIFFReadDirectory(tiff));
984 TIFFClose(tiff);
985 device()->reset();
986 return true;
987 }
988
989 QT_END_NAMESPACE