Bug 1845134 - Part 4: Update existing ui-icons to use the latest source from acorn...
[gecko.git] / media / libpng / pngwrite.c
blob9f3743bf5868d07d01b0ebd36b770dd7a8031ade
2 /* pngwrite.c - general routines to write a PNG file
4 * Copyright (c) 2018-2024 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.
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
14 #include "pngpriv.h"
15 #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
16 # include <errno.h>
17 #endif /* SIMPLIFIED_WRITE_STDIO */
19 #ifdef PNG_WRITE_SUPPORTED
21 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
22 /* Write out all the unknown chunks for the current given location */
23 static void
24 write_unknown_chunks(png_structrp png_ptr, png_const_inforp info_ptr,
25 unsigned int where)
27 if (info_ptr->unknown_chunks_num != 0)
29 png_const_unknown_chunkp up;
31 png_debug(5, "writing extra chunks");
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)
38 /* If per-chunk unknown chunk handling is enabled use it, otherwise
39 * just write the chunks the application has set.
41 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
42 int keep = png_handle_as_unknown(png_ptr, up->name);
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.
51 * The default handling is also slightly weird - it is not possible to
52 * stop the writing of all unsafe-to-copy chunks!
54 * TODO: REVIEW: this would seem to be a bug.
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
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");
67 png_write_chunk(png_ptr, up->name, up->data, up->size);
72 #endif /* WRITE_UNKNOWN_CHUNKS */
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_<chunk> flag, and check info_ptr->valid before
79 * writing the chunk, as that will keep the code from breaking if you want
80 * to just write a plain PNG file. If you have long comments, I suggest
81 * writing them in png_write_end(), and compressing them.
83 void PNGAPI
84 png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr)
86 png_debug(1, "in png_write_info_before_PLTE");
88 if (png_ptr == NULL || info_ptr == NULL)
89 return;
91 if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
93 /* Write PNG signature */
94 png_write_sig(png_ptr);
96 #ifdef PNG_MNG_FEATURES_SUPPORTED
97 if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \
98 png_ptr->mng_features_permitted != 0)
100 png_warning(png_ptr,
101 "MNG features are not allowed in a PNG datastream");
102 png_ptr->mng_features_permitted = 0;
104 #endif
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
114 #endif
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.
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.)
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.
131 #ifdef PNG_WRITE_APNG_SUPPORTED
132 if ((info_ptr->valid & PNG_INFO_acTL) != 0)
133 png_write_acTL(png_ptr, info_ptr->num_frames, info_ptr->num_plays);
134 #endif
135 #ifdef PNG_GAMMA_SUPPORTED
136 # ifdef PNG_WRITE_gAMA_SUPPORTED
137 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
138 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_gAMA) != 0 &&
139 (info_ptr->valid & PNG_INFO_gAMA) != 0)
140 png_write_gAMA_fixed(png_ptr, info_ptr->colorspace.gamma);
141 # endif
142 #endif
144 #ifdef PNG_COLORSPACE_SUPPORTED
145 /* Write only one of sRGB or an ICC profile. If a profile was supplied
146 * and it matches one of the known sRGB ones issue a warning.
148 # ifdef PNG_WRITE_iCCP_SUPPORTED
149 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
150 (info_ptr->valid & PNG_INFO_iCCP) != 0)
152 # ifdef PNG_WRITE_sRGB_SUPPORTED
153 if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
154 png_app_warning(png_ptr,
155 "profile matches sRGB but writing iCCP instead");
156 # endif
158 png_write_iCCP(png_ptr, info_ptr->iccp_name,
159 info_ptr->iccp_profile);
161 # ifdef PNG_WRITE_sRGB_SUPPORTED
162 else
163 # endif
164 # endif
166 # ifdef PNG_WRITE_sRGB_SUPPORTED
167 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
168 (info_ptr->valid & PNG_INFO_sRGB) != 0)
169 png_write_sRGB(png_ptr, info_ptr->colorspace.rendering_intent);
170 # endif /* WRITE_sRGB */
171 #endif /* COLORSPACE */
173 #ifdef PNG_WRITE_sBIT_SUPPORTED
174 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
175 png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
176 #endif
178 #ifdef PNG_COLORSPACE_SUPPORTED
179 # ifdef PNG_WRITE_cHRM_SUPPORTED
180 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
181 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0 &&
182 (info_ptr->valid & PNG_INFO_cHRM) != 0)
183 png_write_cHRM_fixed(png_ptr, &info_ptr->colorspace.end_points_xy);
184 # endif
185 #endif
187 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
188 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
189 #endif
191 png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
195 void PNGAPI
196 png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
198 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
199 int i;
200 #endif
202 png_debug(1, "in png_write_info");
204 if (png_ptr == NULL || info_ptr == NULL)
205 return;
207 png_write_info_before_PLTE(png_ptr, info_ptr);
209 if ((info_ptr->valid & PNG_INFO_PLTE) != 0)
210 png_write_PLTE(png_ptr, info_ptr->palette,
211 (png_uint_32)info_ptr->num_palette);
213 else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
214 png_error(png_ptr, "Valid palette required for paletted images");
216 #ifdef PNG_WRITE_tRNS_SUPPORTED
217 if ((info_ptr->valid & PNG_INFO_tRNS) !=0)
219 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
220 /* Invert the alpha channel (in tRNS) */
221 if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 &&
222 info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
224 int j, jend;
226 jend = info_ptr->num_trans;
227 if (jend > PNG_MAX_PALETTE_LENGTH)
228 jend = PNG_MAX_PALETTE_LENGTH;
230 for (j = 0; j<jend; ++j)
231 info_ptr->trans_alpha[j] =
232 (png_byte)(255 - info_ptr->trans_alpha[j]);
234 #endif
235 png_write_tRNS(png_ptr, info_ptr->trans_alpha, &(info_ptr->trans_color),
236 info_ptr->num_trans, info_ptr->color_type);
238 #endif
239 #ifdef PNG_WRITE_bKGD_SUPPORTED
240 if ((info_ptr->valid & PNG_INFO_bKGD) != 0)
241 png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
242 #endif
244 #ifdef PNG_WRITE_eXIf_SUPPORTED
245 if ((info_ptr->valid & PNG_INFO_eXIf) != 0)
247 png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
248 png_ptr->mode |= PNG_WROTE_eXIf;
250 #endif
252 #ifdef PNG_WRITE_hIST_SUPPORTED
253 if ((info_ptr->valid & PNG_INFO_hIST) != 0)
254 png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
255 #endif
257 #ifdef PNG_WRITE_oFFs_SUPPORTED
258 if ((info_ptr->valid & PNG_INFO_oFFs) != 0)
259 png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
260 info_ptr->offset_unit_type);
261 #endif
263 #ifdef PNG_WRITE_pCAL_SUPPORTED
264 if ((info_ptr->valid & PNG_INFO_pCAL) != 0)
265 png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
266 info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
267 info_ptr->pcal_units, info_ptr->pcal_params);
268 #endif
270 #ifdef PNG_WRITE_sCAL_SUPPORTED
271 if ((info_ptr->valid & PNG_INFO_sCAL) != 0)
272 png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
273 info_ptr->scal_s_width, info_ptr->scal_s_height);
274 #endif /* sCAL */
276 #ifdef PNG_WRITE_pHYs_SUPPORTED
277 if ((info_ptr->valid & PNG_INFO_pHYs) != 0)
278 png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
279 info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
280 #endif /* pHYs */
282 #ifdef PNG_WRITE_tIME_SUPPORTED
283 if ((info_ptr->valid & PNG_INFO_tIME) != 0)
285 png_write_tIME(png_ptr, &(info_ptr->mod_time));
286 png_ptr->mode |= PNG_WROTE_tIME;
288 #endif /* tIME */
290 #ifdef PNG_WRITE_sPLT_SUPPORTED
291 if ((info_ptr->valid & PNG_INFO_sPLT) != 0)
292 for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
293 png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
294 #endif /* sPLT */
296 #ifdef PNG_WRITE_TEXT_SUPPORTED
297 /* Check to see if we need to write text chunks */
298 for (i = 0; i < info_ptr->num_text; i++)
300 png_debug2(2, "Writing header text chunk %d, type %d", i,
301 info_ptr->text[i].compression);
302 /* An internationalized chunk? */
303 if (info_ptr->text[i].compression > 0)
305 #ifdef PNG_WRITE_iTXt_SUPPORTED
306 /* Write international chunk */
307 png_write_iTXt(png_ptr,
308 info_ptr->text[i].compression,
309 info_ptr->text[i].key,
310 info_ptr->text[i].lang,
311 info_ptr->text[i].lang_key,
312 info_ptr->text[i].text);
313 /* Mark this chunk as written */
314 if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
315 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
316 else
317 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
318 #else
319 png_warning(png_ptr, "Unable to write international text");
320 #endif
323 /* If we want a compressed text chunk */
324 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
326 #ifdef PNG_WRITE_zTXt_SUPPORTED
327 /* Write compressed chunk */
328 png_write_zTXt(png_ptr, info_ptr->text[i].key,
329 info_ptr->text[i].text, info_ptr->text[i].compression);
330 /* Mark this chunk as written */
331 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
332 #else
333 png_warning(png_ptr, "Unable to write compressed text");
334 #endif
337 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
339 #ifdef PNG_WRITE_tEXt_SUPPORTED
340 /* Write uncompressed chunk */
341 png_write_tEXt(png_ptr, info_ptr->text[i].key,
342 info_ptr->text[i].text,
344 /* Mark this chunk as written */
345 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
346 #else
347 /* Can't get here */
348 png_warning(png_ptr, "Unable to write uncompressed text");
349 #endif
352 #endif /* tEXt */
354 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
355 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE);
356 #endif
359 /* Writes the end of the PNG file. If you don't want to write comments or
360 * time information, you can pass NULL for info. If you already wrote these
361 * in png_write_info(), do not write them again here. If you have long
362 * comments, I suggest writing them here, and compressing them.
364 void PNGAPI
365 png_write_end(png_structrp png_ptr, png_inforp info_ptr)
367 png_debug(1, "in png_write_end");
369 if (png_ptr == NULL)
370 return;
372 if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
373 png_error(png_ptr, "No IDATs written into file");
375 #ifdef PNG_WRITE_APNG_SUPPORTED
376 if (png_ptr->num_frames_written != png_ptr->num_frames_to_write)
377 png_error(png_ptr, "Not enough frames written");
378 #endif
380 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
381 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
382 png_ptr->num_palette_max >= png_ptr->num_palette)
383 png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
384 #endif
386 /* See if user wants us to write information chunks */
387 if (info_ptr != NULL)
389 #ifdef PNG_WRITE_TEXT_SUPPORTED
390 int i; /* local index variable */
391 #endif
392 #ifdef PNG_WRITE_tIME_SUPPORTED
393 /* Check to see if user has supplied a time chunk */
394 if ((info_ptr->valid & PNG_INFO_tIME) != 0 &&
395 (png_ptr->mode & PNG_WROTE_tIME) == 0)
396 png_write_tIME(png_ptr, &(info_ptr->mod_time));
398 #endif
399 #ifdef PNG_WRITE_TEXT_SUPPORTED
400 /* Loop through comment chunks */
401 for (i = 0; i < info_ptr->num_text; i++)
403 png_debug2(2, "Writing trailer text chunk %d, type %d", i,
404 info_ptr->text[i].compression);
405 /* An internationalized chunk? */
406 if (info_ptr->text[i].compression > 0)
408 #ifdef PNG_WRITE_iTXt_SUPPORTED
409 /* Write international chunk */
410 png_write_iTXt(png_ptr,
411 info_ptr->text[i].compression,
412 info_ptr->text[i].key,
413 info_ptr->text[i].lang,
414 info_ptr->text[i].lang_key,
415 info_ptr->text[i].text);
416 /* Mark this chunk as written */
417 if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
418 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
419 else
420 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
421 #else
422 png_warning(png_ptr, "Unable to write international text");
423 #endif
426 else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
428 #ifdef PNG_WRITE_zTXt_SUPPORTED
429 /* Write compressed chunk */
430 png_write_zTXt(png_ptr, info_ptr->text[i].key,
431 info_ptr->text[i].text, info_ptr->text[i].compression);
432 /* Mark this chunk as written */
433 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
434 #else
435 png_warning(png_ptr, "Unable to write compressed text");
436 #endif
439 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
441 #ifdef PNG_WRITE_tEXt_SUPPORTED
442 /* Write uncompressed chunk */
443 png_write_tEXt(png_ptr, info_ptr->text[i].key,
444 info_ptr->text[i].text, 0);
445 /* Mark this chunk as written */
446 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
447 #else
448 png_warning(png_ptr, "Unable to write uncompressed text");
449 #endif
452 #endif
454 #ifdef PNG_WRITE_eXIf_SUPPORTED
455 if ((info_ptr->valid & PNG_INFO_eXIf) != 0 &&
456 (png_ptr->mode & PNG_WROTE_eXIf) == 0)
457 png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
458 #endif
460 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
461 write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT);
462 #endif
465 png_ptr->mode |= PNG_AFTER_IDAT;
467 /* Write end of PNG file */
468 png_write_IEND(png_ptr);
470 /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03,
471 * and restored again in libpng-1.2.30, may cause some applications that
472 * do not set png_ptr->output_flush_fn to crash. If your application
473 * experiences a problem, please try building libpng with
474 * PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED defined, and report the event to
475 * png-mng-implement at lists.sf.net .
477 #ifdef PNG_WRITE_FLUSH_SUPPORTED
478 # ifdef PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED
479 png_flush(png_ptr);
480 # endif
481 #endif
484 #ifdef PNG_CONVERT_tIME_SUPPORTED
485 void PNGAPI
486 png_convert_from_struct_tm(png_timep ptime, const struct tm * ttime)
488 png_debug(1, "in png_convert_from_struct_tm");
490 ptime->year = (png_uint_16)(1900 + ttime->tm_year);
491 ptime->month = (png_byte)(ttime->tm_mon + 1);
492 ptime->day = (png_byte)ttime->tm_mday;
493 ptime->hour = (png_byte)ttime->tm_hour;
494 ptime->minute = (png_byte)ttime->tm_min;
495 ptime->second = (png_byte)ttime->tm_sec;
498 void PNGAPI
499 png_convert_from_time_t(png_timep ptime, time_t ttime)
501 struct tm *tbuf;
503 png_debug(1, "in png_convert_from_time_t");
505 tbuf = gmtime(&ttime);
506 if (tbuf == NULL)
508 /* TODO: add a safe function which takes a png_ptr argument and raises
509 * a png_error if the ttime argument is invalid and the call to gmtime
510 * fails as a consequence.
512 memset(ptime, 0, sizeof(*ptime));
513 return;
516 png_convert_from_struct_tm(ptime, tbuf);
518 #endif
520 /* Initialize png_ptr structure, and allocate any memory needed */
521 PNG_FUNCTION(png_structp,PNGAPI
522 png_create_write_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
523 png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
525 #ifndef PNG_USER_MEM_SUPPORTED
526 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
527 error_fn, warn_fn, NULL, NULL, NULL);
528 #else
529 return png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
530 warn_fn, NULL, NULL, NULL);
533 /* Alternate initialize png_ptr structure, and allocate any memory needed */
534 PNG_FUNCTION(png_structp,PNGAPI
535 png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
536 png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
537 png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
539 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
540 error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
541 #endif /* USER_MEM */
542 if (png_ptr != NULL)
544 /* Set the zlib control values to defaults; they can be overridden by the
545 * application after the struct has been created.
547 png_ptr->zbuffer_size = PNG_ZBUF_SIZE;
549 /* The 'zlib_strategy' setting is irrelevant because png_default_claim in
550 * pngwutil.c defaults it according to whether or not filters will be
551 * used, and ignores this setting.
553 png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY;
554 png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION;
555 png_ptr->zlib_mem_level = 8;
556 png_ptr->zlib_window_bits = 15;
557 png_ptr->zlib_method = 8;
559 #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
560 png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY;
561 png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION;
562 png_ptr->zlib_text_mem_level = 8;
563 png_ptr->zlib_text_window_bits = 15;
564 png_ptr->zlib_text_method = 8;
565 #endif /* WRITE_COMPRESSED_TEXT */
567 /* This is a highly dubious configuration option; by default it is off,
568 * but it may be appropriate for private builds that are testing
569 * extensions not conformant to the current specification, or of
570 * applications that must not fail to write at all costs!
572 #ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED
573 /* In stable builds only warn if an application error can be completely
574 * handled.
576 png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
577 #endif
579 /* App warnings are warnings in release (or release candidate) builds but
580 * are errors during development.
582 #if PNG_RELEASE_BUILD
583 png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
584 #endif
586 /* TODO: delay this, it can be done in png_init_io() (if the app doesn't
587 * do it itself) avoiding setting the default function if it is not
588 * required.
590 png_set_write_fn(png_ptr, NULL, NULL, NULL);
593 return png_ptr;
597 /* Write a few rows of image data. If the image is interlaced,
598 * either you will have to write the 7 sub images, or, if you
599 * have called png_set_interlace_handling(), you will have to
600 * "write" the image seven times.
602 void PNGAPI
603 png_write_rows(png_structrp png_ptr, png_bytepp row,
604 png_uint_32 num_rows)
606 png_uint_32 i; /* row counter */
607 png_bytepp rp; /* row pointer */
609 png_debug(1, "in png_write_rows");
611 if (png_ptr == NULL)
612 return;
614 /* Loop through the rows */
615 for (i = 0, rp = row; i < num_rows; i++, rp++)
617 png_write_row(png_ptr, *rp);
621 /* Write the image. You only need to call this function once, even
622 * if you are writing an interlaced image.
624 void PNGAPI
625 png_write_image(png_structrp png_ptr, png_bytepp image)
627 png_uint_32 i; /* row index */
628 int pass, num_pass; /* pass variables */
629 png_bytepp rp; /* points to current row */
631 if (png_ptr == NULL)
632 return;
634 png_debug(1, "in png_write_image");
636 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
637 /* Initialize interlace handling. If image is not interlaced,
638 * this will set pass to 1
640 num_pass = png_set_interlace_handling(png_ptr);
641 #else
642 num_pass = 1;
643 #endif
644 /* Loop through passes */
645 for (pass = 0; pass < num_pass; pass++)
647 /* Loop through image */
648 for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
650 png_write_row(png_ptr, *rp);
655 #ifdef PNG_MNG_FEATURES_SUPPORTED
656 /* Performs intrapixel differencing */
657 static void
658 png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
660 png_debug(1, "in png_do_write_intrapixel");
662 if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
664 int bytes_per_pixel;
665 png_uint_32 row_width = row_info->width;
666 if (row_info->bit_depth == 8)
668 png_bytep rp;
669 png_uint_32 i;
671 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
672 bytes_per_pixel = 3;
674 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
675 bytes_per_pixel = 4;
677 else
678 return;
680 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
682 *(rp) = (png_byte)(*rp - *(rp + 1));
683 *(rp + 2) = (png_byte)(*(rp + 2) - *(rp + 1));
687 #ifdef PNG_WRITE_16BIT_SUPPORTED
688 else if (row_info->bit_depth == 16)
690 png_bytep rp;
691 png_uint_32 i;
693 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
694 bytes_per_pixel = 6;
696 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
697 bytes_per_pixel = 8;
699 else
700 return;
702 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
704 png_uint_32 s0 = (png_uint_32)(*(rp ) << 8) | *(rp + 1);
705 png_uint_32 s1 = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
706 png_uint_32 s2 = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
707 png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL);
708 png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
709 *(rp ) = (png_byte)(red >> 8);
710 *(rp + 1) = (png_byte)red;
711 *(rp + 4) = (png_byte)(blue >> 8);
712 *(rp + 5) = (png_byte)blue;
715 #endif /* WRITE_16BIT */
718 #endif /* MNG_FEATURES */
720 /* Called by user to write a row of image data */
721 void PNGAPI
722 png_write_row(png_structrp png_ptr, png_const_bytep row)
724 /* 1.5.6: moved from png_struct to be a local structure: */
725 png_row_info row_info;
727 png_debug2(1, "in png_write_row (row %u, pass %d)",
728 png_ptr->row_number, png_ptr->pass);
730 if (png_ptr == NULL)
731 return;
733 /* Initialize transformations and other stuff if first time */
734 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
736 /* Make sure we wrote the header info */
737 if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
738 png_error(png_ptr,
739 "png_write_info was never called before png_write_row");
741 /* Check for transforms that have been set but were defined out */
742 #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
743 if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
744 png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined");
745 #endif
747 #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
748 if ((png_ptr->transformations & PNG_FILLER) != 0)
749 png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined");
750 #endif
751 #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
752 defined(PNG_READ_PACKSWAP_SUPPORTED)
753 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
754 png_warning(png_ptr,
755 "PNG_WRITE_PACKSWAP_SUPPORTED is not defined");
756 #endif
758 #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
759 if ((png_ptr->transformations & PNG_PACK) != 0)
760 png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined");
761 #endif
763 #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
764 if ((png_ptr->transformations & PNG_SHIFT) != 0)
765 png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined");
766 #endif
768 #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
769 if ((png_ptr->transformations & PNG_BGR) != 0)
770 png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined");
771 #endif
773 #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
774 if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
775 png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined");
776 #endif
778 png_write_start_row(png_ptr);
781 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
782 /* If interlaced and not interested in row, return */
783 if (png_ptr->interlaced != 0 &&
784 (png_ptr->transformations & PNG_INTERLACE) != 0)
786 switch (png_ptr->pass)
788 case 0:
789 if ((png_ptr->row_number & 0x07) != 0)
791 png_write_finish_row(png_ptr);
792 return;
794 break;
796 case 1:
797 if ((png_ptr->row_number & 0x07) != 0 || png_ptr->width < 5)
799 png_write_finish_row(png_ptr);
800 return;
802 break;
804 case 2:
805 if ((png_ptr->row_number & 0x07) != 4)
807 png_write_finish_row(png_ptr);
808 return;
810 break;
812 case 3:
813 if ((png_ptr->row_number & 0x03) != 0 || png_ptr->width < 3)
815 png_write_finish_row(png_ptr);
816 return;
818 break;
820 case 4:
821 if ((png_ptr->row_number & 0x03) != 2)
823 png_write_finish_row(png_ptr);
824 return;
826 break;
828 case 5:
829 if ((png_ptr->row_number & 0x01) != 0 || png_ptr->width < 2)
831 png_write_finish_row(png_ptr);
832 return;
834 break;
836 case 6:
837 if ((png_ptr->row_number & 0x01) == 0)
839 png_write_finish_row(png_ptr);
840 return;
842 break;
844 default: /* error: ignore it */
845 break;
848 #endif
850 /* Set up row info for transformations */
851 row_info.color_type = png_ptr->color_type;
852 row_info.width = png_ptr->usr_width;
853 row_info.channels = png_ptr->usr_channels;
854 row_info.bit_depth = png_ptr->usr_bit_depth;
855 row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels);
856 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
858 png_debug1(3, "row_info->color_type = %d", row_info.color_type);
859 png_debug1(3, "row_info->width = %u", row_info.width);
860 png_debug1(3, "row_info->channels = %d", row_info.channels);
861 png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth);
862 png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth);
863 png_debug1(3, "row_info->rowbytes = %lu", (unsigned long)row_info.rowbytes);
865 /* Copy user's row into buffer, leaving room for filter byte. */
866 memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes);
868 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
869 /* Handle interlacing */
870 if (png_ptr->interlaced && png_ptr->pass < 6 &&
871 (png_ptr->transformations & PNG_INTERLACE) != 0)
873 png_do_write_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass);
874 /* This should always get caught above, but still ... */
875 if (row_info.width == 0)
877 png_write_finish_row(png_ptr);
878 return;
881 #endif
883 #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
884 /* Handle other transformations */
885 if (png_ptr->transformations != 0)
886 png_do_write_transformations(png_ptr, &row_info);
887 #endif
889 /* At this point the row_info pixel depth must match the 'transformed' depth,
890 * which is also the output depth.
892 if (row_info.pixel_depth != png_ptr->pixel_depth ||
893 row_info.pixel_depth != png_ptr->transformed_pixel_depth)
894 png_error(png_ptr, "internal write transform logic error");
896 #ifdef PNG_MNG_FEATURES_SUPPORTED
897 /* Write filter_method 64 (intrapixel differencing) only if
898 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
899 * 2. Libpng did not write a PNG signature (this filter_method is only
900 * used in PNG datastreams that are embedded in MNG datastreams) and
901 * 3. The application called png_permit_mng_features with a mask that
902 * included PNG_FLAG_MNG_FILTER_64 and
903 * 4. The filter_method is 64 and
904 * 5. The color_type is RGB or RGBA
906 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
907 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
909 /* Intrapixel differencing */
910 png_do_write_intrapixel(&row_info, png_ptr->row_buf + 1);
912 #endif
914 /* Added at libpng-1.5.10 */
915 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
916 /* Check for out-of-range palette index */
917 if (row_info.color_type == PNG_COLOR_TYPE_PALETTE &&
918 png_ptr->num_palette_max >= 0)
919 png_do_check_palette_indexes(png_ptr, &row_info);
920 #endif
922 /* Find a filter if necessary, filter the row and write it out. */
923 png_write_find_filter(png_ptr, &row_info);
925 if (png_ptr->write_row_fn != NULL)
926 (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
929 #ifdef PNG_WRITE_FLUSH_SUPPORTED
930 /* Set the automatic flush interval or 0 to turn flushing off */
931 void PNGAPI
932 png_set_flush(png_structrp png_ptr, int nrows)
934 png_debug(1, "in png_set_flush");
936 if (png_ptr == NULL)
937 return;
939 png_ptr->flush_dist = (nrows < 0 ? 0 : (png_uint_32)nrows);
942 /* Flush the current output buffers now */
943 void PNGAPI
944 png_write_flush(png_structrp png_ptr)
946 png_debug(1, "in png_write_flush");
948 if (png_ptr == NULL)
949 return;
951 /* We have already written out all of the data */
952 if (png_ptr->row_number >= png_ptr->num_rows)
953 return;
955 png_compress_IDAT(png_ptr, NULL, 0, Z_SYNC_FLUSH);
956 png_ptr->flush_rows = 0;
957 png_flush(png_ptr);
959 #endif /* WRITE_FLUSH */
961 /* Free any memory used in png_ptr struct without freeing the struct itself. */
962 static void
963 png_write_destroy(png_structrp png_ptr)
965 png_debug(1, "in png_write_destroy");
967 /* Free any memory zlib uses */
968 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
969 deflateEnd(&png_ptr->zstream);
971 /* Free our memory. png_free checks NULL for us. */
972 png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
973 png_free(png_ptr, png_ptr->row_buf);
974 png_ptr->row_buf = NULL;
975 #ifdef PNG_WRITE_FILTER_SUPPORTED
976 png_free(png_ptr, png_ptr->prev_row);
977 png_free(png_ptr, png_ptr->try_row);
978 png_free(png_ptr, png_ptr->tst_row);
979 png_ptr->prev_row = NULL;
980 png_ptr->try_row = NULL;
981 png_ptr->tst_row = NULL;
982 #endif
984 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
985 png_free(png_ptr, png_ptr->chunk_list);
986 png_ptr->chunk_list = NULL;
987 #endif
989 /* The error handling and memory handling information is left intact at this
990 * point: the jmp_buf may still have to be freed. See png_destroy_png_struct
991 * for how this happens.
995 /* Free all memory used by the write.
996 * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for
997 * *png_ptr_ptr. Prior to 1.6.0 it would accept such a value and it would free
998 * the passed in info_structs but it would quietly fail to free any of the data
999 * inside them. In 1.6.0 it quietly does nothing (it has to be quiet because it
1000 * has no png_ptr.)
1002 void PNGAPI
1003 png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
1005 png_debug(1, "in png_destroy_write_struct");
1007 if (png_ptr_ptr != NULL)
1009 png_structrp png_ptr = *png_ptr_ptr;
1011 if (png_ptr != NULL) /* added in libpng 1.6.0 */
1013 png_destroy_info_struct(png_ptr, info_ptr_ptr);
1015 *png_ptr_ptr = NULL;
1016 png_write_destroy(png_ptr);
1017 png_destroy_png_struct(png_ptr);
1022 /* Allow the application to select one or more row filters to use. */
1023 void PNGAPI
1024 png_set_filter(png_structrp png_ptr, int method, int filters)
1026 png_debug(1, "in png_set_filter");
1028 if (png_ptr == NULL)
1029 return;
1031 #ifdef PNG_MNG_FEATURES_SUPPORTED
1032 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
1033 (method == PNG_INTRAPIXEL_DIFFERENCING))
1034 method = PNG_FILTER_TYPE_BASE;
1036 #endif
1037 if (method == PNG_FILTER_TYPE_BASE)
1039 switch (filters & (PNG_ALL_FILTERS | 0x07))
1041 #ifdef PNG_WRITE_FILTER_SUPPORTED
1042 case 5:
1043 case 6:
1044 case 7: png_app_error(png_ptr, "Unknown row filter for method 0");
1045 #endif /* WRITE_FILTER */
1046 /* FALLTHROUGH */
1047 case PNG_FILTER_VALUE_NONE:
1048 png_ptr->do_filter = PNG_FILTER_NONE; break;
1050 #ifdef PNG_WRITE_FILTER_SUPPORTED
1051 case PNG_FILTER_VALUE_SUB:
1052 png_ptr->do_filter = PNG_FILTER_SUB; break;
1054 case PNG_FILTER_VALUE_UP:
1055 png_ptr->do_filter = PNG_FILTER_UP; break;
1057 case PNG_FILTER_VALUE_AVG:
1058 png_ptr->do_filter = PNG_FILTER_AVG; break;
1060 case PNG_FILTER_VALUE_PAETH:
1061 png_ptr->do_filter = PNG_FILTER_PAETH; break;
1063 default:
1064 png_ptr->do_filter = (png_byte)filters; break;
1065 #else
1066 default:
1067 png_app_error(png_ptr, "Unknown row filter for method 0");
1068 #endif /* WRITE_FILTER */
1071 #ifdef PNG_WRITE_FILTER_SUPPORTED
1072 /* If we have allocated the row_buf, this means we have already started
1073 * with the image and we should have allocated all of the filter buffers
1074 * that have been selected. If prev_row isn't already allocated, then
1075 * it is too late to start using the filters that need it, since we
1076 * will be missing the data in the previous row. If an application
1077 * wants to start and stop using particular filters during compression,
1078 * it should start out with all of the filters, and then remove them
1079 * or add them back after the start of compression.
1081 * NOTE: this is a nasty constraint on the code, because it means that the
1082 * prev_row buffer must be maintained even if there are currently no
1083 * 'prev_row' requiring filters active.
1085 if (png_ptr->row_buf != NULL)
1087 int num_filters;
1088 png_alloc_size_t buf_size;
1090 /* Repeat the checks in png_write_start_row; 1 pixel high or wide
1091 * images cannot benefit from certain filters. If this isn't done here
1092 * the check below will fire on 1 pixel high images.
1094 if (png_ptr->height == 1)
1095 filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1097 if (png_ptr->width == 1)
1098 filters &= ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1100 if ((filters & (PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)) != 0
1101 && png_ptr->prev_row == NULL)
1103 /* This is the error case, however it is benign - the previous row
1104 * is not available so the filter can't be used. Just warn here.
1106 png_app_warning(png_ptr,
1107 "png_set_filter: UP/AVG/PAETH cannot be added after start");
1108 filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1111 num_filters = 0;
1113 if (filters & PNG_FILTER_SUB)
1114 num_filters++;
1116 if (filters & PNG_FILTER_UP)
1117 num_filters++;
1119 if (filters & PNG_FILTER_AVG)
1120 num_filters++;
1122 if (filters & PNG_FILTER_PAETH)
1123 num_filters++;
1125 /* Allocate needed row buffers if they have not already been
1126 * allocated.
1128 buf_size = PNG_ROWBYTES(png_ptr->usr_channels * png_ptr->usr_bit_depth,
1129 png_ptr->width) + 1;
1131 if (png_ptr->try_row == NULL)
1132 png_ptr->try_row = png_voidcast(png_bytep,
1133 png_malloc(png_ptr, buf_size));
1135 if (num_filters > 1)
1137 if (png_ptr->tst_row == NULL)
1138 png_ptr->tst_row = png_voidcast(png_bytep,
1139 png_malloc(png_ptr, buf_size));
1142 png_ptr->do_filter = (png_byte)filters;
1143 #endif
1145 else
1146 png_error(png_ptr, "Unknown custom filter method");
1149 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */
1150 /* Provide floating and fixed point APIs */
1151 #ifdef PNG_FLOATING_POINT_SUPPORTED
1152 void PNGAPI
1153 png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method,
1154 int num_weights, png_const_doublep filter_weights,
1155 png_const_doublep filter_costs)
1157 PNG_UNUSED(png_ptr)
1158 PNG_UNUSED(heuristic_method)
1159 PNG_UNUSED(num_weights)
1160 PNG_UNUSED(filter_weights)
1161 PNG_UNUSED(filter_costs)
1163 #endif /* FLOATING_POINT */
1165 #ifdef PNG_FIXED_POINT_SUPPORTED
1166 void PNGAPI
1167 png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method,
1168 int num_weights, png_const_fixed_point_p filter_weights,
1169 png_const_fixed_point_p filter_costs)
1171 PNG_UNUSED(png_ptr)
1172 PNG_UNUSED(heuristic_method)
1173 PNG_UNUSED(num_weights)
1174 PNG_UNUSED(filter_weights)
1175 PNG_UNUSED(filter_costs)
1177 #endif /* FIXED_POINT */
1178 #endif /* WRITE_WEIGHTED_FILTER */
1180 #ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
1181 void PNGAPI
1182 png_set_compression_level(png_structrp png_ptr, int level)
1184 png_debug(1, "in png_set_compression_level");
1186 if (png_ptr == NULL)
1187 return;
1189 png_ptr->zlib_level = level;
1192 void PNGAPI
1193 png_set_compression_mem_level(png_structrp png_ptr, int mem_level)
1195 png_debug(1, "in png_set_compression_mem_level");
1197 if (png_ptr == NULL)
1198 return;
1200 png_ptr->zlib_mem_level = mem_level;
1203 void PNGAPI
1204 png_set_compression_strategy(png_structrp png_ptr, int strategy)
1206 png_debug(1, "in png_set_compression_strategy");
1208 if (png_ptr == NULL)
1209 return;
1211 /* The flag setting here prevents the libpng dynamic selection of strategy.
1213 png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
1214 png_ptr->zlib_strategy = strategy;
1217 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1218 * smaller value of window_bits if it can do so safely.
1220 void PNGAPI
1221 png_set_compression_window_bits(png_structrp png_ptr, int window_bits)
1223 png_debug(1, "in png_set_compression_window_bits");
1225 if (png_ptr == NULL)
1226 return;
1228 /* Prior to 1.6.0 this would warn but then set the window_bits value. This
1229 * meant that negative window bits values could be selected that would cause
1230 * libpng to write a non-standard PNG file with raw deflate or gzip
1231 * compressed IDAT or ancillary chunks. Such files can be read and there is
1232 * no warning on read, so this seems like a very bad idea.
1234 if (window_bits > 15)
1236 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1237 window_bits = 15;
1240 else if (window_bits < 8)
1242 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1243 window_bits = 8;
1246 png_ptr->zlib_window_bits = window_bits;
1249 void PNGAPI
1250 png_set_compression_method(png_structrp png_ptr, int method)
1252 png_debug(1, "in png_set_compression_method");
1254 if (png_ptr == NULL)
1255 return;
1257 /* This would produce an invalid PNG file if it worked, but it doesn't and
1258 * deflate will fault it, so it is harmless to just warn here.
1260 if (method != 8)
1261 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1263 png_ptr->zlib_method = method;
1265 #endif /* WRITE_CUSTOMIZE_COMPRESSION */
1267 /* The following were added to libpng-1.5.4 */
1268 #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
1269 void PNGAPI
1270 png_set_text_compression_level(png_structrp png_ptr, int level)
1272 png_debug(1, "in png_set_text_compression_level");
1274 if (png_ptr == NULL)
1275 return;
1277 png_ptr->zlib_text_level = level;
1280 void PNGAPI
1281 png_set_text_compression_mem_level(png_structrp png_ptr, int mem_level)
1283 png_debug(1, "in png_set_text_compression_mem_level");
1285 if (png_ptr == NULL)
1286 return;
1288 png_ptr->zlib_text_mem_level = mem_level;
1291 void PNGAPI
1292 png_set_text_compression_strategy(png_structrp png_ptr, int strategy)
1294 png_debug(1, "in png_set_text_compression_strategy");
1296 if (png_ptr == NULL)
1297 return;
1299 png_ptr->zlib_text_strategy = strategy;
1302 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1303 * smaller value of window_bits if it can do so safely.
1305 void PNGAPI
1306 png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits)
1308 png_debug(1, "in png_set_text_compression_window_bits");
1310 if (png_ptr == NULL)
1311 return;
1313 if (window_bits > 15)
1315 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1316 window_bits = 15;
1319 else if (window_bits < 8)
1321 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1322 window_bits = 8;
1325 png_ptr->zlib_text_window_bits = window_bits;
1328 void PNGAPI
1329 png_set_text_compression_method(png_structrp png_ptr, int method)
1331 png_debug(1, "in png_set_text_compression_method");
1333 if (png_ptr == NULL)
1334 return;
1336 if (method != 8)
1337 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1339 png_ptr->zlib_text_method = method;
1341 #endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */
1342 /* end of API added to libpng-1.5.4 */
1344 void PNGAPI
1345 png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn)
1347 png_debug(1, "in png_set_write_status_fn");
1349 if (png_ptr == NULL)
1350 return;
1352 png_ptr->write_row_fn = write_row_fn;
1355 #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
1356 void PNGAPI
1357 png_set_write_user_transform_fn(png_structrp png_ptr, png_user_transform_ptr
1358 write_user_transform_fn)
1360 png_debug(1, "in png_set_write_user_transform_fn");
1362 if (png_ptr == NULL)
1363 return;
1365 png_ptr->transformations |= PNG_USER_TRANSFORM;
1366 png_ptr->write_user_transform_fn = write_user_transform_fn;
1368 #endif
1371 #ifdef PNG_INFO_IMAGE_SUPPORTED
1372 void PNGAPI
1373 png_write_png(png_structrp png_ptr, png_inforp info_ptr,
1374 int transforms, voidp params)
1376 png_debug(1, "in png_write_png");
1378 if (png_ptr == NULL || info_ptr == NULL)
1379 return;
1381 if ((info_ptr->valid & PNG_INFO_IDAT) == 0)
1383 png_app_error(png_ptr, "no rows for png_write_image to write");
1384 return;
1387 /* Write the file header information. */
1388 png_write_info(png_ptr, info_ptr);
1390 /* ------ these transformations don't touch the info structure ------- */
1392 /* Invert monochrome pixels */
1393 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1394 #ifdef PNG_WRITE_INVERT_SUPPORTED
1395 png_set_invert_mono(png_ptr);
1396 #else
1397 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1398 #endif
1400 /* Shift the pixels up to a legal bit depth and fill in
1401 * as appropriate to correctly scale the image.
1403 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1404 #ifdef PNG_WRITE_SHIFT_SUPPORTED
1405 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1406 png_set_shift(png_ptr, &info_ptr->sig_bit);
1407 #else
1408 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1409 #endif
1411 /* Pack pixels into bytes */
1412 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1413 #ifdef PNG_WRITE_PACK_SUPPORTED
1414 png_set_packing(png_ptr);
1415 #else
1416 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1417 #endif
1419 /* Swap location of alpha bytes from ARGB to RGBA */
1420 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1421 #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
1422 png_set_swap_alpha(png_ptr);
1423 #else
1424 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1425 #endif
1427 /* Remove a filler (X) from XRGB/RGBX/AG/GA into to convert it into
1428 * RGB, note that the code expects the input color type to be G or RGB; no
1429 * alpha channel.
1431 if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER|
1432 PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
1434 #ifdef PNG_WRITE_FILLER_SUPPORTED
1435 if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0)
1437 if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1438 png_app_error(png_ptr,
1439 "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
1441 /* Continue if ignored - this is the pre-1.6.10 behavior */
1442 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
1445 else if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1446 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1447 #else
1448 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_FILLER not supported");
1449 #endif
1452 /* Flip BGR pixels to RGB */
1453 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1454 #ifdef PNG_WRITE_BGR_SUPPORTED
1455 png_set_bgr(png_ptr);
1456 #else
1457 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1458 #endif
1460 /* Swap bytes of 16-bit files to most significant byte first */
1461 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1462 #ifdef PNG_WRITE_SWAP_SUPPORTED
1463 png_set_swap(png_ptr);
1464 #else
1465 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1466 #endif
1468 /* Swap bits of 1-bit, 2-bit, 4-bit packed pixel formats */
1469 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1470 #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
1471 png_set_packswap(png_ptr);
1472 #else
1473 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1474 #endif
1476 /* Invert the alpha channel from opacity to transparency */
1477 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1478 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
1479 png_set_invert_alpha(png_ptr);
1480 #else
1481 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1482 #endif
1484 /* ----------------------- end of transformations ------------------- */
1486 /* Write the bits */
1487 png_write_image(png_ptr, info_ptr->row_pointers);
1489 /* It is REQUIRED to call this to finish writing the rest of the file */
1490 png_write_end(png_ptr, info_ptr);
1492 PNG_UNUSED(params)
1494 #endif
1497 #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
1498 /* Initialize the write structure - general purpose utility. */
1499 static int
1500 png_image_write_init(png_imagep image)
1502 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
1503 png_safe_error, png_safe_warning);
1505 if (png_ptr != NULL)
1507 png_infop info_ptr = png_create_info_struct(png_ptr);
1509 if (info_ptr != NULL)
1511 png_controlp control = png_voidcast(png_controlp,
1512 png_malloc_warn(png_ptr, (sizeof *control)));
1514 if (control != NULL)
1516 memset(control, 0, (sizeof *control));
1518 control->png_ptr = png_ptr;
1519 control->info_ptr = info_ptr;
1520 control->for_write = 1;
1522 image->opaque = control;
1523 return 1;
1526 /* Error clean up */
1527 png_destroy_info_struct(png_ptr, &info_ptr);
1530 png_destroy_write_struct(&png_ptr, NULL);
1533 return png_image_error(image, "png_image_write_: out of memory");
1536 /* Arguments to png_image_write_main: */
1537 typedef struct
1539 /* Arguments: */
1540 png_imagep image;
1541 png_const_voidp buffer;
1542 png_int_32 row_stride;
1543 png_const_voidp colormap;
1544 int convert_to_8bit;
1545 /* Local variables: */
1546 png_const_voidp first_row;
1547 ptrdiff_t row_bytes;
1548 png_voidp local_row;
1549 /* Byte count for memory writing */
1550 png_bytep memory;
1551 png_alloc_size_t memory_bytes; /* not used for STDIO */
1552 png_alloc_size_t output_bytes; /* running total */
1553 } png_image_write_control;
1555 /* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
1556 * do any necessary byte swapping. The component order is defined by the
1557 * png_image format value.
1559 static int
1560 png_write_image_16bit(png_voidp argument)
1562 png_image_write_control *display = png_voidcast(png_image_write_control*,
1563 argument);
1564 png_imagep image = display->image;
1565 png_structrp png_ptr = image->opaque->png_ptr;
1567 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1568 display->first_row);
1569 png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row);
1570 png_uint_16p row_end;
1571 unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1572 3 : 1;
1573 int aindex = 0;
1574 png_uint_32 y = image->height;
1576 if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1578 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1579 if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1581 aindex = -1;
1582 ++input_row; /* To point to the first component */
1583 ++output_row;
1585 else
1586 aindex = (int)channels;
1587 # else
1588 aindex = (int)channels;
1589 # endif
1592 else
1593 png_error(png_ptr, "png_write_image: internal call error");
1595 /* Work out the output row end and count over this, note that the increment
1596 * above to 'row' means that row_end can actually be beyond the end of the
1597 * row; this is correct.
1599 row_end = output_row + image->width * (channels+1);
1601 for (; y > 0; --y)
1603 png_const_uint_16p in_ptr = input_row;
1604 png_uint_16p out_ptr = output_row;
1606 while (out_ptr < row_end)
1608 png_uint_16 alpha = in_ptr[aindex];
1609 png_uint_32 reciprocal = 0;
1610 int c;
1612 out_ptr[aindex] = alpha;
1614 /* Calculate a reciprocal. The correct calculation is simply
1615 * component/alpha*65535 << 15. (I.e. 15 bits of precision); this
1616 * allows correct rounding by adding .5 before the shift. 'reciprocal'
1617 * is only initialized when required.
1619 if (alpha > 0 && alpha < 65535)
1620 reciprocal = ((0xffff<<15)+(alpha>>1))/alpha;
1622 c = (int)channels;
1623 do /* always at least one channel */
1625 png_uint_16 component = *in_ptr++;
1627 /* The following gives 65535 for an alpha of 0, which is fine,
1628 * otherwise if 0/0 is represented as some other value there is more
1629 * likely to be a discontinuity which will probably damage
1630 * compression when moving from a fully transparent area to a
1631 * nearly transparent one. (The assumption here is that opaque
1632 * areas tend not to be 0 intensity.)
1634 if (component >= alpha)
1635 component = 65535;
1637 /* component<alpha, so component/alpha is less than one and
1638 * component*reciprocal is less than 2^31.
1640 else if (component > 0 && alpha < 65535)
1642 png_uint_32 calc = component * reciprocal;
1643 calc += 16384; /* round to nearest */
1644 component = (png_uint_16)(calc >> 15);
1647 *out_ptr++ = component;
1649 while (--c > 0);
1651 /* Skip to next component (skip the intervening alpha channel) */
1652 ++in_ptr;
1653 ++out_ptr;
1656 png_write_row(png_ptr, png_voidcast(png_const_bytep, display->local_row));
1657 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1660 return 1;
1663 /* Given 16-bit input (1 to 4 channels) write 8-bit output. If an alpha channel
1664 * is present it must be removed from the components, the components are then
1665 * written in sRGB encoding. No components are added or removed.
1667 * Calculate an alpha reciprocal to reverse pre-multiplication. As above the
1668 * calculation can be done to 15 bits of accuracy; however, the output needs to
1669 * be scaled in the range 0..255*65535, so include that scaling here.
1671 # define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+((alpha)>>1))/(alpha))
1673 static png_byte
1674 png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
1675 png_uint_32 reciprocal/*from the above macro*/)
1677 /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0
1678 * is represented as some other value there is more likely to be a
1679 * discontinuity which will probably damage compression when moving from a
1680 * fully transparent area to a nearly transparent one. (The assumption here
1681 * is that opaque areas tend not to be 0 intensity.)
1683 * There is a rounding problem here; if alpha is less than 128 it will end up
1684 * as 0 when scaled to 8 bits. To avoid introducing spurious colors into the
1685 * output change for this too.
1687 if (component >= alpha || alpha < 128)
1688 return 255;
1690 /* component<alpha, so component/alpha is less than one and
1691 * component*reciprocal is less than 2^31.
1693 else if (component > 0)
1695 /* The test is that alpha/257 (rounded) is less than 255, the first value
1696 * that becomes 255 is 65407.
1697 * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore,
1698 * be exact!) [Could also test reciprocal != 0]
1700 if (alpha < 65407)
1702 component *= reciprocal;
1703 component += 64; /* round to nearest */
1704 component >>= 7;
1707 else
1708 component *= 255;
1710 /* Convert the component to sRGB. */
1711 return (png_byte)PNG_sRGB_FROM_LINEAR(component);
1714 else
1715 return 0;
1718 static int
1719 png_write_image_8bit(png_voidp argument)
1721 png_image_write_control *display = png_voidcast(png_image_write_control*,
1722 argument);
1723 png_imagep image = display->image;
1724 png_structrp png_ptr = image->opaque->png_ptr;
1726 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1727 display->first_row);
1728 png_bytep output_row = png_voidcast(png_bytep, display->local_row);
1729 png_uint_32 y = image->height;
1730 unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1731 3 : 1;
1733 if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1735 png_bytep row_end;
1736 int aindex;
1738 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1739 if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1741 aindex = -1;
1742 ++input_row; /* To point to the first component */
1743 ++output_row;
1746 else
1747 # endif
1748 aindex = (int)channels;
1750 /* Use row_end in place of a loop counter: */
1751 row_end = output_row + image->width * (channels+1);
1753 for (; y > 0; --y)
1755 png_const_uint_16p in_ptr = input_row;
1756 png_bytep out_ptr = output_row;
1758 while (out_ptr < row_end)
1760 png_uint_16 alpha = in_ptr[aindex];
1761 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1762 png_uint_32 reciprocal = 0;
1763 int c;
1765 /* Scale and write the alpha channel. */
1766 out_ptr[aindex] = alphabyte;
1768 if (alphabyte > 0 && alphabyte < 255)
1769 reciprocal = UNP_RECIPROCAL(alpha);
1771 c = (int)channels;
1772 do /* always at least one channel */
1773 *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal);
1774 while (--c > 0);
1776 /* Skip to next component (skip the intervening alpha channel) */
1777 ++in_ptr;
1778 ++out_ptr;
1779 } /* while out_ptr < row_end */
1781 png_write_row(png_ptr, png_voidcast(png_const_bytep,
1782 display->local_row));
1783 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1784 } /* while y */
1787 else
1789 /* No alpha channel, so the row_end really is the end of the row and it
1790 * is sufficient to loop over the components one by one.
1792 png_bytep row_end = output_row + image->width * channels;
1794 for (; y > 0; --y)
1796 png_const_uint_16p in_ptr = input_row;
1797 png_bytep out_ptr = output_row;
1799 while (out_ptr < row_end)
1801 png_uint_32 component = *in_ptr++;
1803 component *= 255;
1804 *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component);
1807 png_write_row(png_ptr, output_row);
1808 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1812 return 1;
1815 static void
1816 png_image_set_PLTE(png_image_write_control *display)
1818 png_imagep image = display->image;
1819 const void *cmap = display->colormap;
1820 int entries = image->colormap_entries > 256 ? 256 :
1821 (int)image->colormap_entries;
1823 /* NOTE: the caller must check for cmap != NULL and entries != 0 */
1824 png_uint_32 format = image->format;
1825 unsigned int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
1827 # if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
1828 defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED)
1829 int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1830 (format & PNG_FORMAT_FLAG_ALPHA) != 0;
1831 # else
1832 # define afirst 0
1833 # endif
1835 # ifdef PNG_FORMAT_BGR_SUPPORTED
1836 int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1837 # else
1838 # define bgr 0
1839 # endif
1841 int i, num_trans;
1842 png_color palette[256];
1843 png_byte tRNS[256];
1845 memset(tRNS, 255, (sizeof tRNS));
1846 memset(palette, 0, (sizeof palette));
1848 for (i=num_trans=0; i<entries; ++i)
1850 /* This gets automatically converted to sRGB with reversal of the
1851 * pre-multiplication if the color-map has an alpha channel.
1853 if ((format & PNG_FORMAT_FLAG_LINEAR) != 0)
1855 png_const_uint_16p entry = png_voidcast(png_const_uint_16p, cmap);
1857 entry += (unsigned int)i * channels;
1859 if ((channels & 1) != 0) /* no alpha */
1861 if (channels >= 3) /* RGB */
1863 palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1864 entry[(2 ^ bgr)]);
1865 palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1866 entry[1]);
1867 palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1868 entry[bgr]);
1871 else /* Gray */
1872 palette[i].blue = palette[i].red = palette[i].green =
1873 (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry);
1876 else /* alpha */
1878 png_uint_16 alpha = entry[afirst ? 0 : channels-1];
1879 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1880 png_uint_32 reciprocal = 0;
1882 /* Calculate a reciprocal, as in the png_write_image_8bit code above
1883 * this is designed to produce a value scaled to 255*65535 when
1884 * divided by 128 (i.e. asr 7).
1886 if (alphabyte > 0 && alphabyte < 255)
1887 reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha;
1889 tRNS[i] = alphabyte;
1890 if (alphabyte < 255)
1891 num_trans = i+1;
1893 if (channels >= 3) /* RGB */
1895 palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)],
1896 alpha, reciprocal);
1897 palette[i].green = png_unpremultiply(entry[afirst + 1], alpha,
1898 reciprocal);
1899 palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha,
1900 reciprocal);
1903 else /* gray */
1904 palette[i].blue = palette[i].red = palette[i].green =
1905 png_unpremultiply(entry[afirst], alpha, reciprocal);
1909 else /* Color-map has sRGB values */
1911 png_const_bytep entry = png_voidcast(png_const_bytep, cmap);
1913 entry += (unsigned int)i * channels;
1915 switch (channels)
1917 case 4:
1918 tRNS[i] = entry[afirst ? 0 : 3];
1919 if (tRNS[i] < 255)
1920 num_trans = i+1;
1921 /* FALLTHROUGH */
1922 case 3:
1923 palette[i].blue = entry[afirst + (2 ^ bgr)];
1924 palette[i].green = entry[afirst + 1];
1925 palette[i].red = entry[afirst + bgr];
1926 break;
1928 case 2:
1929 tRNS[i] = entry[1 ^ afirst];
1930 if (tRNS[i] < 255)
1931 num_trans = i+1;
1932 /* FALLTHROUGH */
1933 case 1:
1934 palette[i].blue = palette[i].red = palette[i].green =
1935 entry[afirst];
1936 break;
1938 default:
1939 break;
1944 # ifdef afirst
1945 # undef afirst
1946 # endif
1947 # ifdef bgr
1948 # undef bgr
1949 # endif
1951 png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
1952 entries);
1954 if (num_trans > 0)
1955 png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS,
1956 num_trans, NULL);
1958 image->colormap_entries = (png_uint_32)entries;
1961 static int
1962 png_image_write_main(png_voidp argument)
1964 png_image_write_control *display = png_voidcast(png_image_write_control*,
1965 argument);
1966 png_imagep image = display->image;
1967 png_structrp png_ptr = image->opaque->png_ptr;
1968 png_inforp info_ptr = image->opaque->info_ptr;
1969 png_uint_32 format = image->format;
1971 /* The following four ints are actually booleans */
1972 int colormap = (format & PNG_FORMAT_FLAG_COLORMAP);
1973 int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR); /* input */
1974 int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA);
1975 int write_16bit = linear && (display->convert_to_8bit == 0);
1977 # ifdef PNG_BENIGN_ERRORS_SUPPORTED
1978 /* Make sure we error out on any bad situation */
1979 png_set_benign_errors(png_ptr, 0/*error*/);
1980 # endif
1982 /* Default the 'row_stride' parameter if required, also check the row stride
1983 * and total image size to ensure that they are within the system limits.
1986 unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
1988 if (image->width <= 0x7fffffffU/channels) /* no overflow */
1990 png_uint_32 check;
1991 png_uint_32 png_row_stride = image->width * channels;
1993 if (display->row_stride == 0)
1994 display->row_stride = (png_int_32)/*SAFE*/png_row_stride;
1996 if (display->row_stride < 0)
1997 check = (png_uint_32)(-display->row_stride);
1999 else
2000 check = (png_uint_32)display->row_stride;
2002 if (check >= png_row_stride)
2004 /* Now check for overflow of the image buffer calculation; this
2005 * limits the whole image size to 32 bits for API compatibility with
2006 * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
2008 if (image->height > 0xffffffffU/png_row_stride)
2009 png_error(image->opaque->png_ptr, "memory image too large");
2012 else
2013 png_error(image->opaque->png_ptr, "supplied row stride too small");
2016 else
2017 png_error(image->opaque->png_ptr, "image row stride too large");
2020 /* Set the required transforms then write the rows in the correct order. */
2021 if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0)
2023 if (display->colormap != NULL && image->colormap_entries > 0)
2025 png_uint_32 entries = image->colormap_entries;
2027 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2028 entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)),
2029 PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
2030 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2032 png_image_set_PLTE(display);
2035 else
2036 png_error(image->opaque->png_ptr,
2037 "no color-map for color-mapped image");
2040 else
2041 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2042 write_16bit ? 16 : 8,
2043 ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) +
2044 ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0),
2045 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2047 /* Counter-intuitively the data transformations must be called *after*
2048 * png_write_info, not before as in the read code, but the 'set' functions
2049 * must still be called before. Just set the color space information, never
2050 * write an interlaced image.
2053 if (write_16bit != 0)
2055 /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */
2056 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR);
2058 if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2059 png_set_cHRM_fixed(png_ptr, info_ptr,
2060 /* color x y */
2061 /* white */ 31270, 32900,
2062 /* red */ 64000, 33000,
2063 /* green */ 30000, 60000,
2064 /* blue */ 15000, 6000
2068 else if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2069 png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);
2071 /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit
2072 * space must still be gamma encoded.
2074 else
2075 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE);
2077 /* Write the file header. */
2078 png_write_info(png_ptr, info_ptr);
2080 /* Now set up the data transformations (*after* the header is written),
2081 * remove the handled transformations from the 'format' flags for checking.
2083 * First check for a little endian system if writing 16-bit files.
2085 if (write_16bit != 0)
2087 png_uint_16 le = 0x0001;
2089 if ((*(png_const_bytep) & le) != 0)
2090 png_set_swap(png_ptr);
2093 # ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
2094 if ((format & PNG_FORMAT_FLAG_BGR) != 0)
2096 if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0)
2097 png_set_bgr(png_ptr);
2098 format &= ~PNG_FORMAT_FLAG_BGR;
2100 # endif
2102 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
2103 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
2105 if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
2106 png_set_swap_alpha(png_ptr);
2107 format &= ~PNG_FORMAT_FLAG_AFIRST;
2109 # endif
2111 /* If there are 16 or fewer color-map entries we wrote a lower bit depth
2112 * above, but the application data is still byte packed.
2114 if (colormap != 0 && image->colormap_entries <= 16)
2115 png_set_packing(png_ptr);
2117 /* That should have handled all (both) the transforms. */
2118 if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR |
2119 PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0)
2120 png_error(png_ptr, "png_write_image: unsupported transformation");
2123 png_const_bytep row = png_voidcast(png_const_bytep, display->buffer);
2124 ptrdiff_t row_bytes = display->row_stride;
2126 if (linear != 0)
2127 row_bytes *= (sizeof (png_uint_16));
2129 if (row_bytes < 0)
2130 row += (image->height-1) * (-row_bytes);
2132 display->first_row = row;
2133 display->row_bytes = row_bytes;
2136 /* Apply 'fast' options if the flag is set. */
2137 if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0)
2139 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS);
2140 /* NOTE: determined by experiment using pngstest, this reflects some
2141 * balance between the time to write the image once and the time to read
2142 * it about 50 times. The speed-up in pngstest was about 10-20% of the
2143 * total (user) time on a heavily loaded system.
2145 # ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
2146 png_set_compression_level(png_ptr, 3);
2147 # endif
2150 /* Check for the cases that currently require a pre-transform on the row
2151 * before it is written. This only applies when the input is 16-bit and
2152 * either there is an alpha channel or it is converted to 8-bit.
2154 if ((linear != 0 && alpha != 0 ) ||
2155 (colormap == 0 && display->convert_to_8bit != 0))
2157 png_bytep row = png_voidcast(png_bytep, png_malloc(png_ptr,
2158 png_get_rowbytes(png_ptr, info_ptr)));
2159 int result;
2161 display->local_row = row;
2162 if (write_16bit != 0)
2163 result = png_safe_execute(image, png_write_image_16bit, display);
2164 else
2165 result = png_safe_execute(image, png_write_image_8bit, display);
2166 display->local_row = NULL;
2168 png_free(png_ptr, row);
2170 /* Skip the 'write_end' on error: */
2171 if (result == 0)
2172 return 0;
2175 /* Otherwise this is the case where the input is in a format currently
2176 * supported by the rest of the libpng write code; call it directly.
2178 else
2180 png_const_bytep row = png_voidcast(png_const_bytep, display->first_row);
2181 ptrdiff_t row_bytes = display->row_bytes;
2182 png_uint_32 y = image->height;
2184 for (; y > 0; --y)
2186 png_write_row(png_ptr, row);
2187 row += row_bytes;
2191 png_write_end(png_ptr, info_ptr);
2192 return 1;
2196 static void (PNGCBAPI
2197 image_memory_write)(png_structp png_ptr, png_bytep/*const*/ data, size_t size)
2199 png_image_write_control *display = png_voidcast(png_image_write_control*,
2200 png_ptr->io_ptr/*backdoor: png_get_io_ptr(png_ptr)*/);
2201 png_alloc_size_t ob = display->output_bytes;
2203 /* Check for overflow; this should never happen: */
2204 if (size <= ((png_alloc_size_t)-1) - ob)
2206 /* I don't think libpng ever does this, but just in case: */
2207 if (size > 0)
2209 if (display->memory_bytes >= ob+size) /* writing */
2210 memcpy(display->memory+ob, data, size);
2212 /* Always update the size: */
2213 display->output_bytes = ob+size;
2217 else
2218 png_error(png_ptr, "png_image_write_to_memory: PNG too big");
2221 static void (PNGCBAPI
2222 image_memory_flush)(png_structp png_ptr)
2224 PNG_UNUSED(png_ptr)
2227 static int
2228 png_image_write_memory(png_voidp argument)
2230 png_image_write_control *display = png_voidcast(png_image_write_control*,
2231 argument);
2233 /* The rest of the memory-specific init and write_main in an error protected
2234 * environment. This case needs to use callbacks for the write operations
2235 * since libpng has no built in support for writing to memory.
2237 png_set_write_fn(display->image->opaque->png_ptr, display/*io_ptr*/,
2238 image_memory_write, image_memory_flush);
2240 return png_image_write_main(display);
2243 int PNGAPI
2244 png_image_write_to_memory(png_imagep image, void *memory,
2245 png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8bit,
2246 const void *buffer, png_int_32 row_stride, const void *colormap)
2248 /* Write the image to the given buffer, or count the bytes if it is NULL */
2249 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2251 if (memory_bytes != NULL && buffer != NULL)
2253 /* This is to give the caller an easier error detection in the NULL
2254 * case and guard against uninitialized variable problems:
2256 if (memory == NULL)
2257 *memory_bytes = 0;
2259 if (png_image_write_init(image) != 0)
2261 png_image_write_control display;
2262 int result;
2264 memset(&display, 0, (sizeof display));
2265 display.image = image;
2266 display.buffer = buffer;
2267 display.row_stride = row_stride;
2268 display.colormap = colormap;
2269 display.convert_to_8bit = convert_to_8bit;
2270 display.memory = png_voidcast(png_bytep, memory);
2271 display.memory_bytes = *memory_bytes;
2272 display.output_bytes = 0;
2274 result = png_safe_execute(image, png_image_write_memory, &display);
2275 png_image_free(image);
2277 /* write_memory returns true even if we ran out of buffer. */
2278 if (result)
2280 /* On out-of-buffer this function returns '0' but still updates
2281 * memory_bytes:
2283 if (memory != NULL && display.output_bytes > *memory_bytes)
2284 result = 0;
2286 *memory_bytes = display.output_bytes;
2289 return result;
2292 else
2293 return 0;
2296 else
2297 return png_image_error(image,
2298 "png_image_write_to_memory: invalid argument");
2301 else if (image != NULL)
2302 return png_image_error(image,
2303 "png_image_write_to_memory: incorrect PNG_IMAGE_VERSION");
2305 else
2306 return 0;
2309 #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
2310 int PNGAPI
2311 png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit,
2312 const void *buffer, png_int_32 row_stride, const void *colormap)
2314 /* Write the image to the given (FILE*). */
2315 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2317 if (file != NULL && buffer != NULL)
2319 if (png_image_write_init(image) != 0)
2321 png_image_write_control display;
2322 int result;
2324 /* This is slightly evil, but png_init_io doesn't do anything other
2325 * than this and we haven't changed the standard IO functions so
2326 * this saves a 'safe' function.
2328 image->opaque->png_ptr->io_ptr = file;
2330 memset(&display, 0, (sizeof display));
2331 display.image = image;
2332 display.buffer = buffer;
2333 display.row_stride = row_stride;
2334 display.colormap = colormap;
2335 display.convert_to_8bit = convert_to_8bit;
2337 result = png_safe_execute(image, png_image_write_main, &display);
2338 png_image_free(image);
2339 return result;
2342 else
2343 return 0;
2346 else
2347 return png_image_error(image,
2348 "png_image_write_to_stdio: invalid argument");
2351 else if (image != NULL)
2352 return png_image_error(image,
2353 "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION");
2355 else
2356 return 0;
2359 int PNGAPI
2360 png_image_write_to_file(png_imagep image, const char *file_name,
2361 int convert_to_8bit, const void *buffer, png_int_32 row_stride,
2362 const void *colormap)
2364 /* Write the image to the named file. */
2365 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2367 if (file_name != NULL && buffer != NULL)
2369 FILE *fp = fopen(file_name, "wb");
2371 if (fp != NULL)
2373 if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer,
2374 row_stride, colormap) != 0)
2376 int error; /* from fflush/fclose */
2378 /* Make sure the file is flushed correctly. */
2379 if (fflush(fp) == 0 && ferror(fp) == 0)
2381 if (fclose(fp) == 0)
2382 return 1;
2384 error = errno; /* from fclose */
2387 else
2389 error = errno; /* from fflush or ferror */
2390 (void)fclose(fp);
2393 (void)remove(file_name);
2394 /* The image has already been cleaned up; this is just used to
2395 * set the error (because the original write succeeded).
2397 return png_image_error(image, strerror(error));
2400 else
2402 /* Clean up: just the opened file. */
2403 (void)fclose(fp);
2404 (void)remove(file_name);
2405 return 0;
2409 else
2410 return png_image_error(image, strerror(errno));
2413 else
2414 return png_image_error(image,
2415 "png_image_write_to_file: invalid argument");
2418 else if (image != NULL)
2419 return png_image_error(image,
2420 "png_image_write_to_file: incorrect PNG_IMAGE_VERSION");
2422 else
2423 return 0;
2425 #endif /* SIMPLIFIED_WRITE_STDIO */
2426 #endif /* SIMPLIFIED_WRITE */
2428 #ifdef PNG_WRITE_APNG_SUPPORTED
2429 void PNGAPI
2430 png_write_frame_head(png_structp png_ptr, png_infop info_ptr,
2431 png_bytepp row_pointers, png_uint_32 width, png_uint_32 height,
2432 png_uint_32 x_offset, png_uint_32 y_offset,
2433 png_uint_16 delay_num, png_uint_16 delay_den, png_byte dispose_op,
2434 png_byte blend_op)
2436 png_debug(1, "in png_write_frame_head");
2438 /* there is a chance this has been set after png_write_info was called,
2439 * so it would be set but not written. is there a way to be sure? */
2440 if ((info_ptr->valid & PNG_INFO_acTL) == 0)
2441 png_error(png_ptr, "png_write_frame_head(): acTL not set");
2443 png_write_reset(png_ptr);
2445 png_write_reinit(png_ptr, info_ptr, width, height);
2447 if ((png_ptr->apng_flags & PNG_FIRST_FRAME_HIDDEN) == 0 ||
2448 png_ptr->num_frames_written != 0)
2449 png_write_fcTL(png_ptr, width, height, x_offset, y_offset,
2450 delay_num, delay_den, dispose_op, blend_op);
2452 PNG_UNUSED(row_pointers)
2455 void PNGAPI
2456 png_write_frame_tail(png_structp png_ptr, png_infop info_ptr)
2458 png_debug(1, "in png_write_frame_tail");
2460 png_ptr->num_frames_written++;
2462 PNG_UNUSED(info_ptr)
2464 #endif /* WRITE_APNG */
2465 #endif /* WRITE */