source: trunk/src/gui/image/qpnghandler.cpp@ 858

Last change on this file since 858 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 29.1 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtGui module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "private/qpnghandler_p.h"
43
44#ifndef QT_NO_IMAGEFORMAT_PNG
45#include <qcoreapplication.h>
46#include <qiodevice.h>
47#include <qimage.h>
48#include <qlist.h>
49#include <qtextcodec.h>
50#include <qvariant.h>
51#include <qvector.h>
52
53#ifdef QT_USE_BUNDLED_LIBPNG
54#include <../../3rdparty/libpng/png.h>
55#include <../../3rdparty/libpng/pngconf.h>
56#else
57#include <png.h>
58#include <pngconf.h>
59#endif
60
61#ifdef Q_OS_WINCE
62#define CALLBACK_CALL_TYPE __cdecl
63#else
64#define CALLBACK_CALL_TYPE
65#endif
66
67QT_BEGIN_NAMESPACE
68
69#if defined(Q_OS_WINCE) && defined(STANDARDSHELL_UI_MODEL)
70# define Q_INTERNAL_WIN_NO_THROW __declspec(nothrow)
71#else
72# define Q_INTERNAL_WIN_NO_THROW
73#endif
74
75// avoid going through QImage::scanLine() which calls detach
76#define FAST_SCAN_LINE(data, bpl, y) (data + (y) * bpl)
77
78/*
79 All PNG files load to the minimal QImage equivalent.
80
81 All QImage formats output to reasonably efficient PNG equivalents.
82 Never to grayscale.
83*/
84
85class QPngHandlerPrivate
86{
87public:
88 enum State {
89 Ready,
90 ReadHeader,
91 ReadingEnd,
92 Error
93 };
94
95 QPngHandlerPrivate(QPngHandler *qq)
96 : gamma(0.0), quality(2), png_ptr(0), info_ptr(0),
97 end_info(0), row_pointers(0), state(Ready), q(qq)
98 { }
99
100 float gamma;
101 int quality;
102 QString description;
103
104 png_struct *png_ptr;
105 png_info *info_ptr;
106 png_info *end_info;
107 png_byte **row_pointers;
108
109 bool readPngHeader();
110 bool readPngImage(QImage *image);
111
112 QImage::Format readImageFormat();
113
114 State state;
115
116 QPngHandler *q;
117};
118
119
120#if defined(Q_C_CALLBACKS)
121extern "C" {
122#endif
123
124class QPNGImageWriter {
125public:
126 explicit QPNGImageWriter(QIODevice*);
127 ~QPNGImageWriter();
128
129 enum DisposalMethod { Unspecified, NoDisposal, RestoreBackground, RestoreImage };
130 void setDisposalMethod(DisposalMethod);
131 void setLooping(int loops=0); // 0 == infinity
132 void setFrameDelay(int msecs);
133 void setGamma(float);
134
135 bool writeImage(const QImage& img, int x, int y);
136 bool writeImage(const QImage& img, int quality, const QString &description, int x, int y);
137 bool writeImage(const QImage& img)
138 { return writeImage(img, 0, 0); }
139 bool writeImage(const QImage& img, int quality, const QString &description)
140 { return writeImage(img, quality, description, 0, 0); }
141
142 QIODevice* device() { return dev; }
143
144private:
145 QIODevice* dev;
146 int frames_written;
147 DisposalMethod disposal;
148 int looping;
149 int ms_delay;
150 float gamma;
151};
152
153static
154void CALLBACK_CALL_TYPE iod_read_fn(png_structp png_ptr, png_bytep data, png_size_t length)
155{
156 QPngHandlerPrivate *d = (QPngHandlerPrivate *)png_get_io_ptr(png_ptr);
157 QIODevice *in = d->q->device();
158
159 if (d->state == QPngHandlerPrivate::ReadingEnd && !in->isSequential() && (in->size() - in->pos()) < 4 && length == 4) {
160 // Workaround for certain malformed PNGs that lack the final crc bytes
161 uchar endcrc[4] = { 0xae, 0x42, 0x60, 0x82 };
162 qMemCopy(data, endcrc, 4);
163 in->seek(in->size());
164 return;
165 }
166
167 while (length) {
168 int nr = in->read((char*)data, length);
169 if (nr <= 0) {
170 png_error(png_ptr, "Read Error");
171 return;
172 }
173 length -= nr;
174 }
175}
176
177
178static
179void CALLBACK_CALL_TYPE qpiw_write_fn(png_structp png_ptr, png_bytep data, png_size_t length)
180{
181 QPNGImageWriter* qpiw = (QPNGImageWriter*)png_get_io_ptr(png_ptr);
182 QIODevice* out = qpiw->device();
183
184 uint nr = out->write((char*)data, length);
185 if (nr != length) {
186 png_error(png_ptr, "Write Error");
187 return;
188 }
189}
190
191
192static
193void CALLBACK_CALL_TYPE qpiw_flush_fn(png_structp /* png_ptr */)
194{
195}
196
197#if defined(Q_C_CALLBACKS)
198}
199#endif
200
201static
202void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, float screen_gamma=0.0)
203{
204 if (screen_gamma != 0.0 && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
205 double file_gamma;
206 png_get_gAMA(png_ptr, info_ptr, &file_gamma);
207 png_set_gamma(png_ptr, screen_gamma, file_gamma);
208 }
209
210 png_uint_32 width;
211 png_uint_32 height;
212 int bit_depth;
213 int color_type;
214 png_bytep trans_alpha = 0;
215 png_color_16p trans_color_p = 0;
216 int num_trans;
217 png_colorp palette = 0;
218 int num_palette;
219 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
220
221 if (color_type == PNG_COLOR_TYPE_GRAY) {
222 // Black & White or 8-bit grayscale
223 if (bit_depth == 1 && png_get_channels(png_ptr, info_ptr) == 1) {
224 png_set_invert_mono(png_ptr);
225 png_read_update_info(png_ptr, info_ptr);
226 if (image.size() != QSize(width, height) || image.format() != QImage::Format_Mono) {
227 image = QImage(width, height, QImage::Format_Mono);
228 if (image.isNull())
229 return;
230 }
231 image.setColorCount(2);
232 image.setColor(1, qRgb(0,0,0));
233 image.setColor(0, qRgb(255,255,255));
234 } else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
235 png_set_expand(png_ptr);
236 png_set_strip_16(png_ptr);
237 png_set_gray_to_rgb(png_ptr);
238 if (image.size() != QSize(width, height) || image.format() != QImage::Format_ARGB32) {
239 image = QImage(width, height, QImage::Format_ARGB32);
240 if (image.isNull())
241 return;
242 }
243 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
244 png_set_swap_alpha(png_ptr);
245
246 png_read_update_info(png_ptr, info_ptr);
247 } else {
248 if (bit_depth == 16)
249 png_set_strip_16(png_ptr);
250 else if (bit_depth < 8)
251 png_set_packing(png_ptr);
252 int ncols = bit_depth < 8 ? 1 << bit_depth : 256;
253 png_read_update_info(png_ptr, info_ptr);
254 if (image.size() != QSize(width, height) || image.format() != QImage::Format_Indexed8) {
255 image = QImage(width, height, QImage::Format_Indexed8);
256 if (image.isNull())
257 return;
258 }
259 image.setColorCount(ncols);
260 for (int i=0; i<ncols; i++) {
261 int c = i*255/(ncols-1);
262 image.setColor(i, qRgba(c,c,c,0xff));
263 }
264 if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_color_p) {
265 const int g = trans_color_p->gray;
266 if (g < ncols) {
267 image.setColor(g, 0);
268 }
269 }
270 }
271 } else if (color_type == PNG_COLOR_TYPE_PALETTE
272 && png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette)
273 && num_palette <= 256)
274 {
275 // 1-bit and 8-bit color
276 if (bit_depth != 1)
277 png_set_packing(png_ptr);
278 png_read_update_info(png_ptr, info_ptr);
279 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
280 QImage::Format format = bit_depth == 1 ? QImage::Format_Mono : QImage::Format_Indexed8;
281 if (image.size() != QSize(width, height) || image.format() != format) {
282 image = QImage(width, height, format);
283 if (image.isNull())
284 return;
285 }
286 png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
287 image.setColorCount(num_palette);
288 int i = 0;
289 if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_alpha) {
290 while (i < num_trans) {
291 image.setColor(i, qRgba(
292 palette[i].red,
293 palette[i].green,
294 palette[i].blue,
295 trans_alpha[i]
296 )
297 );
298 i++;
299 }
300 }
301 while (i < num_palette) {
302 image.setColor(i, qRgba(
303 palette[i].red,
304 palette[i].green,
305 palette[i].blue,
306 0xff
307 )
308 );
309 i++;
310 }
311 } else {
312 // 32-bit
313 if (bit_depth == 16)
314 png_set_strip_16(png_ptr);
315
316 png_set_expand(png_ptr);
317
318 if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
319 png_set_gray_to_rgb(png_ptr);
320
321 QImage::Format format = QImage::Format_ARGB32;
322 // Only add filler if no alpha, or we can get 5 channel data.
323 if (!(color_type & PNG_COLOR_MASK_ALPHA)
324 && !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
325 png_set_filler(png_ptr, 0xff, QSysInfo::ByteOrder == QSysInfo::BigEndian ?
326 PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
327 // We want 4 bytes, but it isn't an alpha channel
328 format = QImage::Format_RGB32;
329 }
330 if (image.size() != QSize(width, height) || image.format() != format) {
331 image = QImage(width, height, format);
332 if (image.isNull())
333 return;
334 }
335
336 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
337 png_set_swap_alpha(png_ptr);
338
339 png_read_update_info(png_ptr, info_ptr);
340 }
341
342 // Qt==ARGB==Big(ARGB)==Little(BGRA)
343 if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) {
344 png_set_bgr(png_ptr);
345 }
346}
347
348
349#if defined(Q_C_CALLBACKS)
350extern "C" {
351#endif
352static void CALLBACK_CALL_TYPE qt_png_warning(png_structp /*png_ptr*/, png_const_charp message)
353{
354 qWarning("libpng warning: %s", message);
355}
356
357#if defined(Q_C_CALLBACKS)
358}
359#endif
360
361
362/*!
363 \internal
364*/
365bool Q_INTERNAL_WIN_NO_THROW QPngHandlerPrivate::readPngHeader()
366{
367 state = Error;
368 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0);
369 if (!png_ptr)
370 return false;
371
372 png_set_error_fn(png_ptr, 0, 0, qt_png_warning);
373
374 info_ptr = png_create_info_struct(png_ptr);
375 if (!info_ptr) {
376 png_destroy_read_struct(&png_ptr, 0, 0);
377 png_ptr = 0;
378 return false;
379 }
380
381 end_info = png_create_info_struct(png_ptr);
382 if (!end_info) {
383 png_destroy_read_struct(&png_ptr, &info_ptr, 0);
384 png_ptr = 0;
385 return false;
386 }
387
388 if (setjmp(png_jmpbuf(png_ptr))) {
389 png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
390 png_ptr = 0;
391 return false;
392 }
393
394 png_set_read_fn(png_ptr, this, iod_read_fn);
395 png_read_info(png_ptr, info_ptr);
396
397#ifndef QT_NO_IMAGE_TEXT
398 png_textp text_ptr;
399 int num_text=0;
400 png_get_text(png_ptr,info_ptr,&text_ptr,&num_text);
401
402 while (num_text--) {
403 QString key, value;
404#if defined(PNG_iTXt_SUPPORTED) && !defined(QT_NO_TEXTCODEC)
405 if (text_ptr->lang) {
406 QTextCodec *codec = QTextCodec::codecForName(text_ptr->lang);
407 if (codec) {
408 key = codec->toUnicode(text_ptr->lang_key);
409 value = codec->toUnicode(QByteArray(text_ptr->text, text_ptr->itxt_length));
410 } else {
411 key = QString::fromLatin1(text_ptr->key);
412 value = QString::fromLatin1(QByteArray(text_ptr->text, int(text_ptr->text_length)));
413 }
414 } else
415#endif
416 {
417 key = QString::fromLatin1(text_ptr->key);
418 value = QString::fromLatin1(QByteArray(text_ptr->text, int(text_ptr->text_length)));
419 }
420 if (!description.isEmpty())
421 description += QLatin1String("\n\n");
422 description += key + QLatin1String(": ") + value.simplified();
423 text_ptr++;
424 }
425#endif
426
427 state = ReadHeader;
428 return true;
429}
430
431/*!
432 \internal
433*/
434bool Q_INTERNAL_WIN_NO_THROW QPngHandlerPrivate::readPngImage(QImage *outImage)
435{
436 if (state == Error)
437 return false;
438
439 if (state == Ready && !readPngHeader()) {
440 state = Error;
441 return false;
442 }
443
444 row_pointers = 0;
445 if (setjmp(png_jmpbuf(png_ptr))) {
446 png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
447 delete [] row_pointers;
448 png_ptr = 0;
449 state = Error;
450 return false;
451 }
452
453 setup_qt(*outImage, png_ptr, info_ptr, gamma);
454
455 if (outImage->isNull()) {
456 png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
457 delete [] row_pointers;
458 png_ptr = 0;
459 state = Error;
460 return false;
461 }
462
463 png_uint_32 width;
464 png_uint_32 height;
465 int bit_depth;
466 int color_type;
467 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
468 0, 0, 0);
469
470 uchar *data = outImage->bits();
471 int bpl = outImage->bytesPerLine();
472 row_pointers = new png_bytep[height];
473
474 for (uint y = 0; y < height; y++)
475 row_pointers[y] = data + y * bpl;
476
477 png_read_image(png_ptr, row_pointers);
478
479#if 0 // libpng takes care of this.
480 png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)
481 if (outImage->depth()==32 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
482 QRgb trans = 0xFF000000 | qRgb(
483 (info_ptr->trans_values.red << 8 >> bit_depth)&0xff,
484 (info_ptr->trans_values.green << 8 >> bit_depth)&0xff,
485 (info_ptr->trans_values.blue << 8 >> bit_depth)&0xff);
486 for (uint y=0; y<height; y++) {
487 for (uint x=0; x<info_ptr->width; x++) {
488 if (((uint**)jt)[y][x] == trans) {
489 ((uint**)jt)[y][x] &= 0x00FFFFFF;
490 } else {
491 }
492 }
493 }
494 }
495#endif
496
497 outImage->setDotsPerMeterX(png_get_x_pixels_per_meter(png_ptr,info_ptr));
498 outImage->setDotsPerMeterY(png_get_y_pixels_per_meter(png_ptr,info_ptr));
499
500#ifndef QT_NO_IMAGE_TEXT
501 png_textp text_ptr;
502 int num_text=0;
503 png_get_text(png_ptr,info_ptr,&text_ptr,&num_text);
504 while (num_text--) {
505 outImage->setText(text_ptr->key,0,QString::fromAscii(text_ptr->text));
506 text_ptr++;
507 }
508
509 foreach (const QString &pair, description.split(QLatin1String("\n\n"))) {
510 int index = pair.indexOf(QLatin1Char(':'));
511 if (index >= 0 && pair.indexOf(QLatin1Char(' ')) < index) {
512 outImage->setText(QLatin1String("Description"), pair.simplified());
513 } else {
514 QString key = pair.left(index);
515 outImage->setText(key, pair.mid(index + 2).simplified());
516 }
517 }
518#endif
519
520 state = ReadingEnd;
521 png_read_end(png_ptr, end_info);
522 png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
523 delete [] row_pointers;
524 png_ptr = 0;
525 state = Ready;
526
527 // sanity check palette entries
528 if (color_type == PNG_COLOR_TYPE_PALETTE
529 && outImage->format() == QImage::Format_Indexed8) {
530 int color_table_size = outImage->colorCount();
531 for (int y=0; y<(int)height; ++y) {
532 uchar *p = FAST_SCAN_LINE(data, bpl, y);
533 uchar *end = p + width;
534 while (p < end) {
535 if (*p >= color_table_size)
536 *p = 0;
537 ++p;
538 }
539 }
540 }
541
542 return true;
543}
544
545QImage::Format QPngHandlerPrivate::readImageFormat()
546{
547 QImage::Format format = QImage::Format_Invalid;
548 png_uint_32 width, height;
549 int bit_depth, color_type;
550 png_colorp palette;
551 int num_palette;
552 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
553 if (color_type == PNG_COLOR_TYPE_GRAY) {
554 // Black & White or 8-bit grayscale
555 if (bit_depth == 1 && png_get_channels(png_ptr, info_ptr) == 1) {
556 format = QImage::Format_Mono;
557 } else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
558 format = QImage::Format_ARGB32;
559 } else {
560 format = QImage::Format_Indexed8;
561 }
562 } else if (color_type == PNG_COLOR_TYPE_PALETTE
563 && png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette)
564 && num_palette <= 256)
565 {
566 // 1-bit and 8-bit color
567 if (bit_depth != 1)
568 png_set_packing(png_ptr);
569 png_read_update_info(png_ptr, info_ptr);
570 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
571 format = bit_depth == 1 ? QImage::Format_Mono : QImage::Format_Indexed8;
572 } else {
573 // 32-bit
574 if (bit_depth == 16)
575 png_set_strip_16(png_ptr);
576
577 format = QImage::Format_ARGB32;
578 // Only add filler if no alpha, or we can get 5 channel data.
579 if (!(color_type & PNG_COLOR_MASK_ALPHA)
580 && !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
581 // We want 4 bytes, but it isn't an alpha channel
582 format = QImage::Format_RGB32;
583 }
584 }
585
586 return format;
587}
588
589QPNGImageWriter::QPNGImageWriter(QIODevice* iod) :
590 dev(iod),
591 frames_written(0),
592 disposal(Unspecified),
593 looping(-1),
594 ms_delay(-1),
595 gamma(0.0)
596{
597}
598
599QPNGImageWriter::~QPNGImageWriter()
600{
601}
602
603void QPNGImageWriter::setDisposalMethod(DisposalMethod dm)
604{
605 disposal = dm;
606}
607
608void QPNGImageWriter::setLooping(int loops)
609{
610 looping = loops;
611}
612
613void QPNGImageWriter::setFrameDelay(int msecs)
614{
615 ms_delay = msecs;
616}
617
618void QPNGImageWriter::setGamma(float g)
619{
620 gamma = g;
621}
622
623
624#ifndef QT_NO_IMAGE_TEXT
625static void set_text(const QImage &image, png_structp png_ptr, png_infop info_ptr,
626 const QString &description)
627{
628 QMap<QString, QString> text;
629 foreach (const QString &key, image.textKeys()) {
630 if (!key.isEmpty())
631 text.insert(key, image.text(key));
632 }
633 foreach (const QString &pair, description.split(QLatin1String("\n\n"))) {
634 int index = pair.indexOf(QLatin1Char(':'));
635 if (index >= 0 && pair.indexOf(QLatin1Char(' ')) < index) {
636 QString s = pair.simplified();
637 if (!s.isEmpty())
638 text.insert(QLatin1String("Description"), s);
639 } else {
640 QString key = pair.left(index);
641 if (!key.simplified().isEmpty())
642 text.insert(key, pair.mid(index + 2).simplified());
643 }
644 }
645
646 if (text.isEmpty())
647 return;
648
649 png_textp text_ptr = new png_text[text.size()];
650
651 QMap<QString, QString>::ConstIterator it = text.constBegin();
652 int i = 0;
653 while (it != text.constEnd()) {
654 QString t = it.value();
655 if (t.length() < 40)
656 text_ptr[i].compression = PNG_TEXT_COMPRESSION_NONE;
657 else
658 text_ptr[i].compression = PNG_TEXT_COMPRESSION_zTXt;
659 text_ptr[i].key = qstrdup(it.key().left(79).toLatin1().constData());
660
661#ifndef PNG_iTXt_SUPPORTED
662 QByteArray value = it.value().toLatin1();
663 text_ptr[i].text = qstrdup(value.constData());
664 text_ptr[i].text_length = value.size();
665#else
666 QByteArray value = it.value().toUtf8();
667 text_ptr[i].text = qstrdup(value.constData());
668 text_ptr[i].text_length = 0;
669 text_ptr[i].itxt_length = value.size();
670 text_ptr[i].lang = const_cast<char*>("UTF-8");
671 text_ptr[i].lang_key = qstrdup(it.key().toUtf8().constData());
672#endif
673 ++i;
674 ++it;
675 }
676
677 png_set_text(png_ptr, info_ptr, text_ptr, i);
678 for (i = 0; i < text.size(); ++i) {
679 delete [] text_ptr[i].key;
680 delete [] text_ptr[i].text;
681#ifdef PNG_iTXt_SUPPORTED
682 delete [] text_ptr[i].lang_key;
683#endif
684 }
685 delete [] text_ptr;
686}
687#endif
688
689bool QPNGImageWriter::writeImage(const QImage& image, int off_x, int off_y)
690{
691 return writeImage(image, -1, QString(), off_x, off_y);
692}
693
694bool Q_INTERNAL_WIN_NO_THROW QPNGImageWriter::writeImage(const QImage& image, int quality_in, const QString &description,
695 int off_x_in, int off_y_in)
696{
697#ifdef QT_NO_IMAGE_TEXT
698 Q_UNUSED(description);
699#endif
700
701 QPoint offset = image.offset();
702 int off_x = off_x_in + offset.x();
703 int off_y = off_y_in + offset.y();
704
705 png_structp png_ptr;
706 png_infop info_ptr;
707
708 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,0,0,0);
709 if (!png_ptr) {
710 return false;
711 }
712
713 png_set_error_fn(png_ptr, 0, 0, qt_png_warning);
714
715 info_ptr = png_create_info_struct(png_ptr);
716 if (!info_ptr) {
717 png_destroy_write_struct(&png_ptr, 0);
718 return false;
719 }
720
721 if (setjmp(png_jmpbuf(png_ptr))) {
722 png_destroy_write_struct(&png_ptr, &info_ptr);
723 return false;
724 }
725
726 int quality = quality_in;
727 if (quality >= 0) {
728 if (quality > 9) {
729 qWarning("PNG: Quality %d out of range", quality);
730 quality = 9;
731 }
732 png_set_compression_level(png_ptr, quality);
733 }
734
735 png_set_write_fn(png_ptr, (void*)this, qpiw_write_fn, qpiw_flush_fn);
736
737
738 int color_type = 0;
739 if (image.colorCount())
740 color_type = PNG_COLOR_TYPE_PALETTE;
741 else if (image.hasAlphaChannel())
742 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
743 else
744 color_type = PNG_COLOR_TYPE_RGB;
745
746 png_set_IHDR(png_ptr, info_ptr, image.width(), image.height(),
747 image.depth() == 1 ? 1 : 8, // per channel
748 color_type, 0, 0, 0); // sets #channels
749
750 if (gamma != 0.0) {
751 png_set_gAMA(png_ptr, info_ptr, 1.0/gamma);
752 }
753
754 png_color_8 sig_bit;
755 sig_bit.red = 8;
756 sig_bit.green = 8;
757 sig_bit.blue = 8;
758 sig_bit.alpha = image.hasAlphaChannel() ? 8 : 0;
759 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
760
761 if (image.format() == QImage::Format_MonoLSB)
762 png_set_packswap(png_ptr);
763
764 if (image.colorCount()) {
765 // Paletted
766 int num_palette = qMin(256, image.colorCount());
767 png_color palette[256];
768 png_byte trans[256];
769 int num_trans = 0;
770 for (int i=0; i<num_palette; i++) {
771 QRgb rgba=image.color(i);
772 palette[i].red = qRed(rgba);
773 palette[i].green = qGreen(rgba);
774 palette[i].blue = qBlue(rgba);
775 trans[i] = qAlpha(rgba);
776 if (trans[i] < 255) {
777 num_trans = i+1;
778 }
779 }
780 png_set_PLTE(png_ptr, info_ptr, palette, num_palette);
781
782 if (num_trans) {
783 png_set_tRNS(png_ptr, info_ptr, trans, num_trans, 0);
784 }
785 }
786
787 // Swap ARGB to RGBA (normal PNG format) before saving on
788 // BigEndian machines
789 if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
790 png_set_swap_alpha(png_ptr);
791 }
792
793 // Qt==ARGB==Big(ARGB)==Little(BGRA). But RGB888 is RGB regardless
794 if (QSysInfo::ByteOrder == QSysInfo::LittleEndian
795 && image.format() != QImage::Format_RGB888) {
796 png_set_bgr(png_ptr);
797 }
798
799 if (off_x || off_y) {
800 png_set_oFFs(png_ptr, info_ptr, off_x, off_y, PNG_OFFSET_PIXEL);
801 }
802
803 if (frames_written > 0)
804 png_set_sig_bytes(png_ptr, 8);
805
806 if (image.dotsPerMeterX() > 0 || image.dotsPerMeterY() > 0) {
807 png_set_pHYs(png_ptr, info_ptr,
808 image.dotsPerMeterX(), image.dotsPerMeterY(),
809 PNG_RESOLUTION_METER);
810 }
811
812#ifndef QT_NO_IMAGE_TEXT
813 set_text(image, png_ptr, info_ptr, description);
814#endif
815 png_write_info(png_ptr, info_ptr);
816
817 if (image.depth() != 1)
818 png_set_packing(png_ptr);
819
820 if (color_type == PNG_COLOR_TYPE_RGB && image.format() != QImage::Format_RGB888)
821 png_set_filler(png_ptr, 0,
822 QSysInfo::ByteOrder == QSysInfo::BigEndian ?
823 PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
824
825 if (looping >= 0 && frames_written == 0) {
826 uchar data[13] = "NETSCAPE2.0";
827 // 0123456789aBC
828 data[0xB] = looping%0x100;
829 data[0xC] = looping/0x100;
830 png_write_chunk(png_ptr, (png_byte*)"gIFx", data, 13);
831 }
832 if (ms_delay >= 0 || disposal!=Unspecified) {
833 uchar data[4];
834 data[0] = disposal;
835 data[1] = 0;
836 data[2] = (ms_delay/10)/0x100; // hundredths
837 data[3] = (ms_delay/10)%0x100;
838 png_write_chunk(png_ptr, (png_byte*)"gIFg", data, 4);
839 }
840
841 int height = image.height();
842 int width = image.width();
843 switch (image.format()) {
844 case QImage::Format_Mono:
845 case QImage::Format_MonoLSB:
846 case QImage::Format_Indexed8:
847 case QImage::Format_RGB32:
848 case QImage::Format_ARGB32:
849 case QImage::Format_RGB888:
850 {
851 png_bytep* row_pointers = new png_bytep[height];
852 for (int y=0; y<height; y++)
853 row_pointers[y] = (png_bytep)image.constScanLine(y);
854 png_write_image(png_ptr, row_pointers);
855 delete [] row_pointers;
856 }
857 break;
858 default:
859 {
860 QImage::Format fmt = image.hasAlphaChannel() ? QImage::Format_ARGB32 : QImage::Format_RGB32;
861 QImage row;
862 png_bytep row_pointers[1];
863 for (int y=0; y<height; y++) {
864 row = image.copy(0, y, width, 1).convertToFormat(fmt);
865 row_pointers[0] = png_bytep(row.constScanLine(0));
866 png_write_rows(png_ptr, row_pointers, 1);
867 }
868 }
869 break;
870 }
871
872 png_write_end(png_ptr, info_ptr);
873 frames_written++;
874
875 png_destroy_write_struct(&png_ptr, &info_ptr);
876
877 return true;
878}
879
880static bool write_png_image(const QImage &image, QIODevice *device,
881 int quality, float gamma, const QString &description)
882{
883 QPNGImageWriter writer(device);
884 if (quality >= 0) {
885 quality = qMin(quality, 100);
886 quality = (100-quality) * 9 / 91; // map [0,100] -> [9,0]
887 }
888 writer.setGamma(gamma);
889 return writer.writeImage(image, quality, description);
890}
891
892QPngHandler::QPngHandler()
893 : d(new QPngHandlerPrivate(this))
894{
895}
896
897QPngHandler::~QPngHandler()
898{
899 if (d->png_ptr)
900 png_destroy_read_struct(&d->png_ptr, &d->info_ptr, &d->end_info);
901 delete d;
902}
903
904bool QPngHandler::canRead() const
905{
906 if (d->state == QPngHandlerPrivate::Ready && !canRead(device()))
907 return false;
908
909 if (d->state != QPngHandlerPrivate::Error) {
910 setFormat("png");
911 return true;
912 }
913
914 return false;
915}
916
917bool QPngHandler::canRead(QIODevice *device)
918{
919 if (!device) {
920 qWarning("QPngHandler::canRead() called with no device");
921 return false;
922 }
923
924 return device->peek(8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
925}
926
927bool QPngHandler::read(QImage *image)
928{
929 if (!canRead())
930 return false;
931 return d->readPngImage(image);
932}
933
934bool QPngHandler::write(const QImage &image)
935{
936 return write_png_image(image, device(), d->quality, d->gamma, d->description);
937}
938
939bool QPngHandler::supportsOption(ImageOption option) const
940{
941 return option == Gamma
942 || option == Description
943 || option == ImageFormat
944 || option == Quality
945 || option == Size;
946}
947
948QVariant QPngHandler::option(ImageOption option) const
949{
950 if (d->state == QPngHandlerPrivate::Error)
951 return QVariant();
952 if (d->state == QPngHandlerPrivate::Ready && !d->readPngHeader())
953 return QVariant();
954
955 if (option == Gamma)
956 return d->gamma;
957 else if (option == Quality)
958 return d->quality;
959 else if (option == Description)
960 return d->description;
961 else if (option == Size)
962 return QSize(png_get_image_width(d->png_ptr, d->info_ptr),
963 png_get_image_height(d->png_ptr, d->info_ptr));
964 else if (option == ImageFormat)
965 return d->readImageFormat();
966 return 0;
967}
968
969void QPngHandler::setOption(ImageOption option, const QVariant &value)
970{
971 if (option == Gamma)
972 d->gamma = value.toFloat();
973 else if (option == Quality)
974 d->quality = value.toInt();
975 else if (option == Description)
976 d->description = value.toString();
977}
978
979QByteArray QPngHandler::name() const
980{
981 return "png";
982}
983
984QT_END_NAMESPACE
985
986#endif // QT_NO_IMAGEFORMAT_PNG
Note: See TracBrowser for help on using the repository browser.