PageRenderTime 55ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/qtopiacore/qt/src/gui/image/qpnghandler.cpp

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