gd_png.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include "gd.h"
  6. #include "gd_errors.h"
  7. /* JCE: Arrange HAVE_LIBPNG so that it can be set in gd.h */
  8. #ifdef HAVE_LIBPNG
  9. #include "png.h" /* includes zlib.h and setjmp.h */
  10. #include "gdhelpers.h"
  11. #define TRUE 1
  12. #define FALSE 0
  13. /*---------------------------------------------------------------------------
  14. gd_png.c Copyright 1999 Greg Roelofs and Thomas Boutell
  15. The routines in this file, gdImagePng*() and gdImageCreateFromPng*(),
  16. are drop-in replacements for gdImageGif*() and gdImageCreateFromGif*(),
  17. except that these functions are noisier in the case of errors (comment
  18. out all fprintf() statements to disable that).
  19. GD 2.0 supports RGBA truecolor and will read and write truecolor PNGs.
  20. GD 2.0 supports 8 bits of color resolution per channel and
  21. 7 bits of alpha channel resolution. Images with more than 8 bits
  22. per channel are reduced to 8 bits. Images with an alpha channel are
  23. only able to resolve down to '1/128th opaque' instead of '1/256th',
  24. and this conversion is also automatic. I very much doubt you can see it.
  25. Both tRNS and true alpha are supported.
  26. Gamma is ignored, and there is no support for text annotations.
  27. Last updated: 9 February 2001
  28. ---------------------------------------------------------------------------*/
  29. const char * gdPngGetVersionString()
  30. {
  31. return PNG_LIBPNG_VER_STRING;
  32. }
  33. #ifdef PNG_SETJMP_SUPPORTED
  34. typedef struct _jmpbuf_wrapper
  35. {
  36. jmp_buf jmpbuf;
  37. } jmpbuf_wrapper;
  38. static void gdPngErrorHandler (png_structp png_ptr, png_const_charp msg)
  39. {
  40. jmpbuf_wrapper *jmpbuf_ptr;
  41. /* This function, aside from the extra step of retrieving the "error
  42. * pointer" (below) and the fact that it exists within the application
  43. * rather than within libpng, is essentially identical to libpng's
  44. * default error handler. The second point is critical: since both
  45. * setjmp() and longjmp() are called from the same code, they are
  46. * guaranteed to have compatible notions of how big a jmp_buf is,
  47. * regardless of whether _BSD_SOURCE or anything else has (or has not)
  48. * been defined.
  49. */
  50. gd_error_ex(GD_WARNING, "gd-png: fatal libpng error: %s", msg);
  51. jmpbuf_ptr = png_get_error_ptr (png_ptr);
  52. if (jmpbuf_ptr == NULL) { /* we are completely hosed now */
  53. gd_error_ex(GD_ERROR, "gd-png: EXTREMELY fatal error: jmpbuf unrecoverable; terminating.");
  54. }
  55. longjmp (jmpbuf_ptr->jmpbuf, 1);
  56. }
  57. static void gdPngWarningHandler (png_structp png_ptr, png_const_charp msg)
  58. {
  59. gd_error_ex(GD_WARNING, "gd-png: libpng warning: %s", msg);
  60. }
  61. #endif
  62. static void gdPngReadData (png_structp png_ptr, png_bytep data, png_size_t length)
  63. {
  64. int check;
  65. check = gdGetBuf(data, length, (gdIOCtx *) png_get_io_ptr(png_ptr));
  66. if (check != length) {
  67. png_error(png_ptr, "Read Error: truncated data");
  68. }
  69. }
  70. static void gdPngWriteData (png_structp png_ptr, png_bytep data, png_size_t length)
  71. {
  72. gdPutBuf (data, length, (gdIOCtx *) png_get_io_ptr(png_ptr));
  73. }
  74. static void gdPngFlushData (png_structp png_ptr)
  75. {
  76. }
  77. gdImagePtr gdImageCreateFromPng (FILE * inFile)
  78. {
  79. gdImagePtr im;
  80. gdIOCtx *in = gdNewFileCtx(inFile);
  81. im = gdImageCreateFromPngCtx(in);
  82. in->gd_free(in);
  83. return im;
  84. }
  85. gdImagePtr gdImageCreateFromPngPtr (int size, void *data)
  86. {
  87. gdImagePtr im;
  88. gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
  89. im = gdImageCreateFromPngCtx(in);
  90. in->gd_free(in);
  91. return im;
  92. }
  93. /* This routine is based in part on the Chapter 13 demo code in "PNG: The
  94. * Definitive Guide" (http://www.cdrom.com/pub/png/pngbook.html).
  95. */
  96. gdImagePtr gdImageCreateFromPngCtx (gdIOCtx * infile)
  97. {
  98. png_byte sig[8];
  99. #ifdef PNG_SETJMP_SUPPORTED
  100. jmpbuf_wrapper jbw;
  101. #endif
  102. png_structp png_ptr;
  103. png_infop info_ptr;
  104. png_uint_32 width, height, rowbytes, w, h, res_x, res_y;
  105. int bit_depth, color_type, interlace_type, unit_type;
  106. int num_palette, num_trans;
  107. png_colorp palette;
  108. png_color_16p trans_gray_rgb;
  109. png_color_16p trans_color_rgb;
  110. png_bytep trans;
  111. volatile png_bytep image_data = NULL;
  112. volatile png_bytepp row_pointers = NULL;
  113. gdImagePtr im = NULL;
  114. int i, j, *open = NULL;
  115. volatile int transparent = -1;
  116. volatile int palette_allocated = FALSE;
  117. /* Make sure the signature can't match by dumb luck -- TBB */
  118. /* GRR: isn't sizeof(infile) equal to the size of the pointer? */
  119. memset (sig, 0, sizeof(sig));
  120. /* first do a quick check that the file really is a PNG image; could
  121. * have used slightly more general png_sig_cmp() function instead
  122. */
  123. if (gdGetBuf(sig, 8, infile) < 8) {
  124. return NULL;
  125. }
  126. if (png_sig_cmp(sig, 0, 8) != 0) { /* bad signature */
  127. return NULL;
  128. }
  129. #ifdef PNG_SETJMP_SUPPORTED
  130. png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, &jbw, gdPngErrorHandler, gdPngWarningHandler);
  131. #else
  132. png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  133. #endif
  134. if (png_ptr == NULL) {
  135. gd_error("gd-png error: cannot allocate libpng main struct");
  136. return NULL;
  137. }
  138. info_ptr = png_create_info_struct(png_ptr);
  139. if (info_ptr == NULL) {
  140. gd_error("gd-png error: cannot allocate libpng info struct");
  141. png_destroy_read_struct (&png_ptr, NULL, NULL);
  142. return NULL;
  143. }
  144. /* we could create a second info struct here (end_info), but it's only
  145. * useful if we want to keep pre- and post-IDAT chunk info separated
  146. * (mainly for PNG-aware image editors and converters)
  147. */
  148. /* setjmp() must be called in every non-callback function that calls a
  149. * PNG-reading libpng function
  150. */
  151. #ifdef PNG_SETJMP_SUPPORTED
  152. if (setjmp(jbw.jmpbuf)) {
  153. gd_error("gd-png error: setjmp returns error condition");
  154. png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
  155. return NULL;
  156. }
  157. #endif
  158. png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */
  159. png_set_read_fn(png_ptr, (void *) infile, gdPngReadData);
  160. png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */
  161. png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);
  162. if ((color_type == PNG_COLOR_TYPE_RGB) || (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  163. || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  164. im = gdImageCreateTrueColor((int) width, (int) height);
  165. } else {
  166. im = gdImageCreate((int) width, (int) height);
  167. }
  168. if (im == NULL) {
  169. gd_error("gd-png error: cannot allocate gdImage struct");
  170. png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
  171. return NULL;
  172. }
  173. if (bit_depth == 16) {
  174. png_set_strip_16(png_ptr);
  175. } else if (bit_depth < 8) {
  176. png_set_packing (png_ptr); /* expand to 1 byte per pixel */
  177. }
  178. /* setjmp() must be called in every non-callback function that calls a
  179. * PNG-reading libpng function
  180. */
  181. #ifdef PNG_SETJMP_SUPPORTED
  182. if (setjmp(jbw.jmpbuf)) {
  183. gd_error("gd-png error: setjmp returns error condition");
  184. png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
  185. gdFree(image_data);
  186. gdFree(row_pointers);
  187. if (im) {
  188. gdImageDestroy(im);
  189. }
  190. return NULL;
  191. }
  192. #endif
  193. #ifdef PNG_pHYs_SUPPORTED
  194. /* check if the resolution is specified */
  195. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_pHYs)) {
  196. if (png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y, &unit_type)) {
  197. switch (unit_type) {
  198. case PNG_RESOLUTION_METER:
  199. im->res_x = DPM2DPI(res_x);
  200. im->res_y = DPM2DPI(res_y);
  201. break;
  202. }
  203. }
  204. }
  205. #endif
  206. switch (color_type) {
  207. case PNG_COLOR_TYPE_PALETTE:
  208. png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
  209. #ifdef DEBUG
  210. gd_error("gd-png color_type is palette, colors: %d", num_palette);
  211. #endif /* DEBUG */
  212. if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS)) {
  213. /* gd 2.0: we support this rather thoroughly now. Grab the
  214. * first fully transparent entry, if any, as the value of
  215. * the simple-transparency index, mostly for backwards
  216. * binary compatibility. The alpha channel is where it's
  217. * really at these days.
  218. */
  219. int firstZero = 1;
  220. png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);
  221. for (i = 0; i < num_trans; ++i) {
  222. im->alpha[i] = gdAlphaMax - (trans[i] >> 1);
  223. if ((trans[i] == 0) && (firstZero)) {
  224. transparent = i;
  225. firstZero = 0;
  226. }
  227. }
  228. }
  229. break;
  230. case PNG_COLOR_TYPE_GRAY:
  231. /* create a fake palette and check for single-shade transparency */
  232. if ((palette = (png_colorp) gdMalloc (256 * sizeof (png_color))) == NULL) {
  233. gd_error("gd-png error: cannot allocate gray palette");
  234. png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
  235. return NULL;
  236. }
  237. palette_allocated = TRUE;
  238. if (bit_depth < 8) {
  239. num_palette = 1 << bit_depth;
  240. for (i = 0; i < 256; ++i) {
  241. j = (255 * i) / (num_palette - 1);
  242. palette[i].red = palette[i].green = palette[i].blue = j;
  243. }
  244. } else {
  245. num_palette = 256;
  246. for (i = 0; i < 256; ++i) {
  247. palette[i].red = palette[i].green = palette[i].blue = i;
  248. }
  249. }
  250. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
  251. png_get_tRNS(png_ptr, info_ptr, NULL, NULL, &trans_gray_rgb);
  252. if (bit_depth == 16) { /* png_set_strip_16() not yet in effect */
  253. transparent = trans_gray_rgb->gray >> 8;
  254. } else {
  255. transparent = trans_gray_rgb->gray;
  256. }
  257. /* Note slight error in 16-bit case: up to 256 16-bit shades
  258. * may get mapped to a single 8-bit shade, and only one of them
  259. * is supposed to be transparent. IOW, both opaque pixels and
  260. * transparent pixels will be mapped into the transparent entry.
  261. * There is no particularly good way around this in the case
  262. * that all 256 8-bit shades are used, but one could write some
  263. * custom 16-bit code to handle the case where there are gdFree
  264. * palette entries. This error will be extremely rare in
  265. * general, though. (Quite possibly there is only one such
  266. * image in existence.)
  267. */
  268. }
  269. break;
  270. case PNG_COLOR_TYPE_GRAY_ALPHA:
  271. png_set_gray_to_rgb(png_ptr);
  272. ZEND_FALLTHROUGH;
  273. case PNG_COLOR_TYPE_RGB:
  274. case PNG_COLOR_TYPE_RGB_ALPHA:
  275. /* gd 2.0: we now support truecolor. See the comment above
  276. * for a rare situation in which the transparent pixel may not
  277. * work properly with 16-bit channels.
  278. */
  279. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
  280. png_get_tRNS(png_ptr, info_ptr, NULL, NULL, &trans_color_rgb);
  281. if (bit_depth == 16) { /* png_set_strip_16() not yet in effect */
  282. transparent = gdTrueColor(trans_color_rgb->red >> 8,
  283. trans_color_rgb->green >> 8,
  284. trans_color_rgb->blue >> 8);
  285. } else {
  286. transparent = gdTrueColor(trans_color_rgb->red,
  287. trans_color_rgb->green,
  288. trans_color_rgb->blue);
  289. }
  290. }
  291. break;
  292. }
  293. /* enable the interlace transform if supported */
  294. #ifdef PNG_READ_INTERLACING_SUPPORTED
  295. (void)png_set_interlace_handling(png_ptr);
  296. #endif
  297. png_read_update_info(png_ptr, info_ptr);
  298. /* allocate space for the PNG image data */
  299. rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  300. image_data = (png_bytep) safe_emalloc(rowbytes, height, 0);
  301. row_pointers = (png_bytepp) safe_emalloc(height, sizeof(png_bytep), 0);
  302. /* set the individual row_pointers to point at the correct offsets */
  303. for (h = 0; h < height; ++h) {
  304. row_pointers[h] = image_data + h * rowbytes;
  305. }
  306. png_read_image(png_ptr, row_pointers); /* read whole image... */
  307. png_read_end(png_ptr, NULL); /* ...done! */
  308. if (!im->trueColor) {
  309. im->colorsTotal = num_palette;
  310. /* load the palette and mark all entries "open" (unused) for now */
  311. open = im->open;
  312. for (i = 0; i < num_palette; ++i) {
  313. im->red[i] = palette[i].red;
  314. im->green[i] = palette[i].green;
  315. im->blue[i] = palette[i].blue;
  316. open[i] = 1;
  317. }
  318. for (i = num_palette; i < gdMaxColors; ++i) {
  319. open[i] = 1;
  320. }
  321. }
  322. /* 2.0.12: Slaven Rezic: palette images are not the only images
  323. * with a simple transparent color setting.
  324. */
  325. im->transparent = transparent;
  326. im->interlace = (interlace_type == PNG_INTERLACE_ADAM7);
  327. /* can't nuke structs until done with palette */
  328. png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
  329. switch (color_type) {
  330. case PNG_COLOR_TYPE_RGB:
  331. for (h = 0; h < height; h++) {
  332. int boffset = 0;
  333. for (w = 0; w < width; w++) {
  334. register png_byte r = row_pointers[h][boffset++];
  335. register png_byte g = row_pointers[h][boffset++];
  336. register png_byte b = row_pointers[h][boffset++];
  337. im->tpixels[h][w] = gdTrueColor (r, g, b);
  338. }
  339. }
  340. break;
  341. case PNG_COLOR_TYPE_GRAY_ALPHA:
  342. case PNG_COLOR_TYPE_RGB_ALPHA:
  343. for (h = 0; h < height; h++) {
  344. int boffset = 0;
  345. for (w = 0; w < width; w++) {
  346. register png_byte r = row_pointers[h][boffset++];
  347. register png_byte g = row_pointers[h][boffset++];
  348. register png_byte b = row_pointers[h][boffset++];
  349. /* gd has only 7 bits of alpha channel resolution, and
  350. * 127 is transparent, 0 opaque. A moment of convenience,
  351. * a lifetime of compatibility.
  352. */
  353. register png_byte a = gdAlphaMax - (row_pointers[h][boffset++] >> 1);
  354. im->tpixels[h][w] = gdTrueColorAlpha(r, g, b, a);
  355. }
  356. }
  357. break;
  358. default:
  359. /* Palette image, or something coerced to be one */
  360. for (h = 0; h < height; ++h) {
  361. for (w = 0; w < width; ++w) {
  362. register png_byte idx = row_pointers[h][w];
  363. im->pixels[h][w] = idx;
  364. open[idx] = 0;
  365. }
  366. }
  367. }
  368. #ifdef DEBUG
  369. if (!im->trueColor) {
  370. for (i = num_palette; i < gdMaxColors; ++i) {
  371. if (!open[i]) {
  372. gd_error("gd-png warning: image data references out-of-range color index (%d)", i);
  373. }
  374. }
  375. }
  376. #endif
  377. if (palette_allocated) {
  378. gdFree(palette);
  379. }
  380. gdFree(image_data);
  381. gdFree(row_pointers);
  382. return im;
  383. }
  384. void gdImagePngEx (gdImagePtr im, FILE * outFile, int level, int basefilter)
  385. {
  386. gdIOCtx *out = gdNewFileCtx(outFile);
  387. gdImagePngCtxEx(im, out, level, basefilter);
  388. out->gd_free(out);
  389. }
  390. void gdImagePng (gdImagePtr im, FILE * outFile)
  391. {
  392. gdIOCtx *out = gdNewFileCtx(outFile);
  393. gdImagePngCtxEx(im, out, -1, -1);
  394. out->gd_free(out);
  395. }
  396. void * gdImagePngPtr (gdImagePtr im, int *size)
  397. {
  398. void *rv;
  399. gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
  400. gdImagePngCtxEx(im, out, -1, -1);
  401. rv = gdDPExtractData(out, size);
  402. out->gd_free(out);
  403. return rv;
  404. }
  405. void * gdImagePngPtrEx (gdImagePtr im, int *size, int level, int basefilter)
  406. {
  407. void *rv;
  408. gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
  409. gdImagePngCtxEx(im, out, level, basefilter);
  410. rv = gdDPExtractData(out, size);
  411. out->gd_free(out);
  412. return rv;
  413. }
  414. void gdImagePngCtx (gdImagePtr im, gdIOCtx * outfile)
  415. {
  416. gdImagePngCtxEx(im, outfile, -1, -1);
  417. }
  418. /* This routine is based in part on code from Dale Lutz (Safe Software Inc.)
  419. * and in part on demo code from Chapter 15 of "PNG: The Definitive Guide"
  420. * (http://www.cdrom.com/pub/png/pngbook.html).
  421. */
  422. void gdImagePngCtxEx (gdImagePtr im, gdIOCtx * outfile, int level, int basefilter)
  423. {
  424. int i, j, bit_depth = 0, interlace_type;
  425. int width = im->sx;
  426. int height = im->sy;
  427. int colors = im->colorsTotal;
  428. int *open = im->open;
  429. int mapping[gdMaxColors]; /* mapping[gd_index] == png_index */
  430. png_byte trans_values[256];
  431. png_color_16 trans_rgb_value;
  432. png_color palette[gdMaxColors];
  433. png_structp png_ptr;
  434. png_infop info_ptr;
  435. volatile int transparent = im->transparent;
  436. volatile int remap = FALSE;
  437. #ifdef PNG_SETJMP_SUPPORTED
  438. jmpbuf_wrapper jbw;
  439. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, &jbw, gdPngErrorHandler, gdPngWarningHandler);
  440. #else
  441. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  442. #endif
  443. if (png_ptr == NULL) {
  444. gd_error("gd-png error: cannot allocate libpng main struct");
  445. return;
  446. }
  447. info_ptr = png_create_info_struct(png_ptr);
  448. if (info_ptr == NULL) {
  449. gd_error("gd-png error: cannot allocate libpng info struct");
  450. png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
  451. return;
  452. }
  453. #ifdef PNG_SETJMP_SUPPORTED
  454. if (setjmp(jbw.jmpbuf)) {
  455. gd_error("gd-png error: setjmp returns error condition");
  456. png_destroy_write_struct (&png_ptr, &info_ptr);
  457. return;
  458. }
  459. #endif
  460. png_set_write_fn(png_ptr, (void *) outfile, gdPngWriteData, gdPngFlushData);
  461. /* This is best for palette images, and libpng defaults to it for
  462. * palette images anyway, so we don't need to do it explicitly.
  463. * What to ideally do for truecolor images depends, alas, on the image.
  464. * gd is intentionally imperfect and doesn't spend a lot of time
  465. * fussing with such things.
  466. */
  467. /* png_set_filter(png_ptr, 0, PNG_FILTER_NONE); */
  468. /* 2.0.12: this is finally a parameter */
  469. if (level != -1 && (level < 0 || level > 9)) {
  470. gd_error("gd-png error: compression level must be 0 through 9");
  471. return;
  472. }
  473. png_set_compression_level(png_ptr, level);
  474. if (basefilter >= 0) {
  475. png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, basefilter);
  476. }
  477. #ifdef PNG_pHYs_SUPPORTED
  478. /* 2.1.0: specify the resolution */
  479. png_set_pHYs(png_ptr, info_ptr, DPI2DPM(im->res_x), DPI2DPM(im->res_y),
  480. PNG_RESOLUTION_METER);
  481. #endif
  482. /* can set this to a smaller value without compromising compression if all
  483. * image data is 16K or less; will save some decoder memory [min == 8]
  484. */
  485. /* png_set_compression_window_bits(png_ptr, 15); */
  486. if (!im->trueColor) {
  487. if (transparent >= im->colorsTotal || (transparent >= 0 && open[transparent])) {
  488. transparent = -1;
  489. }
  490. for (i = 0; i < gdMaxColors; ++i) {
  491. mapping[i] = -1;
  492. }
  493. /* count actual number of colors used (colorsTotal == high-water mark) */
  494. colors = 0;
  495. for (i = 0; i < im->colorsTotal; ++i) {
  496. if (!open[i]) {
  497. mapping[i] = colors;
  498. ++colors;
  499. }
  500. }
  501. if (colors == 0) {
  502. gd_error("gd-png error: no colors in palette");
  503. goto bail;
  504. }
  505. if (colors < im->colorsTotal) {
  506. remap = TRUE;
  507. }
  508. if (colors <= 2) {
  509. bit_depth = 1;
  510. } else if (colors <= 4) {
  511. bit_depth = 2;
  512. } else if (colors <= 16) {
  513. bit_depth = 4;
  514. } else {
  515. bit_depth = 8;
  516. }
  517. }
  518. interlace_type = im->interlace ? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE;
  519. if (im->trueColor) {
  520. if (im->saveAlphaFlag) {
  521. png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, interlace_type,
  522. PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
  523. } else {
  524. png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB, interlace_type,
  525. PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
  526. }
  527. } else {
  528. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, PNG_COLOR_TYPE_PALETTE, interlace_type,
  529. PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
  530. }
  531. if (im->trueColor && !im->saveAlphaFlag && (transparent >= 0)) {
  532. /* 2.0.9: fixed by Thomas Winzig */
  533. trans_rgb_value.red = gdTrueColorGetRed (im->transparent);
  534. trans_rgb_value.green = gdTrueColorGetGreen (im->transparent);
  535. trans_rgb_value.blue = gdTrueColorGetBlue (im->transparent);
  536. png_set_tRNS(png_ptr, info_ptr, 0, 0, &trans_rgb_value);
  537. }
  538. if (!im->trueColor) {
  539. /* Oy veh. Remap the PNG palette to put the entries with interesting alpha channel
  540. * values first. This minimizes the size of the tRNS chunk and thus the size
  541. * of the PNG file as a whole.
  542. */
  543. int tc = 0;
  544. int i;
  545. int j;
  546. int k;
  547. for (i = 0; (i < im->colorsTotal); i++) {
  548. if ((!im->open[i]) && (im->alpha[i] != gdAlphaOpaque)) {
  549. tc++;
  550. }
  551. }
  552. if (tc) {
  553. #if 0
  554. for (i = 0; (i < im->colorsTotal); i++) {
  555. trans_values[i] = 255 - ((im->alpha[i] << 1) + (im->alpha[i] >> 6));
  556. }
  557. png_set_tRNS (png_ptr, info_ptr, trans_values, 256, NULL);
  558. #endif
  559. if (!remap) {
  560. remap = TRUE;
  561. }
  562. /* (Semi-)transparent indexes come up from the bottom of the list of real colors; opaque
  563. * indexes come down from the top
  564. */
  565. j = 0;
  566. k = colors - 1;
  567. for (i = 0; i < im->colorsTotal; i++) {
  568. if (!im->open[i]) {
  569. if (im->alpha[i] != gdAlphaOpaque) {
  570. /* Andrew Hull: >> 6, not >> 7! (gd 2.0.5) */
  571. trans_values[j] = 255 - ((im->alpha[i] << 1) + (im->alpha[i] >> 6));
  572. mapping[i] = j++;
  573. } else {
  574. mapping[i] = k--;
  575. }
  576. }
  577. }
  578. png_set_tRNS(png_ptr, info_ptr, trans_values, tc, NULL);
  579. }
  580. }
  581. /* convert palette to libpng layout */
  582. if (!im->trueColor) {
  583. if (remap) {
  584. for (i = 0; i < im->colorsTotal; ++i) {
  585. if (mapping[i] < 0) {
  586. continue;
  587. }
  588. palette[mapping[i]].red = im->red[i];
  589. palette[mapping[i]].green = im->green[i];
  590. palette[mapping[i]].blue = im->blue[i];
  591. }
  592. } else {
  593. for (i = 0; i < colors; ++i) {
  594. palette[i].red = im->red[i];
  595. palette[i].green = im->green[i];
  596. palette[i].blue = im->blue[i];
  597. }
  598. }
  599. png_set_PLTE(png_ptr, info_ptr, palette, colors);
  600. }
  601. /* write out the PNG header info (everything up to first IDAT) */
  602. png_write_info(png_ptr, info_ptr);
  603. /* make sure < 8-bit images are packed into pixels as tightly as possible */
  604. png_set_packing(png_ptr);
  605. /* This code allocates a set of row buffers and copies the gd image data
  606. * into them only in the case that remapping is necessary; in gd 1.3 and
  607. * later, the im->pixels array is laid out identically to libpng's row
  608. * pointers and can be passed to png_write_image() function directly.
  609. * The remapping case could be accomplished with less memory for non-
  610. * interlaced images, but interlacing causes some serious complications.
  611. */
  612. if (im->trueColor) {
  613. /* performance optimizations by Phong Tran */
  614. int channels = im->saveAlphaFlag ? 4 : 3;
  615. /* Our little 7-bit alpha channel trick costs us a bit here. */
  616. png_bytep *row_pointers;
  617. unsigned char* pOutputRow;
  618. int **ptpixels = im->tpixels;
  619. int *pThisRow;
  620. unsigned char a;
  621. int thisPixel;
  622. png_bytep *prow_pointers;
  623. int saveAlphaFlag = im->saveAlphaFlag;
  624. row_pointers = safe_emalloc(sizeof(png_bytep), height, 0);
  625. prow_pointers = row_pointers;
  626. for (j = 0; j < height; ++j) {
  627. *prow_pointers = (png_bytep) safe_emalloc(width, channels, 0);
  628. pOutputRow = *prow_pointers++;
  629. pThisRow = *ptpixels++;
  630. for (i = 0; i < width; ++i) {
  631. thisPixel = *pThisRow++;
  632. *pOutputRow++ = gdTrueColorGetRed(thisPixel);
  633. *pOutputRow++ = gdTrueColorGetGreen(thisPixel);
  634. *pOutputRow++ = gdTrueColorGetBlue(thisPixel);
  635. if (saveAlphaFlag) {
  636. /* convert the 7-bit alpha channel to an 8-bit alpha channel.
  637. * We do a little bit-flipping magic, repeating the MSB
  638. * as the LSB, to ensure that 0 maps to 0 and
  639. * 127 maps to 255. We also have to invert to match
  640. * PNG's convention in which 255 is opaque.
  641. */
  642. a = gdTrueColorGetAlpha(thisPixel);
  643. /* Andrew Hull: >> 6, not >> 7! (gd 2.0.5) */
  644. *pOutputRow++ = 255 - ((a << 1) + (a >> 6));
  645. }
  646. }
  647. }
  648. png_write_image(png_ptr, row_pointers);
  649. png_write_end(png_ptr, info_ptr);
  650. for (j = 0; j < height; ++j) {
  651. gdFree(row_pointers[j]);
  652. }
  653. gdFree(row_pointers);
  654. } else {
  655. if (remap) {
  656. png_bytep *row_pointers;
  657. row_pointers = safe_emalloc(height, sizeof(png_bytep), 0);
  658. for (j = 0; j < height; ++j) {
  659. row_pointers[j] = (png_bytep) gdMalloc(width);
  660. for (i = 0; i < width; ++i) {
  661. row_pointers[j][i] = mapping[im->pixels[j][i]];
  662. }
  663. }
  664. png_write_image(png_ptr, row_pointers);
  665. png_write_end(png_ptr, info_ptr);
  666. for (j = 0; j < height; ++j) {
  667. gdFree(row_pointers[j]);
  668. }
  669. gdFree(row_pointers);
  670. } else {
  671. png_write_image(png_ptr, im->pixels);
  672. png_write_end(png_ptr, info_ptr);
  673. }
  674. }
  675. /* 1.6.3: maybe we should give that memory BACK! TBB */
  676. bail:
  677. png_destroy_write_struct(&png_ptr, &info_ptr);
  678. }
  679. #endif /* HAVE_LIBPNG */