1
2/* pngwrite.c - general routines to write a PNG file
3 *
4 * Copyright (c) 2018-2019 Cosmin Truta
5 * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
6 * Copyright (c) 1996-1997 Andreas Dilger
7 * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
8 *
9 * This code is released under the libpng license.
10 * For conditions of distribution and use, see the disclaimer
11 * and license in png.h
12 */
13
14#include "pngpriv.h"
15#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
16# include <errno.h>
17#endif /* SIMPLIFIED_WRITE_STDIO */
18
19#ifdef PNG_WRITE_SUPPORTED
20
21#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
22/* Write out all the unknown chunks for the current given location */
23static void
24write_unknown_chunks(png_structrp png_ptr, png_const_inforp info_ptr,
25 unsigned int where)
26{
27 if (info_ptr->unknown_chunks_num != 0)
28 {
29 png_const_unknown_chunkp up;
30
31 png_debug(5, "writing extra chunks");
32
33 for (up = info_ptr->unknown_chunks;
34 up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
35 ++up)
36 if ((up->location & where) != 0)
37 {
38 /* If per-chunk unknown chunk handling is enabled use it, otherwise
39 * just write the chunks the application has set.
40 */
41#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
42 int keep = png_handle_as_unknown(png_ptr, up->name);
43
44 /* NOTE: this code is radically different from the read side in the
45 * matter of handling an ancillary unknown chunk. In the read side
46 * the default behavior is to discard it, in the code below the default
47 * behavior is to write it. Critical chunks are, however, only
48 * written if explicitly listed or if the default is set to write all
49 * unknown chunks.
50 *
51 * The default handling is also slightly weird - it is not possible to
52 * stop the writing of all unsafe-to-copy chunks!
53 *
54 * TODO: REVIEW: this would seem to be a bug.
55 */
56 if (keep != PNG_HANDLE_CHUNK_NEVER &&
57 ((up->name[3] & 0x20) /* safe-to-copy overrides everything */ ||
58 keep == PNG_HANDLE_CHUNK_ALWAYS ||
59 (keep == PNG_HANDLE_CHUNK_AS_DEFAULT &&
60 png_ptr->unknown_default == PNG_HANDLE_CHUNK_ALWAYS)))
61#endif
62 {
63 /* TODO: review, what is wrong with a zero length unknown chunk? */
64 if (up->size == 0)
65 png_warning(png_ptr, "Writing zero-length unknown chunk");
66
67 png_write_chunk(png_ptr, up->name, up->data, up->size);
68 }
69 }
70 }
71}
72#endif /* WRITE_UNKNOWN_CHUNKS */
73
74/* Writes all the PNG information. This is the suggested way to use the
75 * library. If you have a new chunk to add, make a function to write it,
76 * and put it in the correct location here. If you want the chunk written
77 * after the image data, put it in png_write_end(). I strongly encourage
78 * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
79 * the chunk, as that will keep the code from breaking if you want to just
80 * write a plain PNG file. If you have long comments, I suggest writing
81 * them in png_write_end(), and compressing them.
82 */
83void PNGAPI
84png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr)
85{
86 png_debug(1, "in png_write_info_before_PLTE");
87
88 if (png_ptr == NULL || info_ptr == NULL)
89 return;
90
91 if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
92 {
93 /* Write PNG signature */
94 png_write_sig(png_ptr);
95
96#ifdef PNG_MNG_FEATURES_SUPPORTED
97 if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \
98 png_ptr->mng_features_permitted != 0)
99 {
100 png_warning(png_ptr,
101 "MNG features are not allowed in a PNG datastream");
102 png_ptr->mng_features_permitted = 0;
103 }
104#endif
105
106 /* Write IHDR information. */
107 png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
108 info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
109 info_ptr->filter_type,
110#ifdef PNG_WRITE_INTERLACING_SUPPORTED
111 info_ptr->interlace_type
112#else
113 0
114#endif
115 );
116
117 /* The rest of these check to see if the valid field has the appropriate
118 * flag set, and if it does, writes the chunk.
119 *
120 * 1.6.0: COLORSPACE support controls the writing of these chunks too, and
121 * the chunks will be written if the WRITE routine is there and
122 * information * is available in the COLORSPACE. (See
123 * png_colorspace_sync_info in png.c for where the valid flags get set.)
124 *
125 * Under certain circumstances the colorspace can be invalidated without
126 * syncing the info_struct 'valid' flags; this happens if libpng detects
127 * an error and calls png_error while the color space is being set, yet
128 * the application continues writing the PNG. So check the 'invalid'
129 * flag here too.
130 */
131#ifdef PNG_GAMMA_SUPPORTED
132# ifdef PNG_WRITE_gAMA_SUPPORTED
133 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
134 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_gAMA) != 0 &&
135 (info_ptr->valid & PNG_INFO_gAMA) != 0)
136 png_write_gAMA_fixed(png_ptr, info_ptr->colorspace.gamma);
137# endif
138#endif
139
140#ifdef PNG_COLORSPACE_SUPPORTED
141 /* Write only one of sRGB or an ICC profile. If a profile was supplied
142 * and it matches one of the known sRGB ones issue a warning.
143 */
144# ifdef PNG_WRITE_iCCP_SUPPORTED
145 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
146 (info_ptr->valid & PNG_INFO_iCCP) != 0)
147 {
148# ifdef PNG_WRITE_sRGB_SUPPORTED
149 if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
150 png_app_warning(png_ptr,
151 "profile matches sRGB but writing iCCP instead");
152# endif
153
154 png_write_iCCP(png_ptr, info_ptr->iccp_name,
155 info_ptr->iccp_profile);
156 }
157# ifdef PNG_WRITE_sRGB_SUPPORTED
158 else
159# endif
160# endif
161
162# ifdef PNG_WRITE_sRGB_SUPPORTED
163 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
164 (info_ptr->valid & PNG_INFO_sRGB) != 0)
165 png_write_sRGB(png_ptr, info_ptr->colorspace.rendering_intent);
166# endif /* WRITE_sRGB */
167#endif /* COLORSPACE */
168
169#ifdef PNG_WRITE_sBIT_SUPPORTED
170 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
171 png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
172#endif
173
174#ifdef PNG_COLORSPACE_SUPPORTED
175# ifdef PNG_WRITE_cHRM_SUPPORTED
176 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
177 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0 &&
178 (info_ptr->valid & PNG_INFO_cHRM) != 0)
179 png_write_cHRM_fixed(png_ptr, &info_ptr->colorspace.end_points_xy);
180# endif
181#endif
182
183#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
184 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
185#endif
186
187 png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
188 }
189}
190
191void PNGAPI
192png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
193{
194#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
195 int i;
196#endif
197
198 png_debug(1, "in png_write_info");
199
200 if (png_ptr == NULL || info_ptr == NULL)
201 return;
202
203 png_write_info_before_PLTE(png_ptr, info_ptr);
204
205 if ((info_ptr->valid & PNG_INFO_PLTE) != 0)
206 png_write_PLTE(png_ptr, info_ptr->palette,
207 (png_uint_32)info_ptr->num_palette);
208
209 else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
210 png_error(png_ptr, "Valid palette required for paletted images");
211
212#ifdef PNG_WRITE_tRNS_SUPPORTED
213 if ((info_ptr->valid & PNG_INFO_tRNS) !=0)
214 {
215#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
216 /* Invert the alpha channel (in tRNS) */
217 if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 &&
218 info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
219 {
220 int j, jend;
221
222 jend = info_ptr->num_trans;
223 if (jend > PNG_MAX_PALETTE_LENGTH)
224 jend = PNG_MAX_PALETTE_LENGTH;
225
226 for (j = 0; j<jend; ++j)
227 info_ptr->trans_alpha[j] =
228 (png_byte)(255 - info_ptr->trans_alpha[j]);
229 }
230#endif
231 png_write_tRNS(png_ptr, info_ptr->trans_alpha, &(info_ptr->trans_color),
232 info_ptr->num_trans, info_ptr->color_type);
233 }
234#endif
235#ifdef PNG_WRITE_bKGD_SUPPORTED
236 if ((info_ptr->valid & PNG_INFO_bKGD) != 0)
237 png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
238#endif
239
240#ifdef PNG_WRITE_eXIf_SUPPORTED
241 if ((info_ptr->valid & PNG_INFO_eXIf) != 0)
242 png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
243#endif
244
245#ifdef PNG_WRITE_hIST_SUPPORTED
246 if ((info_ptr->valid & PNG_INFO_hIST) != 0)
247 png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
248#endif
249
250#ifdef PNG_WRITE_oFFs_SUPPORTED
251 if ((info_ptr->valid & PNG_INFO_oFFs) != 0)
252 png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
253 info_ptr->offset_unit_type);
254#endif
255
256#ifdef PNG_WRITE_pCAL_SUPPORTED
257 if ((info_ptr->valid & PNG_INFO_pCAL) != 0)
258 png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
259 info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
260 info_ptr->pcal_units, info_ptr->pcal_params);
261#endif
262
263#ifdef PNG_WRITE_sCAL_SUPPORTED
264 if ((info_ptr->valid & PNG_INFO_sCAL) != 0)
265 png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
266 info_ptr->scal_s_width, info_ptr->scal_s_height);
267#endif /* sCAL */
268
269#ifdef PNG_WRITE_pHYs_SUPPORTED
270 if ((info_ptr->valid & PNG_INFO_pHYs) != 0)
271 png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
272 info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
273#endif /* pHYs */
274
275#ifdef PNG_WRITE_tIME_SUPPORTED
276 if ((info_ptr->valid & PNG_INFO_tIME) != 0)
277 {
278 png_write_tIME(png_ptr, &(info_ptr->mod_time));
279 png_ptr->mode |= PNG_WROTE_tIME;
280 }
281#endif /* tIME */
282
283#ifdef PNG_WRITE_sPLT_SUPPORTED
284 if ((info_ptr->valid & PNG_INFO_sPLT) != 0)
285 for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
286 png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
287#endif /* sPLT */
288
289#ifdef PNG_WRITE_TEXT_SUPPORTED
290 /* Check to see if we need to write text chunks */
291 for (i = 0; i < info_ptr->num_text; i++)
292 {
293 png_debug2(2, "Writing header text chunk %d, type %d", i,
294 info_ptr->text[i].compression);
295 /* An internationalized chunk? */
296 if (info_ptr->text[i].compression > 0)
297 {
298#ifdef PNG_WRITE_iTXt_SUPPORTED
299 /* Write international chunk */
300 png_write_iTXt(png_ptr,
301 info_ptr->text[i].compression,
302 info_ptr->text[i].key,
303 info_ptr->text[i].lang,
304 info_ptr->text[i].lang_key,
305 info_ptr->text[i].text);
306 /* Mark this chunk as written */
307 if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
308 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
309 else
310 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
311#else
312 png_warning(png_ptr, "Unable to write international text");
313#endif
314 }
315
316 /* If we want a compressed text chunk */
317 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
318 {
319#ifdef PNG_WRITE_zTXt_SUPPORTED
320 /* Write compressed chunk */
321 png_write_zTXt(png_ptr, info_ptr->text[i].key,
322 info_ptr->text[i].text, info_ptr->text[i].compression);
323 /* Mark this chunk as written */
324 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
325#else
326 png_warning(png_ptr, "Unable to write compressed text");
327#endif
328 }
329
330 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
331 {
332#ifdef PNG_WRITE_tEXt_SUPPORTED
333 /* Write uncompressed chunk */
334 png_write_tEXt(png_ptr, info_ptr->text[i].key,
335 info_ptr->text[i].text,
336 0);
337 /* Mark this chunk as written */
338 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
339#else
340 /* Can't get here */
341 png_warning(png_ptr, "Unable to write uncompressed text");
342#endif
343 }
344 }
345#endif /* tEXt */
346
347#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
348 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE);
349#endif
350}
351
352/* Writes the end of the PNG file. If you don't want to write comments or
353 * time information, you can pass NULL for info. If you already wrote these
354 * in png_write_info(), do not write them again here. If you have long
355 * comments, I suggest writing them here, and compressing them.
356 */
357void PNGAPI
358png_write_end(png_structrp png_ptr, png_inforp info_ptr)
359{
360 png_debug(1, "in png_write_end");
361
362 if (png_ptr == NULL)
363 return;
364
365 if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
366 png_error(png_ptr, "No IDATs written into file");
367
368#ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
369 if (png_ptr->num_palette_max > png_ptr->num_palette)
370 png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
371#endif
372
373 /* See if user wants us to write information chunks */
374 if (info_ptr != NULL)
375 {
376#ifdef PNG_WRITE_TEXT_SUPPORTED
377 int i; /* local index variable */
378#endif
379#ifdef PNG_WRITE_tIME_SUPPORTED
380 /* Check to see if user has supplied a time chunk */
381 if ((info_ptr->valid & PNG_INFO_tIME) != 0 &&
382 (png_ptr->mode & PNG_WROTE_tIME) == 0)
383 png_write_tIME(png_ptr, &(info_ptr->mod_time));
384
385#endif
386#ifdef PNG_WRITE_TEXT_SUPPORTED
387 /* Loop through comment chunks */
388 for (i = 0; i < info_ptr->num_text; i++)
389 {
390 png_debug2(2, "Writing trailer text chunk %d, type %d", i,
391 info_ptr->text[i].compression);
392 /* An internationalized chunk? */
393 if (info_ptr->text[i].compression > 0)
394 {
395#ifdef PNG_WRITE_iTXt_SUPPORTED
396 /* Write international chunk */
397 png_write_iTXt(png_ptr,
398 info_ptr->text[i].compression,
399 info_ptr->text[i].key,
400 info_ptr->text[i].lang,
401 info_ptr->text[i].lang_key,
402 info_ptr->text[i].text);
403 /* Mark this chunk as written */
404 if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
405 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
406 else
407 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
408#else
409 png_warning(png_ptr, "Unable to write international text");
410#endif
411 }
412
413 else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
414 {
415#ifdef PNG_WRITE_zTXt_SUPPORTED
416 /* Write compressed chunk */
417 png_write_zTXt(png_ptr, info_ptr->text[i].key,
418 info_ptr->text[i].text, info_ptr->text[i].compression);
419 /* Mark this chunk as written */
420 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
421#else
422 png_warning(png_ptr, "Unable to write compressed text");
423#endif
424 }
425
426 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
427 {
428#ifdef PNG_WRITE_tEXt_SUPPORTED
429 /* Write uncompressed chunk */
430 png_write_tEXt(png_ptr, info_ptr->text[i].key,
431 info_ptr->text[i].text, 0);
432 /* Mark this chunk as written */
433 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
434#else
435 png_warning(png_ptr, "Unable to write uncompressed text");
436#endif
437 }
438 }
439#endif
440
441#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
442 write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT);
443#endif
444 }
445
446 png_ptr->mode |= PNG_AFTER_IDAT;
447
448 /* Write end of PNG file */
449 png_write_IEND(png_ptr);
450
451 /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03,
452 * and restored again in libpng-1.2.30, may cause some applications that
453 * do not set png_ptr->output_flush_fn to crash. If your application
454 * experiences a problem, please try building libpng with
455 * PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED defined, and report the event to
456 * png-mng-implement at lists.sf.net .
457 */
458#ifdef PNG_WRITE_FLUSH_SUPPORTED
459# ifdef PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED
460 png_flush(png_ptr);
461# endif
462#endif
463}
464
465#ifdef PNG_CONVERT_tIME_SUPPORTED
466void PNGAPI
467png_convert_from_struct_tm(png_timep ptime, const struct tm * ttime)
468{
469 png_debug(1, "in png_convert_from_struct_tm");
470
471 ptime->year = (png_uint_16)(1900 + ttime->tm_year);
472 ptime->month = (png_byte)(ttime->tm_mon + 1);
473 ptime->day = (png_byte)ttime->tm_mday;
474 ptime->hour = (png_byte)ttime->tm_hour;
475 ptime->minute = (png_byte)ttime->tm_min;
476 ptime->second = (png_byte)ttime->tm_sec;
477}
478
479void PNGAPI
480png_convert_from_time_t(png_timep ptime, time_t ttime)
481{
482 struct tm *tbuf;
483
484 png_debug(1, "in png_convert_from_time_t");
485
486 tbuf = gmtime(&ttime);
487 png_convert_from_struct_tm(ptime, tbuf);
488}
489#endif
490
491/* Initialize png_ptr structure, and allocate any memory needed */
492PNG_FUNCTION(png_structp,PNGAPI
493png_create_write_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
494 png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
495{
496#ifndef PNG_USER_MEM_SUPPORTED
497 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
498 error_fn, warn_fn, NULL, NULL, NULL);
499#else
500 return png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
501 warn_fn, NULL, NULL, NULL);
502}
503
504/* Alternate initialize png_ptr structure, and allocate any memory needed */
505PNG_FUNCTION(png_structp,PNGAPI
506png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
507 png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
508 png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
509{
510 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
511 error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
512#endif /* USER_MEM */
513 if (png_ptr != NULL)
514 {
515 /* Set the zlib control values to defaults; they can be overridden by the
516 * application after the struct has been created.
517 */
518 png_ptr->zbuffer_size = PNG_ZBUF_SIZE;
519
520 /* The 'zlib_strategy' setting is irrelevant because png_default_claim in
521 * pngwutil.c defaults it according to whether or not filters will be
522 * used, and ignores this setting.
523 */
524 png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY;
525 png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION;
526 png_ptr->zlib_mem_level = 8;
527 png_ptr->zlib_window_bits = 15;
528 png_ptr->zlib_method = 8;
529
530#ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
531 png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY;
532 png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION;
533 png_ptr->zlib_text_mem_level = 8;
534 png_ptr->zlib_text_window_bits = 15;
535 png_ptr->zlib_text_method = 8;
536#endif /* WRITE_COMPRESSED_TEXT */
537
538 /* This is a highly dubious configuration option; by default it is off,
539 * but it may be appropriate for private builds that are testing
540 * extensions not conformant to the current specification, or of
541 * applications that must not fail to write at all costs!
542 */
543#ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED
544 /* In stable builds only warn if an application error can be completely
545 * handled.
546 */
547 png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
548#endif
549
550 /* App warnings are warnings in release (or release candidate) builds but
551 * are errors during development.
552 */
553#if PNG_RELEASE_BUILD
554 png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
555#endif
556
557 /* TODO: delay this, it can be done in png_init_io() (if the app doesn't
558 * do it itself) avoiding setting the default function if it is not
559 * required.
560 */
561 png_set_write_fn(png_ptr, NULL, NULL, NULL);
562 }
563
564 return png_ptr;
565}
566
567
568/* Write a few rows of image data. If the image is interlaced,
569 * either you will have to write the 7 sub images, or, if you
570 * have called png_set_interlace_handling(), you will have to
571 * "write" the image seven times.
572 */
573void PNGAPI
574png_write_rows(png_structrp png_ptr, png_bytepp row,
575 png_uint_32 num_rows)
576{
577 png_uint_32 i; /* row counter */
578 png_bytepp rp; /* row pointer */
579
580 png_debug(1, "in png_write_rows");
581
582 if (png_ptr == NULL)
583 return;
584
585 /* Loop through the rows */
586 for (i = 0, rp = row; i < num_rows; i++, rp++)
587 {
588 png_write_row(png_ptr, *rp);
589 }
590}
591
592/* Write the image. You only need to call this function once, even
593 * if you are writing an interlaced image.
594 */
595void PNGAPI
596png_write_image(png_structrp png_ptr, png_bytepp image)
597{
598 png_uint_32 i; /* row index */
599 int pass, num_pass; /* pass variables */
600 png_bytepp rp; /* points to current row */
601
602 if (png_ptr == NULL)
603 return;
604
605 png_debug(1, "in png_write_image");
606
607#ifdef PNG_WRITE_INTERLACING_SUPPORTED
608 /* Initialize interlace handling. If image is not interlaced,
609 * this will set pass to 1
610 */
611 num_pass = png_set_interlace_handling(png_ptr);
612#else
613 num_pass = 1;
614#endif
615 /* Loop through passes */
616 for (pass = 0; pass < num_pass; pass++)
617 {
618 /* Loop through image */
619 for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
620 {
621 png_write_row(png_ptr, *rp);
622 }
623 }
624}
625
626#ifdef PNG_MNG_FEATURES_SUPPORTED
627/* Performs intrapixel differencing */
628static void
629png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
630{
631 png_debug(1, "in png_do_write_intrapixel");
632
633 if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
634 {
635 int bytes_per_pixel;
636 png_uint_32 row_width = row_info->width;
637 if (row_info->bit_depth == 8)
638 {
639 png_bytep rp;
640 png_uint_32 i;
641
642 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
643 bytes_per_pixel = 3;
644
645 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
646 bytes_per_pixel = 4;
647
648 else
649 return;
650
651 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
652 {
653 *(rp) = (png_byte)(*rp - *(rp + 1));
654 *(rp + 2) = (png_byte)(*(rp + 2) - *(rp + 1));
655 }
656 }
657
658#ifdef PNG_WRITE_16BIT_SUPPORTED
659 else if (row_info->bit_depth == 16)
660 {
661 png_bytep rp;
662 png_uint_32 i;
663
664 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
665 bytes_per_pixel = 6;
666
667 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
668 bytes_per_pixel = 8;
669
670 else
671 return;
672
673 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
674 {
675 png_uint_32 s0 = (png_uint_32)(*(rp ) << 8) | *(rp + 1);
676 png_uint_32 s1 = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
677 png_uint_32 s2 = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
678 png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL);
679 png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
680 *(rp ) = (png_byte)(red >> 8);
681 *(rp + 1) = (png_byte)red;
682 *(rp + 4) = (png_byte)(blue >> 8);
683 *(rp + 5) = (png_byte)blue;
684 }
685 }
686#endif /* WRITE_16BIT */
687 }
688}
689#endif /* MNG_FEATURES */
690
691/* Called by user to write a row of image data */
692void PNGAPI
693png_write_row(png_structrp png_ptr, png_const_bytep row)
694{
695 /* 1.5.6: moved from png_struct to be a local structure: */
696 png_row_info row_info;
697
698 if (png_ptr == NULL)
699 return;
700
701 png_debug2(1, "in png_write_row (row %u, pass %d)",
702 png_ptr->row_number, png_ptr->pass);
703
704 /* Initialize transformations and other stuff if first time */
705 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
706 {
707 /* Make sure we wrote the header info */
708 if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
709 png_error(png_ptr,
710 "png_write_info was never called before png_write_row");
711
712 /* Check for transforms that have been set but were defined out */
713#if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
714 if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
715 png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined");
716#endif
717
718#if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
719 if ((png_ptr->transformations & PNG_FILLER) != 0)
720 png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined");
721#endif
722#if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
723 defined(PNG_READ_PACKSWAP_SUPPORTED)
724 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
725 png_warning(png_ptr,
726 "PNG_WRITE_PACKSWAP_SUPPORTED is not defined");
727#endif
728
729#if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
730 if ((png_ptr->transformations & PNG_PACK) != 0)
731 png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined");
732#endif
733
734#if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
735 if ((png_ptr->transformations & PNG_SHIFT) != 0)
736 png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined");
737#endif
738
739#if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
740 if ((png_ptr->transformations & PNG_BGR) != 0)
741 png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined");
742#endif
743
744#if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
745 if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
746 png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined");
747#endif
748
749 png_write_start_row(png_ptr);
750 }
751
752#ifdef PNG_WRITE_INTERLACING_SUPPORTED
753 /* If interlaced and not interested in row, return */
754 if (png_ptr->interlaced != 0 &&
755 (png_ptr->transformations & PNG_INTERLACE) != 0)
756 {
757 switch (png_ptr->pass)
758 {
759 case 0:
760 if ((png_ptr->row_number & 0x07) != 0)
761 {
762 png_write_finish_row(png_ptr);
763 return;
764 }
765 break;
766
767 case 1:
768 if ((png_ptr->row_number & 0x07) != 0 || png_ptr->width < 5)
769 {
770 png_write_finish_row(png_ptr);
771 return;
772 }
773 break;
774
775 case 2:
776 if ((png_ptr->row_number & 0x07) != 4)
777 {
778 png_write_finish_row(png_ptr);
779 return;
780 }
781 break;
782
783 case 3:
784 if ((png_ptr->row_number & 0x03) != 0 || png_ptr->width < 3)
785 {
786 png_write_finish_row(png_ptr);
787 return;
788 }
789 break;
790
791 case 4:
792 if ((png_ptr->row_number & 0x03) != 2)
793 {
794 png_write_finish_row(png_ptr);
795 return;
796 }
797 break;
798
799 case 5:
800 if ((png_ptr->row_number & 0x01) != 0 || png_ptr->width < 2)
801 {
802 png_write_finish_row(png_ptr);
803 return;
804 }
805 break;
806
807 case 6:
808 if ((png_ptr->row_number & 0x01) == 0)
809 {
810 png_write_finish_row(png_ptr);
811 return;
812 }
813 break;
814
815 default: /* error: ignore it */
816 break;
817 }
818 }
819#endif
820
821 /* Set up row info for transformations */
822 row_info.color_type = png_ptr->color_type;
823 row_info.width = png_ptr->usr_width;
824 row_info.channels = png_ptr->usr_channels;
825 row_info.bit_depth = png_ptr->usr_bit_depth;
826 row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels);
827 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
828
829 png_debug1(3, "row_info->color_type = %d", row_info.color_type);
830 png_debug1(3, "row_info->width = %u", row_info.width);
831 png_debug1(3, "row_info->channels = %d", row_info.channels);
832 png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth);
833 png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth);
834 png_debug1(3, "row_info->rowbytes = %lu", (unsigned long)row_info.rowbytes);
835
836 /* Copy user's row into buffer, leaving room for filter byte. */
837 memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes);
838
839#ifdef PNG_WRITE_INTERLACING_SUPPORTED
840 /* Handle interlacing */
841 if (png_ptr->interlaced && png_ptr->pass < 6 &&
842 (png_ptr->transformations & PNG_INTERLACE) != 0)
843 {
844 png_do_write_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass);
845 /* This should always get caught above, but still ... */
846 if (row_info.width == 0)
847 {
848 png_write_finish_row(png_ptr);
849 return;
850 }
851 }
852#endif
853
854#ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
855 /* Handle other transformations */
856 if (png_ptr->transformations != 0)
857 png_do_write_transformations(png_ptr, &row_info);
858#endif
859
860 /* At this point the row_info pixel depth must match the 'transformed' depth,
861 * which is also the output depth.
862 */
863 if (row_info.pixel_depth != png_ptr->pixel_depth ||
864 row_info.pixel_depth != png_ptr->transformed_pixel_depth)
865 png_error(png_ptr, "internal write transform logic error");
866
867#ifdef PNG_MNG_FEATURES_SUPPORTED
868 /* Write filter_method 64 (intrapixel differencing) only if
869 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
870 * 2. Libpng did not write a PNG signature (this filter_method is only
871 * used in PNG datastreams that are embedded in MNG datastreams) and
872 * 3. The application called png_permit_mng_features with a mask that
873 * included PNG_FLAG_MNG_FILTER_64 and
874 * 4. The filter_method is 64 and
875 * 5. The color_type is RGB or RGBA
876 */
877 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
878 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
879 {
880 /* Intrapixel differencing */
881 png_do_write_intrapixel(&row_info, png_ptr->row_buf + 1);
882 }
883#endif
884
885/* Added at libpng-1.5.10 */
886#ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
887 /* Check for out-of-range palette index */
888 if (row_info.color_type == PNG_COLOR_TYPE_PALETTE &&
889 png_ptr->num_palette_max >= 0)
890 png_do_check_palette_indexes(png_ptr, &row_info);
891#endif
892
893 /* Find a filter if necessary, filter the row and write it out. */
894 png_write_find_filter(png_ptr, &row_info);
895
896 if (png_ptr->write_row_fn != NULL)
897 (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
898}
899
900#ifdef PNG_WRITE_FLUSH_SUPPORTED
901/* Set the automatic flush interval or 0 to turn flushing off */
902void PNGAPI
903png_set_flush(png_structrp png_ptr, int nrows)
904{
905 png_debug(1, "in png_set_flush");
906
907 if (png_ptr == NULL)
908 return;
909
910 png_ptr->flush_dist = (nrows < 0 ? 0 : (png_uint_32)nrows);
911}
912
913/* Flush the current output buffers now */
914void PNGAPI
915png_write_flush(png_structrp png_ptr)
916{
917 png_debug(1, "in png_write_flush");
918
919 if (png_ptr == NULL)
920 return;
921
922 /* We have already written out all of the data */
923 if (png_ptr->row_number >= png_ptr->num_rows)
924 return;
925
926 png_compress_IDAT(png_ptr, NULL, 0, Z_SYNC_FLUSH);
927 png_ptr->flush_rows = 0;
928 png_flush(png_ptr);
929}
930#endif /* WRITE_FLUSH */
931
932/* Free any memory used in png_ptr struct without freeing the struct itself. */
933static void
934png_write_destroy(png_structrp png_ptr)
935{
936 png_debug(1, "in png_write_destroy");
937
938 /* Free any memory zlib uses */
939 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
940 deflateEnd(&png_ptr->zstream);
941
942 /* Free our memory. png_free checks NULL for us. */
943 png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
944 png_free(png_ptr, png_ptr->row_buf);
945 png_ptr->row_buf = NULL;
946#ifdef PNG_WRITE_FILTER_SUPPORTED
947 png_free(png_ptr, png_ptr->prev_row);
948 png_free(png_ptr, png_ptr->try_row);
949 png_free(png_ptr, png_ptr->tst_row);
950 png_ptr->prev_row = NULL;
951 png_ptr->try_row = NULL;
952 png_ptr->tst_row = NULL;
953#endif
954
955#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
956 png_free(png_ptr, png_ptr->chunk_list);
957 png_ptr->chunk_list = NULL;
958#endif
959
960 /* The error handling and memory handling information is left intact at this
961 * point: the jmp_buf may still have to be freed. See png_destroy_png_struct
962 * for how this happens.
963 */
964}
965
966/* Free all memory used by the write.
967 * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for
968 * *png_ptr_ptr. Prior to 1.6.0 it would accept such a value and it would free
969 * the passed in info_structs but it would quietly fail to free any of the data
970 * inside them. In 1.6.0 it quietly does nothing (it has to be quiet because it
971 * has no png_ptr.)
972 */
973void PNGAPI
974png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
975{
976 png_debug(1, "in png_destroy_write_struct");
977
978 if (png_ptr_ptr != NULL)
979 {
980 png_structrp png_ptr = *png_ptr_ptr;
981
982 if (png_ptr != NULL) /* added in libpng 1.6.0 */
983 {
984 png_destroy_info_struct(png_ptr, info_ptr_ptr);
985
986 *png_ptr_ptr = NULL;
987 png_write_destroy(png_ptr);
988 png_destroy_png_struct(png_ptr);
989 }
990 }
991}
992
993/* Allow the application to select one or more row filters to use. */
994void PNGAPI
995png_set_filter(png_structrp png_ptr, int method, int filters)
996{
997 png_debug(1, "in png_set_filter");
998
999 if (png_ptr == NULL)
1000 return;
1001
1002#ifdef PNG_MNG_FEATURES_SUPPORTED
1003 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
1004 (method == PNG_INTRAPIXEL_DIFFERENCING))
1005 method = PNG_FILTER_TYPE_BASE;
1006
1007#endif
1008 if (method == PNG_FILTER_TYPE_BASE)
1009 {
1010 switch (filters & (PNG_ALL_FILTERS | 0x07))
1011 {
1012#ifdef PNG_WRITE_FILTER_SUPPORTED
1013 case 5:
1014 case 6:
1015 case 7: png_app_error(png_ptr, "Unknown row filter for method 0");
1016#endif /* WRITE_FILTER */
1017 /* FALLTHROUGH */
1018 case PNG_FILTER_VALUE_NONE:
1019 png_ptr->do_filter = PNG_FILTER_NONE; break;
1020
1021#ifdef PNG_WRITE_FILTER_SUPPORTED
1022 case PNG_FILTER_VALUE_SUB:
1023 png_ptr->do_filter = PNG_FILTER_SUB; break;
1024
1025 case PNG_FILTER_VALUE_UP:
1026 png_ptr->do_filter = PNG_FILTER_UP; break;
1027
1028 case PNG_FILTER_VALUE_AVG:
1029 png_ptr->do_filter = PNG_FILTER_AVG; break;
1030
1031 case PNG_FILTER_VALUE_PAETH:
1032 png_ptr->do_filter = PNG_FILTER_PAETH; break;
1033
1034 default:
1035 png_ptr->do_filter = (png_byte)filters; break;
1036#else
1037 default:
1038 png_app_error(png_ptr, "Unknown row filter for method 0");
1039#endif /* WRITE_FILTER */
1040 }
1041
1042#ifdef PNG_WRITE_FILTER_SUPPORTED
1043 /* If we have allocated the row_buf, this means we have already started
1044 * with the image and we should have allocated all of the filter buffers
1045 * that have been selected. If prev_row isn't already allocated, then
1046 * it is too late to start using the filters that need it, since we
1047 * will be missing the data in the previous row. If an application
1048 * wants to start and stop using particular filters during compression,
1049 * it should start out with all of the filters, and then remove them
1050 * or add them back after the start of compression.
1051 *
1052 * NOTE: this is a nasty constraint on the code, because it means that the
1053 * prev_row buffer must be maintained even if there are currently no
1054 * 'prev_row' requiring filters active.
1055 */
1056 if (png_ptr->row_buf != NULL)
1057 {
1058 int num_filters;
1059 png_alloc_size_t buf_size;
1060
1061 /* Repeat the checks in png_write_start_row; 1 pixel high or wide
1062 * images cannot benefit from certain filters. If this isn't done here
1063 * the check below will fire on 1 pixel high images.
1064 */
1065 if (png_ptr->height == 1)
1066 filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1067
1068 if (png_ptr->width == 1)
1069 filters &= ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1070
1071 if ((filters & (PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)) != 0
1072 && png_ptr->prev_row == NULL)
1073 {
1074 /* This is the error case, however it is benign - the previous row
1075 * is not available so the filter can't be used. Just warn here.
1076 */
1077 png_app_warning(png_ptr,
1078 "png_set_filter: UP/AVG/PAETH cannot be added after start");
1079 filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1080 }
1081
1082 num_filters = 0;
1083
1084 if (filters & PNG_FILTER_SUB)
1085 num_filters++;
1086
1087 if (filters & PNG_FILTER_UP)
1088 num_filters++;
1089
1090 if (filters & PNG_FILTER_AVG)
1091 num_filters++;
1092
1093 if (filters & PNG_FILTER_PAETH)
1094 num_filters++;
1095
1096 /* Allocate needed row buffers if they have not already been
1097 * allocated.
1098 */
1099 buf_size = PNG_ROWBYTES(png_ptr->usr_channels * png_ptr->usr_bit_depth,
1100 png_ptr->width) + 1;
1101
1102 if (png_ptr->try_row == NULL)
1103 png_ptr->try_row = png_voidcast(png_bytep,
1104 png_malloc(png_ptr, buf_size));
1105
1106 if (num_filters > 1)
1107 {
1108 if (png_ptr->tst_row == NULL)
1109 png_ptr->tst_row = png_voidcast(png_bytep,
1110 png_malloc(png_ptr, buf_size));
1111 }
1112 }
1113 png_ptr->do_filter = (png_byte)filters;
1114#endif
1115 }
1116 else
1117 png_error(png_ptr, "Unknown custom filter method");
1118}
1119
1120#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */
1121/* Provide floating and fixed point APIs */
1122#ifdef PNG_FLOATING_POINT_SUPPORTED
1123void PNGAPI
1124png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method,
1125 int num_weights, png_const_doublep filter_weights,
1126 png_const_doublep filter_costs)
1127{
1128 PNG_UNUSED(png_ptr)
1129 PNG_UNUSED(heuristic_method)
1130 PNG_UNUSED(num_weights)
1131 PNG_UNUSED(filter_weights)
1132 PNG_UNUSED(filter_costs)
1133}
1134#endif /* FLOATING_POINT */
1135
1136#ifdef PNG_FIXED_POINT_SUPPORTED
1137void PNGAPI
1138png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method,
1139 int num_weights, png_const_fixed_point_p filter_weights,
1140 png_const_fixed_point_p filter_costs)
1141{
1142 PNG_UNUSED(png_ptr)
1143 PNG_UNUSED(heuristic_method)
1144 PNG_UNUSED(num_weights)
1145 PNG_UNUSED(filter_weights)
1146 PNG_UNUSED(filter_costs)
1147}
1148#endif /* FIXED_POINT */
1149#endif /* WRITE_WEIGHTED_FILTER */
1150
1151#ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
1152void PNGAPI
1153png_set_compression_level(png_structrp png_ptr, int level)
1154{
1155 png_debug(1, "in png_set_compression_level");
1156
1157 if (png_ptr == NULL)
1158 return;
1159
1160 png_ptr->zlib_level = level;
1161}
1162
1163void PNGAPI
1164png_set_compression_mem_level(png_structrp png_ptr, int mem_level)
1165{
1166 png_debug(1, "in png_set_compression_mem_level");
1167
1168 if (png_ptr == NULL)
1169 return;
1170
1171 png_ptr->zlib_mem_level = mem_level;
1172}
1173
1174void PNGAPI
1175png_set_compression_strategy(png_structrp png_ptr, int strategy)
1176{
1177 png_debug(1, "in png_set_compression_strategy");
1178
1179 if (png_ptr == NULL)
1180 return;
1181
1182 /* The flag setting here prevents the libpng dynamic selection of strategy.
1183 */
1184 png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
1185 png_ptr->zlib_strategy = strategy;
1186}
1187
1188/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1189 * smaller value of window_bits if it can do so safely.
1190 */
1191void PNGAPI
1192png_set_compression_window_bits(png_structrp png_ptr, int window_bits)
1193{
1194 if (png_ptr == NULL)
1195 return;
1196
1197 /* Prior to 1.6.0 this would warn but then set the window_bits value. This
1198 * meant that negative window bits values could be selected that would cause
1199 * libpng to write a non-standard PNG file with raw deflate or gzip
1200 * compressed IDAT or ancillary chunks. Such files can be read and there is
1201 * no warning on read, so this seems like a very bad idea.
1202 */
1203 if (window_bits > 15)
1204 {
1205 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1206 window_bits = 15;
1207 }
1208
1209 else if (window_bits < 8)
1210 {
1211 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1212 window_bits = 8;
1213 }
1214
1215 png_ptr->zlib_window_bits = window_bits;
1216}
1217
1218void PNGAPI
1219png_set_compression_method(png_structrp png_ptr, int method)
1220{
1221 png_debug(1, "in png_set_compression_method");
1222
1223 if (png_ptr == NULL)
1224 return;
1225
1226 /* This would produce an invalid PNG file if it worked, but it doesn't and
1227 * deflate will fault it, so it is harmless to just warn here.
1228 */
1229 if (method != 8)
1230 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1231
1232 png_ptr->zlib_method = method;
1233}
1234#endif /* WRITE_CUSTOMIZE_COMPRESSION */
1235
1236/* The following were added to libpng-1.5.4 */
1237#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
1238void PNGAPI
1239png_set_text_compression_level(png_structrp png_ptr, int level)
1240{
1241 png_debug(1, "in png_set_text_compression_level");
1242
1243 if (png_ptr == NULL)
1244 return;
1245
1246 png_ptr->zlib_text_level = level;
1247}
1248
1249void PNGAPI
1250png_set_text_compression_mem_level(png_structrp png_ptr, int mem_level)
1251{
1252 png_debug(1, "in png_set_text_compression_mem_level");
1253
1254 if (png_ptr == NULL)
1255 return;
1256
1257 png_ptr->zlib_text_mem_level = mem_level;
1258}
1259
1260void PNGAPI
1261png_set_text_compression_strategy(png_structrp png_ptr, int strategy)
1262{
1263 png_debug(1, "in png_set_text_compression_strategy");
1264
1265 if (png_ptr == NULL)
1266 return;
1267
1268 png_ptr->zlib_text_strategy = strategy;
1269}
1270
1271/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1272 * smaller value of window_bits if it can do so safely.
1273 */
1274void PNGAPI
1275png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits)
1276{
1277 if (png_ptr == NULL)
1278 return;
1279
1280 if (window_bits > 15)
1281 {
1282 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1283 window_bits = 15;
1284 }
1285
1286 else if (window_bits < 8)
1287 {
1288 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1289 window_bits = 8;
1290 }
1291
1292 png_ptr->zlib_text_window_bits = window_bits;
1293}
1294
1295void PNGAPI
1296png_set_text_compression_method(png_structrp png_ptr, int method)
1297{
1298 png_debug(1, "in png_set_text_compression_method");
1299
1300 if (png_ptr == NULL)
1301 return;
1302
1303 if (method != 8)
1304 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1305
1306 png_ptr->zlib_text_method = method;
1307}
1308#endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */
1309/* end of API added to libpng-1.5.4 */
1310
1311void PNGAPI
1312png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn)
1313{
1314 if (png_ptr == NULL)
1315 return;
1316
1317 png_ptr->write_row_fn = write_row_fn;
1318}
1319
1320#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
1321void PNGAPI
1322png_set_write_user_transform_fn(png_structrp png_ptr, png_user_transform_ptr
1323 write_user_transform_fn)
1324{
1325 png_debug(1, "in png_set_write_user_transform_fn");
1326
1327 if (png_ptr == NULL)
1328 return;
1329
1330 png_ptr->transformations |= PNG_USER_TRANSFORM;
1331 png_ptr->write_user_transform_fn = write_user_transform_fn;
1332}
1333#endif
1334
1335
1336#ifdef PNG_INFO_IMAGE_SUPPORTED
1337void PNGAPI
1338png_write_png(png_structrp png_ptr, png_inforp info_ptr,
1339 int transforms, voidp params)
1340{
1341 if (png_ptr == NULL || info_ptr == NULL)
1342 return;
1343
1344 if ((info_ptr->valid & PNG_INFO_IDAT) == 0)
1345 {
1346 png_app_error(png_ptr, "no rows for png_write_image to write");
1347 return;
1348 }
1349
1350 /* Write the file header information. */
1351 png_write_info(png_ptr, info_ptr);
1352
1353 /* ------ these transformations don't touch the info structure ------- */
1354
1355 /* Invert monochrome pixels */
1356 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1357#ifdef PNG_WRITE_INVERT_SUPPORTED
1358 png_set_invert_mono(png_ptr);
1359#else
1360 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1361#endif
1362
1363 /* Shift the pixels up to a legal bit depth and fill in
1364 * as appropriate to correctly scale the image.
1365 */
1366 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1367#ifdef PNG_WRITE_SHIFT_SUPPORTED
1368 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1369 png_set_shift(png_ptr, &info_ptr->sig_bit);
1370#else
1371 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1372#endif
1373
1374 /* Pack pixels into bytes */
1375 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1376#ifdef PNG_WRITE_PACK_SUPPORTED
1377 png_set_packing(png_ptr);
1378#else
1379 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1380#endif
1381
1382 /* Swap location of alpha bytes from ARGB to RGBA */
1383 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1384#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
1385 png_set_swap_alpha(png_ptr);
1386#else
1387 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1388#endif
1389
1390 /* Remove a filler (X) from XRGB/RGBX/AG/GA into to convert it into
1391 * RGB, note that the code expects the input color type to be G or RGB; no
1392 * alpha channel.
1393 */
1394 if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER|
1395 PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
1396 {
1397#ifdef PNG_WRITE_FILLER_SUPPORTED
1398 if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0)
1399 {
1400 if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1401 png_app_error(png_ptr,
1402 "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
1403
1404 /* Continue if ignored - this is the pre-1.6.10 behavior */
1405 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
1406 }
1407
1408 else if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1409 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1410#else
1411 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_FILLER not supported");
1412#endif
1413 }
1414
1415 /* Flip BGR pixels to RGB */
1416 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1417#ifdef PNG_WRITE_BGR_SUPPORTED
1418 png_set_bgr(png_ptr);
1419#else
1420 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1421#endif
1422
1423 /* Swap bytes of 16-bit files to most significant byte first */
1424 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1425#ifdef PNG_WRITE_SWAP_SUPPORTED
1426 png_set_swap(png_ptr);
1427#else
1428 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1429#endif
1430
1431 /* Swap bits of 1-bit, 2-bit, 4-bit packed pixel formats */
1432 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1433#ifdef PNG_WRITE_PACKSWAP_SUPPORTED
1434 png_set_packswap(png_ptr);
1435#else
1436 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1437#endif
1438
1439 /* Invert the alpha channel from opacity to transparency */
1440 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1441#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
1442 png_set_invert_alpha(png_ptr);
1443#else
1444 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1445#endif
1446
1447 /* ----------------------- end of transformations ------------------- */
1448
1449 /* Write the bits */
1450 png_write_image(png_ptr, info_ptr->row_pointers);
1451
1452 /* It is REQUIRED to call this to finish writing the rest of the file */
1453 png_write_end(png_ptr, info_ptr);
1454
1455 PNG_UNUSED(params)
1456}
1457#endif
1458
1459
1460#ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
1461/* Initialize the write structure - general purpose utility. */
1462static int
1463png_image_write_init(png_imagep image)
1464{
1465 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
1466 png_safe_error, png_safe_warning);
1467
1468 if (png_ptr != NULL)
1469 {
1470 png_infop info_ptr = png_create_info_struct(png_ptr);
1471
1472 if (info_ptr != NULL)
1473 {
1474 png_controlp control = png_voidcast(png_controlp,
1475 png_malloc_warn(png_ptr, (sizeof *control)));
1476
1477 if (control != NULL)
1478 {
1479 memset(control, 0, (sizeof *control));
1480
1481 control->png_ptr = png_ptr;
1482 control->info_ptr = info_ptr;
1483 control->for_write = 1;
1484
1485 image->opaque = control;
1486 return 1;
1487 }
1488
1489 /* Error clean up */
1490 png_destroy_info_struct(png_ptr, &info_ptr);
1491 }
1492
1493 png_destroy_write_struct(&png_ptr, NULL);
1494 }
1495
1496 return png_image_error(image, "png_image_write_: out of memory");
1497}
1498
1499/* Arguments to png_image_write_main: */
1500typedef struct
1501{
1502 /* Arguments: */
1503 png_imagep image;
1504 png_const_voidp buffer;
1505 png_int_32 row_stride;
1506 png_const_voidp colormap;
1507 int convert_to_8bit;
1508 /* Local variables: */
1509 png_const_voidp first_row;
1510 ptrdiff_t row_bytes;
1511 png_voidp local_row;
1512 /* Byte count for memory writing */
1513 png_bytep memory;
1514 png_alloc_size_t memory_bytes; /* not used for STDIO */
1515 png_alloc_size_t output_bytes; /* running total */
1516} png_image_write_control;
1517
1518/* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
1519 * do any necessary byte swapping. The component order is defined by the
1520 * png_image format value.
1521 */
1522static int
1523png_write_image_16bit(png_voidp argument)
1524{
1525 png_image_write_control *display = png_voidcast(png_image_write_control*,
1526 argument);
1527 png_imagep image = display->image;
1528 png_structrp png_ptr = image->opaque->png_ptr;
1529
1530 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1531 display->first_row);
1532 png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row);
1533 png_uint_16p row_end;
1534 unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1535 3 : 1;
1536 int aindex = 0;
1537 png_uint_32 y = image->height;
1538
1539 if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1540 {
1541# ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1542 if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1543 {
1544 aindex = -1;
1545 ++input_row; /* To point to the first component */
1546 ++output_row;
1547 }
1548 else
1549 aindex = (int)channels;
1550# else
1551 aindex = (int)channels;
1552# endif
1553 }
1554
1555 else
1556 png_error(png_ptr, "png_write_image: internal call error");
1557
1558 /* Work out the output row end and count over this, note that the increment
1559 * above to 'row' means that row_end can actually be beyond the end of the
1560 * row; this is correct.
1561 */
1562 row_end = output_row + image->width * (channels+1);
1563
1564 for (; y > 0; --y)
1565 {
1566 png_const_uint_16p in_ptr = input_row;
1567 png_uint_16p out_ptr = output_row;
1568
1569 while (out_ptr < row_end)
1570 {
1571 png_uint_16 alpha = in_ptr[aindex];
1572 png_uint_32 reciprocal = 0;
1573 int c;
1574
1575 out_ptr[aindex] = alpha;
1576
1577 /* Calculate a reciprocal. The correct calculation is simply
1578 * component/alpha*65535 << 15. (I.e. 15 bits of precision); this
1579 * allows correct rounding by adding .5 before the shift. 'reciprocal'
1580 * is only initialized when required.
1581 */
1582 if (alpha > 0 && alpha < 65535)
1583 reciprocal = ((0xffff<<15)+(alpha>>1))/alpha;
1584
1585 c = (int)channels;
1586 do /* always at least one channel */
1587 {
1588 png_uint_16 component = *in_ptr++;
1589
1590 /* The following gives 65535 for an alpha of 0, which is fine,
1591 * otherwise if 0/0 is represented as some other value there is more
1592 * likely to be a discontinuity which will probably damage
1593 * compression when moving from a fully transparent area to a
1594 * nearly transparent one. (The assumption here is that opaque
1595 * areas tend not to be 0 intensity.)
1596 */
1597 if (component >= alpha)
1598 component = 65535;
1599
1600 /* component<alpha, so component/alpha is less than one and
1601 * component*reciprocal is less than 2^31.
1602 */
1603 else if (component > 0 && alpha < 65535)
1604 {
1605 png_uint_32 calc = component * reciprocal;
1606 calc += 16384; /* round to nearest */
1607 component = (png_uint_16)(calc >> 15);
1608 }
1609
1610 *out_ptr++ = component;
1611 }
1612 while (--c > 0);
1613
1614 /* Skip to next component (skip the intervening alpha channel) */
1615 ++in_ptr;
1616 ++out_ptr;
1617 }
1618
1619 png_write_row(png_ptr, png_voidcast(png_const_bytep, display->local_row));
1620 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1621 }
1622
1623 return 1;
1624}
1625
1626/* Given 16-bit input (1 to 4 channels) write 8-bit output. If an alpha channel
1627 * is present it must be removed from the components, the components are then
1628 * written in sRGB encoding. No components are added or removed.
1629 *
1630 * Calculate an alpha reciprocal to reverse pre-multiplication. As above the
1631 * calculation can be done to 15 bits of accuracy; however, the output needs to
1632 * be scaled in the range 0..255*65535, so include that scaling here.
1633 */
1634# define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+((alpha)>>1))/(alpha))
1635
1636static png_byte
1637png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
1638 png_uint_32 reciprocal/*from the above macro*/)
1639{
1640 /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0
1641 * is represented as some other value there is more likely to be a
1642 * discontinuity which will probably damage compression when moving from a
1643 * fully transparent area to a nearly transparent one. (The assumption here
1644 * is that opaque areas tend not to be 0 intensity.)
1645 *
1646 * There is a rounding problem here; if alpha is less than 128 it will end up
1647 * as 0 when scaled to 8 bits. To avoid introducing spurious colors into the
1648 * output change for this too.
1649 */
1650 if (component >= alpha || alpha < 128)
1651 return 255;
1652
1653 /* component<alpha, so component/alpha is less than one and
1654 * component*reciprocal is less than 2^31.
1655 */
1656 else if (component > 0)
1657 {
1658 /* The test is that alpha/257 (rounded) is less than 255, the first value
1659 * that becomes 255 is 65407.
1660 * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore,
1661 * be exact!) [Could also test reciprocal != 0]
1662 */
1663 if (alpha < 65407)
1664 {
1665 component *= reciprocal;
1666 component += 64; /* round to nearest */
1667 component >>= 7;
1668 }
1669
1670 else
1671 component *= 255;
1672
1673 /* Convert the component to sRGB. */
1674 return (png_byte)PNG_sRGB_FROM_LINEAR(component);
1675 }
1676
1677 else
1678 return 0;
1679}
1680
1681static int
1682png_write_image_8bit(png_voidp argument)
1683{
1684 png_image_write_control *display = png_voidcast(png_image_write_control*,
1685 argument);
1686 png_imagep image = display->image;
1687 png_structrp png_ptr = image->opaque->png_ptr;
1688
1689 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1690 display->first_row);
1691 png_bytep output_row = png_voidcast(png_bytep, display->local_row);
1692 png_uint_32 y = image->height;
1693 unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1694 3 : 1;
1695
1696 if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1697 {
1698 png_bytep row_end;
1699 int aindex;
1700
1701# ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1702 if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1703 {
1704 aindex = -1;
1705 ++input_row; /* To point to the first component */
1706 ++output_row;
1707 }
1708
1709 else
1710# endif
1711 aindex = (int)channels;
1712
1713 /* Use row_end in place of a loop counter: */
1714 row_end = output_row + image->width * (channels+1);
1715
1716 for (; y > 0; --y)
1717 {
1718 png_const_uint_16p in_ptr = input_row;
1719 png_bytep out_ptr = output_row;
1720
1721 while (out_ptr < row_end)
1722 {
1723 png_uint_16 alpha = in_ptr[aindex];
1724 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1725 png_uint_32 reciprocal = 0;
1726 int c;
1727
1728 /* Scale and write the alpha channel. */
1729 out_ptr[aindex] = alphabyte;
1730
1731 if (alphabyte > 0 && alphabyte < 255)
1732 reciprocal = UNP_RECIPROCAL(alpha);
1733
1734 c = (int)channels;
1735 do /* always at least one channel */
1736 *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal);
1737 while (--c > 0);
1738
1739 /* Skip to next component (skip the intervening alpha channel) */
1740 ++in_ptr;
1741 ++out_ptr;
1742 } /* while out_ptr < row_end */
1743
1744 png_write_row(png_ptr, png_voidcast(png_const_bytep,
1745 display->local_row));
1746 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1747 } /* while y */
1748 }
1749
1750 else
1751 {
1752 /* No alpha channel, so the row_end really is the end of the row and it
1753 * is sufficient to loop over the components one by one.
1754 */
1755 png_bytep row_end = output_row + image->width * channels;
1756
1757 for (; y > 0; --y)
1758 {
1759 png_const_uint_16p in_ptr = input_row;
1760 png_bytep out_ptr = output_row;
1761
1762 while (out_ptr < row_end)
1763 {
1764 png_uint_32 component = *in_ptr++;
1765
1766 component *= 255;
1767 *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component);
1768 }
1769
1770 png_write_row(png_ptr, output_row);
1771 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1772 }
1773 }
1774
1775 return 1;
1776}
1777
1778static void
1779png_image_set_PLTE(png_image_write_control *display)
1780{
1781 png_imagep image = display->image;
1782 const void *cmap = display->colormap;
1783 int entries = image->colormap_entries > 256 ? 256 :
1784 (int)image->colormap_entries;
1785
1786 /* NOTE: the caller must check for cmap != NULL and entries != 0 */
1787 png_uint_32 format = image->format;
1788 unsigned int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
1789
1790# if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
1791 defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED)
1792 int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1793 (format & PNG_FORMAT_FLAG_ALPHA) != 0;
1794# else
1795# define afirst 0
1796# endif
1797
1798# ifdef PNG_FORMAT_BGR_SUPPORTED
1799 int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1800# else
1801# define bgr 0
1802# endif
1803
1804 int i, num_trans;
1805 png_color palette[256];
1806 png_byte tRNS[256];
1807
1808 memset(tRNS, 255, (sizeof tRNS));
1809 memset(palette, 0, (sizeof palette));
1810
1811 for (i=num_trans=0; i<entries; ++i)
1812 {
1813 /* This gets automatically converted to sRGB with reversal of the
1814 * pre-multiplication if the color-map has an alpha channel.
1815 */
1816 if ((format & PNG_FORMAT_FLAG_LINEAR) != 0)
1817 {
1818 png_const_uint_16p entry = png_voidcast(png_const_uint_16p, cmap);
1819
1820 entry += (unsigned int)i * channels;
1821
1822 if ((channels & 1) != 0) /* no alpha */
1823 {
1824 if (channels >= 3) /* RGB */
1825 {
1826 palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1827 entry[(2 ^ bgr)]);
1828 palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1829 entry[1]);
1830 palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1831 entry[bgr]);
1832 }
1833
1834 else /* Gray */
1835 palette[i].blue = palette[i].red = palette[i].green =
1836 (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry);
1837 }
1838
1839 else /* alpha */
1840 {
1841 png_uint_16 alpha = entry[afirst ? 0 : channels-1];
1842 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1843 png_uint_32 reciprocal = 0;
1844
1845 /* Calculate a reciprocal, as in the png_write_image_8bit code above
1846 * this is designed to produce a value scaled to 255*65535 when
1847 * divided by 128 (i.e. asr 7).
1848 */
1849 if (alphabyte > 0 && alphabyte < 255)
1850 reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha;
1851
1852 tRNS[i] = alphabyte;
1853 if (alphabyte < 255)
1854 num_trans = i+1;
1855
1856 if (channels >= 3) /* RGB */
1857 {
1858 palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)],
1859 alpha, reciprocal);
1860 palette[i].green = png_unpremultiply(entry[afirst + 1], alpha,
1861 reciprocal);
1862 palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha,
1863 reciprocal);
1864 }
1865
1866 else /* gray */
1867 palette[i].blue = palette[i].red = palette[i].green =
1868 png_unpremultiply(entry[afirst], alpha, reciprocal);
1869 }
1870 }
1871
1872 else /* Color-map has sRGB values */
1873 {
1874 png_const_bytep entry = png_voidcast(png_const_bytep, cmap);
1875
1876 entry += (unsigned int)i * channels;
1877
1878 switch (channels)
1879 {
1880 case 4:
1881 tRNS[i] = entry[afirst ? 0 : 3];
1882 if (tRNS[i] < 255)
1883 num_trans = i+1;
1884 /* FALLTHROUGH */
1885 case 3:
1886 palette[i].blue = entry[afirst + (2 ^ bgr)];
1887 palette[i].green = entry[afirst + 1];
1888 palette[i].red = entry[afirst + bgr];
1889 break;
1890
1891 case 2:
1892 tRNS[i] = entry[1 ^ afirst];
1893 if (tRNS[i] < 255)
1894 num_trans = i+1;
1895 /* FALLTHROUGH */
1896 case 1:
1897 palette[i].blue = palette[i].red = palette[i].green =
1898 entry[afirst];
1899 break;
1900
1901 default:
1902 break;
1903 }
1904 }
1905 }
1906
1907# ifdef afirst
1908# undef afirst
1909# endif
1910# ifdef bgr
1911# undef bgr
1912# endif
1913
1914 png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
1915 entries);
1916
1917 if (num_trans > 0)
1918 png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS,
1919 num_trans, NULL);
1920
1921 image->colormap_entries = (png_uint_32)entries;
1922}
1923
1924static int
1925png_image_write_main(png_voidp argument)
1926{
1927 png_image_write_control *display = png_voidcast(png_image_write_control*,
1928 argument);
1929 png_imagep image = display->image;
1930 png_structrp png_ptr = image->opaque->png_ptr;
1931 png_inforp info_ptr = image->opaque->info_ptr;
1932 png_uint_32 format = image->format;
1933
1934 /* The following four ints are actually booleans */
1935 int colormap = (format & PNG_FORMAT_FLAG_COLORMAP);
1936 int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR); /* input */
1937 int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA);
1938 int write_16bit = linear && (display->convert_to_8bit == 0);
1939
1940# ifdef PNG_BENIGN_ERRORS_SUPPORTED
1941 /* Make sure we error out on any bad situation */
1942 png_set_benign_errors(png_ptr, 0/*error*/);
1943# endif
1944
1945 /* Default the 'row_stride' parameter if required, also check the row stride
1946 * and total image size to ensure that they are within the system limits.
1947 */
1948 {
1949 unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
1950
1951 if (image->width <= 0x7fffffffU/channels) /* no overflow */
1952 {
1953 png_uint_32 check;
1954 png_uint_32 png_row_stride = image->width * channels;
1955
1956 if (display->row_stride == 0)
1957 display->row_stride = (png_int_32)/*SAFE*/png_row_stride;
1958
1959 if (display->row_stride < 0)
1960 check = (png_uint_32)(-display->row_stride);
1961
1962 else
1963 check = (png_uint_32)display->row_stride;
1964
1965 if (check >= png_row_stride)
1966 {
1967 /* Now check for overflow of the image buffer calculation; this
1968 * limits the whole image size to 32 bits for API compatibility with
1969 * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
1970 */
1971 if (image->height > 0xffffffffU/png_row_stride)
1972 png_error(image->opaque->png_ptr, "memory image too large");
1973 }
1974
1975 else
1976 png_error(image->opaque->png_ptr, "supplied row stride too small");
1977 }
1978
1979 else
1980 png_error(image->opaque->png_ptr, "image row stride too large");
1981 }
1982
1983 /* Set the required transforms then write the rows in the correct order. */
1984 if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0)
1985 {
1986 if (display->colormap != NULL && image->colormap_entries > 0)
1987 {
1988 png_uint_32 entries = image->colormap_entries;
1989
1990 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
1991 entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)),
1992 PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
1993 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1994
1995 png_image_set_PLTE(display);
1996 }
1997
1998 else
1999 png_error(image->opaque->png_ptr,
2000 "no color-map for color-mapped image");
2001 }
2002
2003 else
2004 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2005 write_16bit ? 16 : 8,
2006 ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) +
2007 ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0),
2008 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2009
2010 /* Counter-intuitively the data transformations must be called *after*
2011 * png_write_info, not before as in the read code, but the 'set' functions
2012 * must still be called before. Just set the color space information, never
2013 * write an interlaced image.
2014 */
2015
2016 if (write_16bit != 0)
2017 {
2018 /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */
2019 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR);
2020
2021 if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2022 png_set_cHRM_fixed(png_ptr, info_ptr,
2023 /* color x y */
2024 /* white */ 31270, 32900,
2025 /* red */ 64000, 33000,
2026 /* green */ 30000, 60000,
2027 /* blue */ 15000, 6000
2028 );
2029 }
2030
2031 else if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2032 png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);
2033
2034 /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit
2035 * space must still be gamma encoded.
2036 */
2037 else
2038 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE);
2039
2040 /* Write the file header. */
2041 png_write_info(png_ptr, info_ptr);
2042
2043 /* Now set up the data transformations (*after* the header is written),
2044 * remove the handled transformations from the 'format' flags for checking.
2045 *
2046 * First check for a little endian system if writing 16-bit files.
2047 */
2048 if (write_16bit != 0)
2049 {
2050 png_uint_16 le = 0x0001;
2051
2052 if ((*(png_const_bytep) & le) != 0)
2053 png_set_swap(png_ptr);
2054 }
2055
2056# ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
2057 if ((format & PNG_FORMAT_FLAG_BGR) != 0)
2058 {
2059 if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0)
2060 png_set_bgr(png_ptr);
2061 format &= ~PNG_FORMAT_FLAG_BGR;
2062 }
2063# endif
2064
2065# ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
2066 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
2067 {
2068 if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
2069 png_set_swap_alpha(png_ptr);
2070 format &= ~PNG_FORMAT_FLAG_AFIRST;
2071 }
2072# endif
2073
2074 /* If there are 16 or fewer color-map entries we wrote a lower bit depth
2075 * above, but the application data is still byte packed.
2076 */
2077 if (colormap != 0 && image->colormap_entries <= 16)
2078 png_set_packing(png_ptr);
2079
2080 /* That should have handled all (both) the transforms. */
2081 if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR |
2082 PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0)
2083 png_error(png_ptr, "png_write_image: unsupported transformation");
2084
2085 {
2086 png_const_bytep row = png_voidcast(png_const_bytep, display->buffer);
2087 ptrdiff_t row_bytes = display->row_stride;
2088
2089 if (linear != 0)
2090 row_bytes *= (sizeof (png_uint_16));
2091
2092 if (row_bytes < 0)
2093 row += (image->height-1) * (-row_bytes);
2094
2095 display->first_row = row;
2096 display->row_bytes = row_bytes;
2097 }
2098
2099 /* Apply 'fast' options if the flag is set. */
2100 if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0)
2101 {
2102 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS);
2103 /* NOTE: determined by experiment using pngstest, this reflects some
2104 * balance between the time to write the image once and the time to read
2105 * it about 50 times. The speed-up in pngstest was about 10-20% of the
2106 * total (user) time on a heavily loaded system.
2107 */
2108# ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
2109 png_set_compression_level(png_ptr, 3);
2110# endif
2111 }
2112
2113 /* Check for the cases that currently require a pre-transform on the row
2114 * before it is written. This only applies when the input is 16-bit and
2115 * either there is an alpha channel or it is converted to 8-bit.
2116 */
2117 if ((linear != 0 && alpha != 0 ) ||
2118 (colormap == 0 && display->convert_to_8bit != 0))
2119 {
2120 png_bytep row = png_voidcast(png_bytep, png_malloc(png_ptr,
2121 png_get_rowbytes(png_ptr, info_ptr)));
2122 int result;
2123
2124 display->local_row = row;
2125 if (write_16bit != 0)
2126 result = png_safe_execute(image, png_write_image_16bit, display);
2127 else
2128 result = png_safe_execute(image, png_write_image_8bit, display);
2129 display->local_row = NULL;
2130
2131 png_free(png_ptr, row);
2132
2133 /* Skip the 'write_end' on error: */
2134 if (result == 0)
2135 return 0;
2136 }
2137
2138 /* Otherwise this is the case where the input is in a format currently
2139 * supported by the rest of the libpng write code; call it directly.
2140 */
2141 else
2142 {
2143 png_const_bytep row = png_voidcast(png_const_bytep, display->first_row);
2144 ptrdiff_t row_bytes = display->row_bytes;
2145 png_uint_32 y = image->height;
2146
2147 for (; y > 0; --y)
2148 {
2149 png_write_row(png_ptr, row);
2150 row += row_bytes;
2151 }
2152 }
2153
2154 png_write_end(png_ptr, info_ptr);
2155 return 1;
2156}
2157
2158
2159static void (PNGCBAPI
2160image_memory_write)(png_structp png_ptr, png_bytep/*const*/ data, size_t size)
2161{
2162 png_image_write_control *display = png_voidcast(png_image_write_control*,
2163 png_ptr->io_ptr/*backdoor: png_get_io_ptr(png_ptr)*/);
2164 png_alloc_size_t ob = display->output_bytes;
2165
2166 /* Check for overflow; this should never happen: */
2167 if (size <= ((png_alloc_size_t)-1) - ob)
2168 {
2169 /* I don't think libpng ever does this, but just in case: */
2170 if (size > 0)
2171 {
2172 if (display->memory_bytes >= ob+size) /* writing */
2173 memcpy(display->memory+ob, data, size);
2174
2175 /* Always update the size: */
2176 display->output_bytes = ob+size;
2177 }
2178 }
2179
2180 else
2181 png_error(png_ptr, "png_image_write_to_memory: PNG too big");
2182}
2183
2184static void (PNGCBAPI
2185image_memory_flush)(png_structp png_ptr)
2186{
2187 PNG_UNUSED(png_ptr)
2188}
2189
2190static int
2191png_image_write_memory(png_voidp argument)
2192{
2193 png_image_write_control *display = png_voidcast(png_image_write_control*,
2194 argument);
2195
2196 /* The rest of the memory-specific init and write_main in an error protected
2197 * environment. This case needs to use callbacks for the write operations
2198 * since libpng has no built in support for writing to memory.
2199 */
2200 png_set_write_fn(display->image->opaque->png_ptr, display/*io_ptr*/,
2201 image_memory_write, image_memory_flush);
2202
2203 return png_image_write_main(display);
2204}
2205
2206int PNGAPI
2207png_image_write_to_memory(png_imagep image, void *memory,
2208 png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8bit,
2209 const void *buffer, png_int_32 row_stride, const void *colormap)
2210{
2211 /* Write the image to the given buffer, or count the bytes if it is NULL */
2212 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2213 {
2214 if (memory_bytes != NULL && buffer != NULL)
2215 {
2216 /* This is to give the caller an easier error detection in the NULL
2217 * case and guard against uninitialized variable problems:
2218 */
2219 if (memory == NULL)
2220 *memory_bytes = 0;
2221
2222 if (png_image_write_init(image) != 0)
2223 {
2224 png_image_write_control display;
2225 int result;
2226
2227 memset(&display, 0, (sizeof display));
2228 display.image = image;
2229 display.buffer = buffer;
2230 display.row_stride = row_stride;
2231 display.colormap = colormap;
2232 display.convert_to_8bit = convert_to_8bit;
2233 display.memory = png_voidcast(png_bytep, memory);
2234 display.memory_bytes = *memory_bytes;
2235 display.output_bytes = 0;
2236
2237 result = png_safe_execute(image, png_image_write_memory, &display);
2238 png_image_free(image);
2239
2240 /* write_memory returns true even if we ran out of buffer. */
2241 if (result)
2242 {
2243 /* On out-of-buffer this function returns '0' but still updates
2244 * memory_bytes:
2245 */
2246 if (memory != NULL && display.output_bytes > *memory_bytes)
2247 result = 0;
2248
2249 *memory_bytes = display.output_bytes;
2250 }
2251
2252 return result;
2253 }
2254
2255 else
2256 return 0;
2257 }
2258
2259 else
2260 return png_image_error(image,
2261 "png_image_write_to_memory: invalid argument");
2262 }
2263
2264 else if (image != NULL)
2265 return png_image_error(image,
2266 "png_image_write_to_memory: incorrect PNG_IMAGE_VERSION");
2267
2268 else
2269 return 0;
2270}
2271
2272#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
2273int PNGAPI
2274png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit,
2275 const void *buffer, png_int_32 row_stride, const void *colormap)
2276{
2277 /* Write the image to the given (FILE*). */
2278 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2279 {
2280 if (file != NULL && buffer != NULL)
2281 {
2282 if (png_image_write_init(image) != 0)
2283 {
2284 png_image_write_control display;
2285 int result;
2286
2287 /* This is slightly evil, but png_init_io doesn't do anything other
2288 * than this and we haven't changed the standard IO functions so
2289 * this saves a 'safe' function.
2290 */
2291 image->opaque->png_ptr->io_ptr = file;
2292
2293 memset(&display, 0, (sizeof display));
2294 display.image = image;
2295 display.buffer = buffer;
2296 display.row_stride = row_stride;
2297 display.colormap = colormap;
2298 display.convert_to_8bit = convert_to_8bit;
2299
2300 result = png_safe_execute(image, png_image_write_main, &display);
2301 png_image_free(image);
2302 return result;
2303 }
2304
2305 else
2306 return 0;
2307 }
2308
2309 else
2310 return png_image_error(image,
2311 "png_image_write_to_stdio: invalid argument");
2312 }
2313
2314 else if (image != NULL)
2315 return png_image_error(image,
2316 "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION");
2317
2318 else
2319 return 0;
2320}
2321
2322int PNGAPI
2323png_image_write_to_file(png_imagep image, const char *file_name,
2324 int convert_to_8bit, const void *buffer, png_int_32 row_stride,
2325 const void *colormap)
2326{
2327 /* Write the image to the named file. */
2328 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2329 {
2330 if (file_name != NULL && buffer != NULL)
2331 {
2332 FILE *fp = fopen(file_name, "wb");
2333
2334 if (fp != NULL)
2335 {
2336 if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer,
2337 row_stride, colormap) != 0)
2338 {
2339 int error; /* from fflush/fclose */
2340
2341 /* Make sure the file is flushed correctly. */
2342 if (fflush(fp) == 0 && ferror(fp) == 0)
2343 {
2344 if (fclose(fp) == 0)
2345 return 1;
2346
2347 error = errno; /* from fclose */
2348 }
2349
2350 else
2351 {
2352 error = errno; /* from fflush or ferror */
2353 (void)fclose(fp);
2354 }
2355
2356 (void)remove(file_name);
2357 /* The image has already been cleaned up; this is just used to
2358 * set the error (because the original write succeeded).
2359 */
2360 return png_image_error(image, strerror(error));
2361 }
2362
2363 else
2364 {
2365 /* Clean up: just the opened file. */
2366 (void)fclose(fp);
2367 (void)remove(file_name);
2368 return 0;
2369 }
2370 }
2371
2372 else
2373 return png_image_error(image, strerror(errno));
2374 }
2375
2376 else
2377 return png_image_error(image,
2378 "png_image_write_to_file: invalid argument");
2379 }
2380
2381 else if (image != NULL)
2382 return png_image_error(image,
2383 "png_image_write_to_file: incorrect PNG_IMAGE_VERSION");
2384
2385 else
2386 return 0;
2387}
2388#endif /* SIMPLIFIED_WRITE_STDIO */
2389#endif /* SIMPLIFIED_WRITE */
2390#endif /* WRITE */
2391