Bug 946178 - Disable test_outgoing_radio_off.js to see if it fixes Mnw and lets us...
[gecko.git] / media / libpng / pngwrite.c
blob5df53126e52eb34c6ff040c098cd6803f462e973
2 /* pngwrite.c - general routines to write a PNG file
4 * Last changed in libpng 1.6.2 [April 25, 2013]
5 * Copyright (c) 1998-2013 Glenn Randers-Pehrson
6 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7 * (Version 0.88 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 #if defined(PNG_SIMPLIFIED_WRITE_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
16 # include <errno.h>
17 #endif
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)
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)
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 /* PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED */
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.
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))
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) && \
98 (png_ptr->mng_features_permitted))
100 png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
101 png_ptr->mng_features_permitted = 0;
103 #endif
105 /* Write IHDR information. */
106 png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
107 info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
108 info_ptr->filter_type,
109 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
110 info_ptr->interlace_type
111 #else
113 #endif
116 /* The rest of these check to see if the valid field has the appropriate
117 * flag set, and if it does, writes the chunk.
119 * 1.6.0: COLORSPACE support controls the writing of these chunks too, and
120 * the chunks will be written if the WRITE routine is there and information
121 * is available in the COLORSPACE. (See png_colorspace_sync_info in png.c
122 * for where the valid flags get set.)
124 * Under certain circumstances the colorspace can be invalidated without
125 * syncing the info_struct 'valid' flags; this happens if libpng detects and
126 * error and calls png_error while the color space is being set, yet the
127 * application continues writing the PNG. So check the 'invalid' flag here
128 * too.
130 #ifdef PNG_WRITE_APNG_SUPPORTED
131 if (info_ptr->valid & PNG_INFO_acTL)
132 png_write_acTL(png_ptr, info_ptr->num_frames, info_ptr->num_plays);
133 #endif
134 #ifdef PNG_GAMMA_SUPPORTED
135 # ifdef PNG_WRITE_gAMA_SUPPORTED
136 if (!(info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) &&
137 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_gAMA) &&
138 (info_ptr->valid & PNG_INFO_gAMA))
139 png_write_gAMA_fixed(png_ptr, info_ptr->colorspace.gamma);
140 # endif
141 #endif
143 #ifdef PNG_COLORSPACE_SUPPORTED
144 /* Write only one of sRGB or an ICC profile. If a profile was supplied
145 * and it matches one of the known sRGB ones issue a warning.
147 # ifdef PNG_WRITE_iCCP_SUPPORTED
148 if (!(info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) &&
149 (info_ptr->valid & PNG_INFO_iCCP))
151 # ifdef PNG_WRITE_sRGB_SUPPORTED
152 if (info_ptr->valid & PNG_INFO_sRGB)
153 png_app_warning(png_ptr,
154 "profile matches sRGB but writing iCCP instead");
155 # endif
157 png_write_iCCP(png_ptr, info_ptr->iccp_name,
158 info_ptr->iccp_profile);
160 # ifdef PNG_WRITE_sRGB_SUPPORTED
161 else
162 # endif
163 # endif
165 # ifdef PNG_WRITE_sRGB_SUPPORTED
166 if (!(info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) &&
167 (info_ptr->valid & PNG_INFO_sRGB))
168 png_write_sRGB(png_ptr, info_ptr->colorspace.rendering_intent);
169 # endif /* WRITE_sRGB */
170 #endif /* COLORSPACE */
172 #ifdef PNG_WRITE_sBIT_SUPPORTED
173 if (info_ptr->valid & PNG_INFO_sBIT)
174 png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
175 #endif
177 #ifdef PNG_COLORSPACE_SUPPORTED
178 # ifdef PNG_WRITE_cHRM_SUPPORTED
179 if (!(info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) &&
180 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) &&
181 (info_ptr->valid & PNG_INFO_cHRM))
182 png_write_cHRM_fixed(png_ptr, &info_ptr->colorspace.end_points_xy);
183 # endif
184 #endif
186 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
187 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
188 #endif
190 png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
194 void PNGAPI
195 png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
197 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
198 int i;
199 #endif
201 png_debug(1, "in png_write_info");
203 if (png_ptr == NULL || info_ptr == NULL)
204 return;
206 png_write_info_before_PLTE(png_ptr, info_ptr);
208 if (info_ptr->valid & PNG_INFO_PLTE)
209 png_write_PLTE(png_ptr, info_ptr->palette,
210 (png_uint_32)info_ptr->num_palette);
212 else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
213 png_error(png_ptr, "Valid palette required for paletted images");
215 #ifdef PNG_WRITE_tRNS_SUPPORTED
216 if (info_ptr->valid & PNG_INFO_tRNS)
218 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
219 /* Invert the alpha channel (in tRNS) */
220 if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
221 info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
223 int j;
224 for (j = 0; j<(int)info_ptr->num_trans; j++)
225 info_ptr->trans_alpha[j] =
226 (png_byte)(255 - info_ptr->trans_alpha[j]);
228 #endif
229 png_write_tRNS(png_ptr, info_ptr->trans_alpha, &(info_ptr->trans_color),
230 info_ptr->num_trans, info_ptr->color_type);
232 #endif
233 #ifdef PNG_WRITE_bKGD_SUPPORTED
234 if (info_ptr->valid & PNG_INFO_bKGD)
235 png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
236 #endif
238 #ifdef PNG_WRITE_hIST_SUPPORTED
239 if (info_ptr->valid & PNG_INFO_hIST)
240 png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
241 #endif
243 #ifdef PNG_WRITE_oFFs_SUPPORTED
244 if (info_ptr->valid & PNG_INFO_oFFs)
245 png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
246 info_ptr->offset_unit_type);
247 #endif
249 #ifdef PNG_WRITE_pCAL_SUPPORTED
250 if (info_ptr->valid & PNG_INFO_pCAL)
251 png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
252 info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
253 info_ptr->pcal_units, info_ptr->pcal_params);
254 #endif
256 #ifdef PNG_WRITE_sCAL_SUPPORTED
257 if (info_ptr->valid & PNG_INFO_sCAL)
258 png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
259 info_ptr->scal_s_width, info_ptr->scal_s_height);
260 #endif /* sCAL */
262 #ifdef PNG_WRITE_pHYs_SUPPORTED
263 if (info_ptr->valid & PNG_INFO_pHYs)
264 png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
265 info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
266 #endif /* pHYs */
268 #ifdef PNG_WRITE_tIME_SUPPORTED
269 if (info_ptr->valid & PNG_INFO_tIME)
271 png_write_tIME(png_ptr, &(info_ptr->mod_time));
272 png_ptr->mode |= PNG_WROTE_tIME;
274 #endif /* tIME */
276 #ifdef PNG_WRITE_sPLT_SUPPORTED
277 if (info_ptr->valid & PNG_INFO_sPLT)
278 for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
279 png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
280 #endif /* sPLT */
282 #ifdef PNG_WRITE_TEXT_SUPPORTED
283 /* Check to see if we need to write text chunks */
284 for (i = 0; i < info_ptr->num_text; i++)
286 png_debug2(2, "Writing header text chunk %d, type %d", i,
287 info_ptr->text[i].compression);
288 /* An internationalized chunk? */
289 if (info_ptr->text[i].compression > 0)
291 #ifdef PNG_WRITE_iTXt_SUPPORTED
292 /* Write international chunk */
293 png_write_iTXt(png_ptr,
294 info_ptr->text[i].compression,
295 info_ptr->text[i].key,
296 info_ptr->text[i].lang,
297 info_ptr->text[i].lang_key,
298 info_ptr->text[i].text);
299 #else
300 png_warning(png_ptr, "Unable to write international text");
301 #endif
302 /* Mark this chunk as written */
303 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
306 /* If we want a compressed text chunk */
307 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
309 #ifdef PNG_WRITE_zTXt_SUPPORTED
310 /* Write compressed chunk */
311 png_write_zTXt(png_ptr, info_ptr->text[i].key,
312 info_ptr->text[i].text, 0,
313 info_ptr->text[i].compression);
314 #else
315 png_warning(png_ptr, "Unable to write compressed text");
316 #endif
317 /* Mark this chunk as written */
318 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
321 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
323 #ifdef PNG_WRITE_tEXt_SUPPORTED
324 /* Write uncompressed chunk */
325 png_write_tEXt(png_ptr, info_ptr->text[i].key,
326 info_ptr->text[i].text,
328 /* Mark this chunk as written */
329 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
330 #else
331 /* Can't get here */
332 png_warning(png_ptr, "Unable to write uncompressed text");
333 #endif
336 #endif /* tEXt */
338 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
339 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE);
340 #endif
343 /* Writes the end of the PNG file. If you don't want to write comments or
344 * time information, you can pass NULL for info. If you already wrote these
345 * in png_write_info(), do not write them again here. If you have long
346 * comments, I suggest writing them here, and compressing them.
348 void PNGAPI
349 png_write_end(png_structrp png_ptr, png_inforp info_ptr)
351 png_debug(1, "in png_write_end");
353 if (png_ptr == NULL)
354 return;
356 if (!(png_ptr->mode & PNG_HAVE_IDAT))
357 png_error(png_ptr, "No IDATs written into file");
359 #ifdef PNG_WRITE_APNG_SUPPORTED
360 if (png_ptr->num_frames_written != png_ptr->num_frames_to_write)
361 png_error(png_ptr, "Not enough frames written");
362 #endif
364 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
365 if (png_ptr->num_palette_max > png_ptr->num_palette)
366 png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
367 #endif
369 /* See if user wants us to write information chunks */
370 if (info_ptr != NULL)
372 #ifdef PNG_WRITE_TEXT_SUPPORTED
373 int i; /* local index variable */
374 #endif
375 #ifdef PNG_WRITE_tIME_SUPPORTED
376 /* Check to see if user has supplied a time chunk */
377 if ((info_ptr->valid & PNG_INFO_tIME) &&
378 !(png_ptr->mode & PNG_WROTE_tIME))
379 png_write_tIME(png_ptr, &(info_ptr->mod_time));
381 #endif
382 #ifdef PNG_WRITE_TEXT_SUPPORTED
383 /* Loop through comment chunks */
384 for (i = 0; i < info_ptr->num_text; i++)
386 png_debug2(2, "Writing trailer text chunk %d, type %d", i,
387 info_ptr->text[i].compression);
388 /* An internationalized chunk? */
389 if (info_ptr->text[i].compression > 0)
391 #ifdef PNG_WRITE_iTXt_SUPPORTED
392 /* Write international chunk */
393 png_write_iTXt(png_ptr,
394 info_ptr->text[i].compression,
395 info_ptr->text[i].key,
396 info_ptr->text[i].lang,
397 info_ptr->text[i].lang_key,
398 info_ptr->text[i].text);
399 #else
400 png_warning(png_ptr, "Unable to write international text");
401 #endif
402 /* Mark this chunk as written */
403 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
406 else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
408 #ifdef PNG_WRITE_zTXt_SUPPORTED
409 /* Write compressed chunk */
410 png_write_zTXt(png_ptr, info_ptr->text[i].key,
411 info_ptr->text[i].text, 0,
412 info_ptr->text[i].compression);
413 #else
414 png_warning(png_ptr, "Unable to write compressed text");
415 #endif
416 /* Mark this chunk as written */
417 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
420 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
422 #ifdef PNG_WRITE_tEXt_SUPPORTED
423 /* Write uncompressed chunk */
424 png_write_tEXt(png_ptr, info_ptr->text[i].key,
425 info_ptr->text[i].text, 0);
426 #else
427 png_warning(png_ptr, "Unable to write uncompressed text");
428 #endif
430 /* Mark this chunk as written */
431 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
434 #endif
435 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
436 write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT);
437 #endif
440 png_ptr->mode |= PNG_AFTER_IDAT;
442 /* Write end of PNG file */
443 png_write_IEND(png_ptr);
444 /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03,
445 * and restored again in libpng-1.2.30, may cause some applications that
446 * do not set png_ptr->output_flush_fn to crash. If your application
447 * experiences a problem, please try building libpng with
448 * PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED defined, and report the event to
449 * png-mng-implement at lists.sf.net .
451 #ifdef PNG_WRITE_FLUSH_SUPPORTED
452 # ifdef PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED
453 png_flush(png_ptr);
454 # endif
455 #endif
458 #ifdef PNG_CONVERT_tIME_SUPPORTED
459 void PNGAPI
460 png_convert_from_struct_tm(png_timep ptime, PNG_CONST struct tm * ttime)
462 png_debug(1, "in png_convert_from_struct_tm");
464 ptime->year = (png_uint_16)(1900 + ttime->tm_year);
465 ptime->month = (png_byte)(ttime->tm_mon + 1);
466 ptime->day = (png_byte)ttime->tm_mday;
467 ptime->hour = (png_byte)ttime->tm_hour;
468 ptime->minute = (png_byte)ttime->tm_min;
469 ptime->second = (png_byte)ttime->tm_sec;
472 void PNGAPI
473 png_convert_from_time_t(png_timep ptime, time_t ttime)
475 struct tm *tbuf;
477 png_debug(1, "in png_convert_from_time_t");
479 tbuf = gmtime(&ttime);
480 png_convert_from_struct_tm(ptime, tbuf);
482 #endif
484 /* Initialize png_ptr structure, and allocate any memory needed */
485 PNG_FUNCTION(png_structp,PNGAPI
486 png_create_write_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
487 png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
489 #ifndef PNG_USER_MEM_SUPPORTED
490 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
491 error_fn, warn_fn, NULL, NULL, NULL);
492 #else
493 return png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
494 warn_fn, NULL, NULL, NULL);
497 /* Alternate initialize png_ptr structure, and allocate any memory needed */
498 PNG_FUNCTION(png_structp,PNGAPI
499 png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
500 png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
501 png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
503 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
504 error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
505 #endif /* PNG_USER_MEM_SUPPORTED */
506 if (png_ptr != NULL)
508 /* Set the zlib control values to defaults; they can be overridden by the
509 * application after the struct has been created.
511 png_ptr->zbuffer_size = PNG_ZBUF_SIZE;
513 /* The 'zlib_strategy' setting is irrelevant because png_default_claim in
514 * pngwutil.c defaults it according to whether or not filters will be
515 * used, and ignores this setting.
517 png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY;
518 png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION;
519 png_ptr->zlib_mem_level = 8;
520 png_ptr->zlib_window_bits = 15;
521 png_ptr->zlib_method = 8;
523 #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
524 png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY;
525 png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION;
526 png_ptr->zlib_text_mem_level = 8;
527 png_ptr->zlib_text_window_bits = 15;
528 png_ptr->zlib_text_method = 8;
529 #endif /* PNG_WRITE_COMPRESSED_TEXT_SUPPORTED */
531 /* This is a highly dubious configuration option; by default it is off,
532 * but it may be appropriate for private builds that are testing
533 * extensions not conformant to the current specification, or of
534 * applications that must not fail to write at all costs!
536 #ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED
537 png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
538 /* In stable builds only warn if an application error can be completely
539 * handled.
541 #endif
543 /* App warnings are warnings in release (or release candidate) builds but
544 * are errors during development.
546 #if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
547 png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
548 #endif
550 /* TODO: delay this, it can be done in png_init_io() (if the app doesn't
551 * do it itself) avoiding setting the default function if it is not
552 * required.
554 png_set_write_fn(png_ptr, NULL, NULL, NULL);
557 return png_ptr;
561 /* Write a few rows of image data. If the image is interlaced,
562 * either you will have to write the 7 sub images, or, if you
563 * have called png_set_interlace_handling(), you will have to
564 * "write" the image seven times.
566 void PNGAPI
567 png_write_rows(png_structrp png_ptr, png_bytepp row,
568 png_uint_32 num_rows)
570 png_uint_32 i; /* row counter */
571 png_bytepp rp; /* row pointer */
573 png_debug(1, "in png_write_rows");
575 if (png_ptr == NULL)
576 return;
578 /* Loop through the rows */
579 for (i = 0, rp = row; i < num_rows; i++, rp++)
581 png_write_row(png_ptr, *rp);
585 /* Write the image. You only need to call this function once, even
586 * if you are writing an interlaced image.
588 void PNGAPI
589 png_write_image(png_structrp png_ptr, png_bytepp image)
591 png_uint_32 i; /* row index */
592 int pass, num_pass; /* pass variables */
593 png_bytepp rp; /* points to current row */
595 if (png_ptr == NULL)
596 return;
598 png_debug(1, "in png_write_image");
600 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
601 /* Initialize interlace handling. If image is not interlaced,
602 * this will set pass to 1
604 num_pass = png_set_interlace_handling(png_ptr);
605 #else
606 num_pass = 1;
607 #endif
608 /* Loop through passes */
609 for (pass = 0; pass < num_pass; pass++)
611 /* Loop through image */
612 for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
614 png_write_row(png_ptr, *rp);
619 /* Called by user to write a row of image data */
620 void PNGAPI
621 png_write_row(png_structrp png_ptr, png_const_bytep row)
623 /* 1.5.6: moved from png_struct to be a local structure: */
624 png_row_info row_info;
626 if (png_ptr == NULL)
627 return;
629 png_debug2(1, "in png_write_row (row %u, pass %d)",
630 png_ptr->row_number, png_ptr->pass);
632 /* Initialize transformations and other stuff if first time */
633 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
635 /* Make sure we wrote the header info */
636 if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
637 png_error(png_ptr,
638 "png_write_info was never called before png_write_row");
640 /* Check for transforms that have been set but were defined out */
641 #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
642 if (png_ptr->transformations & PNG_INVERT_MONO)
643 png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined");
644 #endif
646 #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
647 if (png_ptr->transformations & PNG_FILLER)
648 png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined");
649 #endif
650 #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
651 defined(PNG_READ_PACKSWAP_SUPPORTED)
652 if (png_ptr->transformations & PNG_PACKSWAP)
653 png_warning(png_ptr,
654 "PNG_WRITE_PACKSWAP_SUPPORTED is not defined");
655 #endif
657 #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
658 if (png_ptr->transformations & PNG_PACK)
659 png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined");
660 #endif
662 #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
663 if (png_ptr->transformations & PNG_SHIFT)
664 png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined");
665 #endif
667 #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
668 if (png_ptr->transformations & PNG_BGR)
669 png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined");
670 #endif
672 #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
673 if (png_ptr->transformations & PNG_SWAP_BYTES)
674 png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined");
675 #endif
677 png_write_start_row(png_ptr);
680 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
681 /* If interlaced and not interested in row, return */
682 if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
684 switch (png_ptr->pass)
686 case 0:
687 if (png_ptr->row_number & 0x07)
689 png_write_finish_row(png_ptr);
690 return;
692 break;
694 case 1:
695 if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
697 png_write_finish_row(png_ptr);
698 return;
700 break;
702 case 2:
703 if ((png_ptr->row_number & 0x07) != 4)
705 png_write_finish_row(png_ptr);
706 return;
708 break;
710 case 3:
711 if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
713 png_write_finish_row(png_ptr);
714 return;
716 break;
718 case 4:
719 if ((png_ptr->row_number & 0x03) != 2)
721 png_write_finish_row(png_ptr);
722 return;
724 break;
726 case 5:
727 if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
729 png_write_finish_row(png_ptr);
730 return;
732 break;
734 case 6:
735 if (!(png_ptr->row_number & 0x01))
737 png_write_finish_row(png_ptr);
738 return;
740 break;
742 default: /* error: ignore it */
743 break;
746 #endif
748 /* Set up row info for transformations */
749 row_info.color_type = png_ptr->color_type;
750 row_info.width = png_ptr->usr_width;
751 row_info.channels = png_ptr->usr_channels;
752 row_info.bit_depth = png_ptr->usr_bit_depth;
753 row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels);
754 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
756 png_debug1(3, "row_info->color_type = %d", row_info.color_type);
757 png_debug1(3, "row_info->width = %u", row_info.width);
758 png_debug1(3, "row_info->channels = %d", row_info.channels);
759 png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth);
760 png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth);
761 png_debug1(3, "row_info->rowbytes = %lu", (unsigned long)row_info.rowbytes);
763 /* Copy user's row into buffer, leaving room for filter byte. */
764 memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes);
766 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
767 /* Handle interlacing */
768 if (png_ptr->interlaced && png_ptr->pass < 6 &&
769 (png_ptr->transformations & PNG_INTERLACE))
771 png_do_write_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass);
772 /* This should always get caught above, but still ... */
773 if (!(row_info.width))
775 png_write_finish_row(png_ptr);
776 return;
779 #endif
781 #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
782 /* Handle other transformations */
783 if (png_ptr->transformations)
784 png_do_write_transformations(png_ptr, &row_info);
785 #endif
787 /* At this point the row_info pixel depth must match the 'transformed' depth,
788 * which is also the output depth.
790 if (row_info.pixel_depth != png_ptr->pixel_depth ||
791 row_info.pixel_depth != png_ptr->transformed_pixel_depth)
792 png_error(png_ptr, "internal write transform logic error");
794 #ifdef PNG_MNG_FEATURES_SUPPORTED
795 /* Write filter_method 64 (intrapixel differencing) only if
796 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
797 * 2. Libpng did not write a PNG signature (this filter_method is only
798 * used in PNG datastreams that are embedded in MNG datastreams) and
799 * 3. The application called png_permit_mng_features with a mask that
800 * included PNG_FLAG_MNG_FILTER_64 and
801 * 4. The filter_method is 64 and
802 * 5. The color_type is RGB or RGBA
804 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
805 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
807 /* Intrapixel differencing */
808 png_do_write_intrapixel(&row_info, png_ptr->row_buf + 1);
810 #endif
812 /* Added at libpng-1.5.10 */
813 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
814 /* Check for out-of-range palette index */
815 if (row_info.color_type == PNG_COLOR_TYPE_PALETTE &&
816 png_ptr->num_palette_max >= 0)
817 png_do_check_palette_indexes(png_ptr, &row_info);
818 #endif
820 /* Find a filter if necessary, filter the row and write it out. */
821 png_write_find_filter(png_ptr, &row_info);
823 if (png_ptr->write_row_fn != NULL)
824 (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
827 #ifdef PNG_WRITE_FLUSH_SUPPORTED
828 /* Set the automatic flush interval or 0 to turn flushing off */
829 void PNGAPI
830 png_set_flush(png_structrp png_ptr, int nrows)
832 png_debug(1, "in png_set_flush");
834 if (png_ptr == NULL)
835 return;
837 png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
840 /* Flush the current output buffers now */
841 void PNGAPI
842 png_write_flush(png_structrp png_ptr)
844 png_debug(1, "in png_write_flush");
846 if (png_ptr == NULL)
847 return;
849 /* We have already written out all of the data */
850 if (png_ptr->row_number >= png_ptr->num_rows)
851 return;
853 png_compress_IDAT(png_ptr, NULL, 0, Z_SYNC_FLUSH);
854 png_ptr->flush_rows = 0;
855 png_flush(png_ptr);
857 #endif /* PNG_WRITE_FLUSH_SUPPORTED */
859 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
860 static void png_reset_filter_heuristics(png_structrp png_ptr);/* forward decl */
861 #endif
863 /* Free any memory used in png_ptr struct without freeing the struct itself. */
864 static void
865 png_write_destroy(png_structrp png_ptr)
867 png_debug(1, "in png_write_destroy");
869 /* Free any memory zlib uses */
870 if (png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED)
871 deflateEnd(&png_ptr->zstream);
873 /* Free our memory. png_free checks NULL for us. */
874 png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
875 png_free(png_ptr, png_ptr->row_buf);
876 #ifdef PNG_WRITE_FILTER_SUPPORTED
877 png_free(png_ptr, png_ptr->prev_row);
878 png_free(png_ptr, png_ptr->sub_row);
879 png_free(png_ptr, png_ptr->up_row);
880 png_free(png_ptr, png_ptr->avg_row);
881 png_free(png_ptr, png_ptr->paeth_row);
882 #endif
884 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
885 /* Use this to save a little code space, it doesn't free the filter_costs */
886 png_reset_filter_heuristics(png_ptr);
887 png_free(png_ptr, png_ptr->filter_costs);
888 png_free(png_ptr, png_ptr->inv_filter_costs);
889 #endif
891 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
892 png_free(png_ptr, png_ptr->chunk_list);
893 #endif
895 /* The error handling and memory handling information is left intact at this
896 * point: the jmp_buf may still have to be freed. See png_destroy_png_struct
897 * for how this happens.
901 /* Free all memory used by the write.
902 * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for
903 * *png_ptr_ptr. Prior to 1.6.0 it would accept such a value and it would free
904 * the passed in info_structs but it would quietly fail to free any of the data
905 * inside them. In 1.6.0 it quietly does nothing (it has to be quiet because it
906 * has no png_ptr.)
908 void PNGAPI
909 png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
911 png_debug(1, "in png_destroy_write_struct");
913 if (png_ptr_ptr != NULL)
915 png_structrp png_ptr = *png_ptr_ptr;
917 if (png_ptr != NULL) /* added in libpng 1.6.0 */
919 png_destroy_info_struct(png_ptr, info_ptr_ptr);
921 *png_ptr_ptr = NULL;
922 png_write_destroy(png_ptr);
923 png_destroy_png_struct(png_ptr);
928 /* Allow the application to select one or more row filters to use. */
929 void PNGAPI
930 png_set_filter(png_structrp png_ptr, int method, int filters)
932 png_debug(1, "in png_set_filter");
934 if (png_ptr == NULL)
935 return;
937 #ifdef PNG_MNG_FEATURES_SUPPORTED
938 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
939 (method == PNG_INTRAPIXEL_DIFFERENCING))
940 method = PNG_FILTER_TYPE_BASE;
942 #endif
943 if (method == PNG_FILTER_TYPE_BASE)
945 switch (filters & (PNG_ALL_FILTERS | 0x07))
947 #ifdef PNG_WRITE_FILTER_SUPPORTED
948 case 5:
949 case 6:
950 case 7: png_app_error(png_ptr, "Unknown row filter for method 0");
951 /* FALL THROUGH */
952 #endif /* PNG_WRITE_FILTER_SUPPORTED */
953 case PNG_FILTER_VALUE_NONE:
954 png_ptr->do_filter = PNG_FILTER_NONE; break;
956 #ifdef PNG_WRITE_FILTER_SUPPORTED
957 case PNG_FILTER_VALUE_SUB:
958 png_ptr->do_filter = PNG_FILTER_SUB; break;
960 case PNG_FILTER_VALUE_UP:
961 png_ptr->do_filter = PNG_FILTER_UP; break;
963 case PNG_FILTER_VALUE_AVG:
964 png_ptr->do_filter = PNG_FILTER_AVG; break;
966 case PNG_FILTER_VALUE_PAETH:
967 png_ptr->do_filter = PNG_FILTER_PAETH; break;
969 default:
970 png_ptr->do_filter = (png_byte)filters; break;
971 #else
972 default:
973 png_app_error(png_ptr, "Unknown row filter for method 0");
974 #endif /* PNG_WRITE_FILTER_SUPPORTED */
977 /* If we have allocated the row_buf, this means we have already started
978 * with the image and we should have allocated all of the filter buffers
979 * that have been selected. If prev_row isn't already allocated, then
980 * it is too late to start using the filters that need it, since we
981 * will be missing the data in the previous row. If an application
982 * wants to start and stop using particular filters during compression,
983 * it should start out with all of the filters, and then add and
984 * remove them after the start of compression.
986 if (png_ptr->row_buf != NULL)
988 #ifdef PNG_WRITE_FILTER_SUPPORTED
989 if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
991 png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
992 (png_ptr->rowbytes + 1));
993 png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
996 if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
998 if (png_ptr->prev_row == NULL)
1000 png_warning(png_ptr, "Can't add Up filter after starting");
1001 png_ptr->do_filter = (png_byte)(png_ptr->do_filter &
1002 ~PNG_FILTER_UP);
1005 else
1007 png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
1008 (png_ptr->rowbytes + 1));
1009 png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
1013 if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
1015 if (png_ptr->prev_row == NULL)
1017 png_warning(png_ptr, "Can't add Average filter after starting");
1018 png_ptr->do_filter = (png_byte)(png_ptr->do_filter &
1019 ~PNG_FILTER_AVG);
1022 else
1024 png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
1025 (png_ptr->rowbytes + 1));
1026 png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
1030 if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
1031 png_ptr->paeth_row == NULL)
1033 if (png_ptr->prev_row == NULL)
1035 png_warning(png_ptr, "Can't add Paeth filter after starting");
1036 png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
1039 else
1041 png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
1042 (png_ptr->rowbytes + 1));
1043 png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
1047 if (png_ptr->do_filter == PNG_NO_FILTERS)
1048 #endif /* PNG_WRITE_FILTER_SUPPORTED */
1049 png_ptr->do_filter = PNG_FILTER_NONE;
1052 else
1053 png_error(png_ptr, "Unknown custom filter method");
1056 /* This allows us to influence the way in which libpng chooses the "best"
1057 * filter for the current scanline. While the "minimum-sum-of-absolute-
1058 * differences metric is relatively fast and effective, there is some
1059 * question as to whether it can be improved upon by trying to keep the
1060 * filtered data going to zlib more consistent, hopefully resulting in
1061 * better compression.
1063 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* GRR 970116 */
1064 /* Convenience reset API. */
1065 static void
1066 png_reset_filter_heuristics(png_structrp png_ptr)
1068 /* Clear out any old values in the 'weights' - this must be done because if
1069 * the app calls set_filter_heuristics multiple times with different
1070 * 'num_weights' values we would otherwise potentially have wrong sized
1071 * arrays.
1073 png_ptr->num_prev_filters = 0;
1074 png_ptr->heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
1075 if (png_ptr->prev_filters != NULL)
1077 png_bytep old = png_ptr->prev_filters;
1078 png_ptr->prev_filters = NULL;
1079 png_free(png_ptr, old);
1081 if (png_ptr->filter_weights != NULL)
1083 png_uint_16p old = png_ptr->filter_weights;
1084 png_ptr->filter_weights = NULL;
1085 png_free(png_ptr, old);
1088 if (png_ptr->inv_filter_weights != NULL)
1090 png_uint_16p old = png_ptr->inv_filter_weights;
1091 png_ptr->inv_filter_weights = NULL;
1092 png_free(png_ptr, old);
1095 /* Leave the filter_costs - this array is fixed size. */
1098 static int
1099 png_init_filter_heuristics(png_structrp png_ptr, int heuristic_method,
1100 int num_weights)
1102 if (png_ptr == NULL)
1103 return 0;
1105 /* Clear out the arrays */
1106 png_reset_filter_heuristics(png_ptr);
1108 /* Check arguments; the 'reset' function makes the correct settings for the
1109 * unweighted case, but we must handle the weight case by initializing the
1110 * arrays for the caller.
1112 if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
1114 int i;
1116 if (num_weights > 0)
1118 png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
1119 (png_uint_32)((sizeof (png_byte)) * num_weights));
1121 /* To make sure that the weighting starts out fairly */
1122 for (i = 0; i < num_weights; i++)
1124 png_ptr->prev_filters[i] = 255;
1127 png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
1128 (png_uint_32)((sizeof (png_uint_16)) * num_weights));
1130 png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
1131 (png_uint_32)((sizeof (png_uint_16)) * num_weights));
1133 for (i = 0; i < num_weights; i++)
1135 png_ptr->inv_filter_weights[i] =
1136 png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
1139 /* Safe to set this now */
1140 png_ptr->num_prev_filters = (png_byte)num_weights;
1143 /* If, in the future, there are other filter methods, this would
1144 * need to be based on png_ptr->filter.
1146 if (png_ptr->filter_costs == NULL)
1148 png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
1149 (png_uint_32)((sizeof (png_uint_16)) * PNG_FILTER_VALUE_LAST));
1151 png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
1152 (png_uint_32)((sizeof (png_uint_16)) * PNG_FILTER_VALUE_LAST));
1155 for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
1157 png_ptr->inv_filter_costs[i] =
1158 png_ptr->filter_costs[i] = PNG_COST_FACTOR;
1161 /* All the arrays are inited, safe to set this: */
1162 png_ptr->heuristic_method = PNG_FILTER_HEURISTIC_WEIGHTED;
1164 /* Return the 'ok' code. */
1165 return 1;
1167 else if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT ||
1168 heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
1170 return 1;
1172 else
1174 png_warning(png_ptr, "Unknown filter heuristic method");
1175 return 0;
1179 /* Provide floating and fixed point APIs */
1180 #ifdef PNG_FLOATING_POINT_SUPPORTED
1181 void PNGAPI
1182 png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method,
1183 int num_weights, png_const_doublep filter_weights,
1184 png_const_doublep filter_costs)
1186 png_debug(1, "in png_set_filter_heuristics");
1188 /* The internal API allocates all the arrays and ensures that the elements of
1189 * those arrays are set to the default value.
1191 if (!png_init_filter_heuristics(png_ptr, heuristic_method, num_weights))
1192 return;
1194 /* If using the weighted method copy in the weights. */
1195 if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
1197 int i;
1198 for (i = 0; i < num_weights; i++)
1200 if (filter_weights[i] <= 0.0)
1202 png_ptr->inv_filter_weights[i] =
1203 png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
1206 else
1208 png_ptr->inv_filter_weights[i] =
1209 (png_uint_16)(PNG_WEIGHT_FACTOR*filter_weights[i]+.5);
1211 png_ptr->filter_weights[i] =
1212 (png_uint_16)(PNG_WEIGHT_FACTOR/filter_weights[i]+.5);
1216 /* Here is where we set the relative costs of the different filters. We
1217 * should take the desired compression level into account when setting
1218 * the costs, so that Paeth, for instance, has a high relative cost at low
1219 * compression levels, while it has a lower relative cost at higher
1220 * compression settings. The filter types are in order of increasing
1221 * relative cost, so it would be possible to do this with an algorithm.
1223 for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) if (filter_costs[i] >= 1.0)
1225 png_ptr->inv_filter_costs[i] =
1226 (png_uint_16)(PNG_COST_FACTOR / filter_costs[i] + .5);
1228 png_ptr->filter_costs[i] =
1229 (png_uint_16)(PNG_COST_FACTOR * filter_costs[i] + .5);
1233 #endif /* FLOATING_POINT */
1235 #ifdef PNG_FIXED_POINT_SUPPORTED
1236 void PNGAPI
1237 png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method,
1238 int num_weights, png_const_fixed_point_p filter_weights,
1239 png_const_fixed_point_p filter_costs)
1241 png_debug(1, "in png_set_filter_heuristics_fixed");
1243 /* The internal API allocates all the arrays and ensures that the elements of
1244 * those arrays are set to the default value.
1246 if (!png_init_filter_heuristics(png_ptr, heuristic_method, num_weights))
1247 return;
1249 /* If using the weighted method copy in the weights. */
1250 if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
1252 int i;
1253 for (i = 0; i < num_weights; i++)
1255 if (filter_weights[i] <= 0)
1257 png_ptr->inv_filter_weights[i] =
1258 png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
1261 else
1263 png_ptr->inv_filter_weights[i] = (png_uint_16)
1264 ((PNG_WEIGHT_FACTOR*filter_weights[i]+PNG_FP_HALF)/PNG_FP_1);
1266 png_ptr->filter_weights[i] = (png_uint_16)((PNG_WEIGHT_FACTOR*
1267 PNG_FP_1+(filter_weights[i]/2))/filter_weights[i]);
1271 /* Here is where we set the relative costs of the different filters. We
1272 * should take the desired compression level into account when setting
1273 * the costs, so that Paeth, for instance, has a high relative cost at low
1274 * compression levels, while it has a lower relative cost at higher
1275 * compression settings. The filter types are in order of increasing
1276 * relative cost, so it would be possible to do this with an algorithm.
1278 for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
1279 if (filter_costs[i] >= PNG_FP_1)
1281 png_uint_32 tmp;
1283 /* Use a 32 bit unsigned temporary here because otherwise the
1284 * intermediate value will be a 32 bit *signed* integer (ANSI rules)
1285 * and this will get the wrong answer on division.
1287 tmp = PNG_COST_FACTOR*PNG_FP_1 + (filter_costs[i]/2);
1288 tmp /= filter_costs[i];
1290 png_ptr->inv_filter_costs[i] = (png_uint_16)tmp;
1292 tmp = PNG_COST_FACTOR * filter_costs[i] + PNG_FP_HALF;
1293 tmp /= PNG_FP_1;
1295 png_ptr->filter_costs[i] = (png_uint_16)tmp;
1299 #endif /* FIXED_POINT */
1300 #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
1302 void PNGAPI
1303 png_set_compression_level(png_structrp png_ptr, int level)
1305 png_debug(1, "in png_set_compression_level");
1307 if (png_ptr == NULL)
1308 return;
1310 png_ptr->zlib_level = level;
1313 void PNGAPI
1314 png_set_compression_mem_level(png_structrp png_ptr, int mem_level)
1316 png_debug(1, "in png_set_compression_mem_level");
1318 if (png_ptr == NULL)
1319 return;
1321 png_ptr->zlib_mem_level = mem_level;
1324 void PNGAPI
1325 png_set_compression_strategy(png_structrp png_ptr, int strategy)
1327 png_debug(1, "in png_set_compression_strategy");
1329 if (png_ptr == NULL)
1330 return;
1332 /* The flag setting here prevents the libpng dynamic selection of strategy.
1334 png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
1335 png_ptr->zlib_strategy = strategy;
1338 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1339 * smaller value of window_bits if it can do so safely.
1341 void PNGAPI
1342 png_set_compression_window_bits(png_structrp png_ptr, int window_bits)
1344 if (png_ptr == NULL)
1345 return;
1347 /* Prior to 1.6.0 this would warn but then set the window_bits value, this
1348 * meant that negative window bits values could be selected which would cause
1349 * libpng to write a non-standard PNG file with raw deflate or gzip
1350 * compressed IDAT or ancillary chunks. Such files can be read and there is
1351 * no warning on read, so this seems like a very bad idea.
1353 if (window_bits > 15)
1355 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1356 window_bits = 15;
1359 else if (window_bits < 8)
1361 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1362 window_bits = 8;
1365 png_ptr->zlib_window_bits = window_bits;
1368 void PNGAPI
1369 png_set_compression_method(png_structrp png_ptr, int method)
1371 png_debug(1, "in png_set_compression_method");
1373 if (png_ptr == NULL)
1374 return;
1376 /* This would produce an invalid PNG file if it worked, but it doesn't and
1377 * deflate will fault it, so it is harmless to just warn here.
1379 if (method != 8)
1380 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1382 png_ptr->zlib_method = method;
1385 /* The following were added to libpng-1.5.4 */
1386 #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
1387 void PNGAPI
1388 png_set_text_compression_level(png_structrp png_ptr, int level)
1390 png_debug(1, "in png_set_text_compression_level");
1392 if (png_ptr == NULL)
1393 return;
1395 png_ptr->zlib_text_level = level;
1398 void PNGAPI
1399 png_set_text_compression_mem_level(png_structrp png_ptr, int mem_level)
1401 png_debug(1, "in png_set_text_compression_mem_level");
1403 if (png_ptr == NULL)
1404 return;
1406 png_ptr->zlib_text_mem_level = mem_level;
1409 void PNGAPI
1410 png_set_text_compression_strategy(png_structrp png_ptr, int strategy)
1412 png_debug(1, "in png_set_text_compression_strategy");
1414 if (png_ptr == NULL)
1415 return;
1417 png_ptr->zlib_text_strategy = strategy;
1420 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1421 * smaller value of window_bits if it can do so safely.
1423 void PNGAPI
1424 png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits)
1426 if (png_ptr == NULL)
1427 return;
1429 if (window_bits > 15)
1431 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1432 window_bits = 15;
1435 else if (window_bits < 8)
1437 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1438 window_bits = 8;
1441 png_ptr->zlib_text_window_bits = window_bits;
1444 void PNGAPI
1445 png_set_text_compression_method(png_structrp png_ptr, int method)
1447 png_debug(1, "in png_set_text_compression_method");
1449 if (png_ptr == NULL)
1450 return;
1452 if (method != 8)
1453 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1455 png_ptr->zlib_text_method = method;
1457 #endif /* PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED */
1458 /* end of API added to libpng-1.5.4 */
1460 void PNGAPI
1461 png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn)
1463 if (png_ptr == NULL)
1464 return;
1466 png_ptr->write_row_fn = write_row_fn;
1469 #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
1470 void PNGAPI
1471 png_set_write_user_transform_fn(png_structrp png_ptr, png_user_transform_ptr
1472 write_user_transform_fn)
1474 png_debug(1, "in png_set_write_user_transform_fn");
1476 if (png_ptr == NULL)
1477 return;
1479 png_ptr->transformations |= PNG_USER_TRANSFORM;
1480 png_ptr->write_user_transform_fn = write_user_transform_fn;
1482 #endif
1485 #ifdef PNG_INFO_IMAGE_SUPPORTED
1486 void PNGAPI
1487 png_write_png(png_structrp png_ptr, png_inforp info_ptr,
1488 int transforms, voidp params)
1490 if (png_ptr == NULL || info_ptr == NULL)
1491 return;
1493 /* Write the file header information. */
1494 png_write_info(png_ptr, info_ptr);
1496 /* ------ these transformations don't touch the info structure ------- */
1498 #ifdef PNG_WRITE_INVERT_SUPPORTED
1499 /* Invert monochrome pixels */
1500 if (transforms & PNG_TRANSFORM_INVERT_MONO)
1501 png_set_invert_mono(png_ptr);
1502 #endif
1504 #ifdef PNG_WRITE_SHIFT_SUPPORTED
1505 /* Shift the pixels up to a legal bit depth and fill in
1506 * as appropriate to correctly scale the image.
1508 if ((transforms & PNG_TRANSFORM_SHIFT)
1509 && (info_ptr->valid & PNG_INFO_sBIT))
1510 png_set_shift(png_ptr, &info_ptr->sig_bit);
1511 #endif
1513 #ifdef PNG_WRITE_PACK_SUPPORTED
1514 /* Pack pixels into bytes */
1515 if (transforms & PNG_TRANSFORM_PACKING)
1516 png_set_packing(png_ptr);
1517 #endif
1519 #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
1520 /* Swap location of alpha bytes from ARGB to RGBA */
1521 if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
1522 png_set_swap_alpha(png_ptr);
1523 #endif
1525 #ifdef PNG_WRITE_FILLER_SUPPORTED
1526 /* Pack XRGB/RGBX/ARGB/RGBA into RGB (4 channels -> 3 channels) */
1527 if (transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER)
1528 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
1530 else if (transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE)
1531 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1532 #endif
1534 #ifdef PNG_WRITE_BGR_SUPPORTED
1535 /* Flip BGR pixels to RGB */
1536 if (transforms & PNG_TRANSFORM_BGR)
1537 png_set_bgr(png_ptr);
1538 #endif
1540 #ifdef PNG_WRITE_SWAP_SUPPORTED
1541 /* Swap bytes of 16-bit files to most significant byte first */
1542 if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
1543 png_set_swap(png_ptr);
1544 #endif
1546 #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
1547 /* Swap bits of 1, 2, 4 bit packed pixel formats */
1548 if (transforms & PNG_TRANSFORM_PACKSWAP)
1549 png_set_packswap(png_ptr);
1550 #endif
1552 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
1553 /* Invert the alpha channel from opacity to transparency */
1554 if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
1555 png_set_invert_alpha(png_ptr);
1556 #endif
1558 /* ----------------------- end of transformations ------------------- */
1560 /* Write the bits */
1561 if (info_ptr->valid & PNG_INFO_IDAT)
1562 png_write_image(png_ptr, info_ptr->row_pointers);
1564 /* It is REQUIRED to call this to finish writing the rest of the file */
1565 png_write_end(png_ptr, info_ptr);
1567 PNG_UNUSED(transforms) /* Quiet compiler warnings */
1568 PNG_UNUSED(params)
1570 #endif
1573 #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
1574 #ifdef PNG_STDIO_SUPPORTED /* currently required for png_image_write_* */
1575 /* Initialize the write structure - general purpose utility. */
1576 static int
1577 png_image_write_init(png_imagep image)
1579 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
1580 png_safe_error, png_safe_warning);
1582 if (png_ptr != NULL)
1584 png_infop info_ptr = png_create_info_struct(png_ptr);
1586 if (info_ptr != NULL)
1588 png_controlp control = png_voidcast(png_controlp,
1589 png_malloc_warn(png_ptr, (sizeof *control)));
1591 if (control != NULL)
1593 memset(control, 0, (sizeof *control));
1595 control->png_ptr = png_ptr;
1596 control->info_ptr = info_ptr;
1597 control->for_write = 1;
1599 image->opaque = control;
1600 return 1;
1603 /* Error clean up */
1604 png_destroy_info_struct(png_ptr, &info_ptr);
1607 png_destroy_write_struct(&png_ptr, NULL);
1610 return png_image_error(image, "png_image_write_: out of memory");
1613 /* Arguments to png_image_write_main: */
1614 typedef struct
1616 /* Arguments: */
1617 png_imagep image;
1618 png_const_voidp buffer;
1619 png_int_32 row_stride;
1620 png_const_voidp colormap;
1621 int convert_to_8bit;
1622 /* Local variables: */
1623 png_const_voidp first_row;
1624 ptrdiff_t row_bytes;
1625 png_voidp local_row;
1626 } png_image_write_control;
1628 /* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
1629 * do any necessary byte swapping. The component order is defined by the
1630 * png_image format value.
1632 static int
1633 png_write_image_16bit(png_voidp argument)
1635 png_image_write_control *display = png_voidcast(png_image_write_control*,
1636 argument);
1637 png_imagep image = display->image;
1638 png_structrp png_ptr = image->opaque->png_ptr;
1640 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1641 display->first_row);
1642 png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row);
1643 png_uint_16p row_end;
1644 const int channels = (image->format & PNG_FORMAT_FLAG_COLOR) ? 3 : 1;
1645 int aindex = 0;
1646 png_uint_32 y = image->height;
1648 if (image->format & PNG_FORMAT_FLAG_ALPHA)
1650 if (image->format & PNG_FORMAT_FLAG_AFIRST)
1652 aindex = -1;
1653 ++input_row; /* To point to the first component */
1654 ++output_row;
1657 else
1658 aindex = channels;
1661 else
1662 png_error(png_ptr, "png_write_image: internal call error");
1664 /* Work out the output row end and count over this, note that the increment
1665 * above to 'row' means that row_end can actually be beyond the end of the
1666 * row; this is correct.
1668 row_end = output_row + image->width * (channels+1);
1670 while (y-- > 0)
1672 png_const_uint_16p in_ptr = input_row;
1673 png_uint_16p out_ptr = output_row;
1675 while (out_ptr < row_end)
1677 const png_uint_16 alpha = in_ptr[aindex];
1678 png_uint_32 reciprocal = 0;
1679 int c;
1681 out_ptr[aindex] = alpha;
1683 /* Calculate a reciprocal. The correct calculation is simply
1684 * component/alpha*65535 << 15. (I.e. 15 bits of precision); this
1685 * allows correct rounding by adding .5 before the shift. 'reciprocal'
1686 * is only initialized when required.
1688 if (alpha > 0 && alpha < 65535)
1689 reciprocal = ((0xffff<<15)+(alpha>>1))/alpha;
1691 c = channels;
1692 do /* always at least one channel */
1694 png_uint_16 component = *in_ptr++;
1696 /* The following gives 65535 for an alpha of 0, which is fine,
1697 * otherwise if 0/0 is represented as some other value there is more
1698 * likely to be a discontinuity which will probably damage
1699 * compression when moving from a fully transparent area to a
1700 * nearly transparent one. (The assumption here is that opaque
1701 * areas tend not to be 0 intensity.)
1703 if (component >= alpha)
1704 component = 65535;
1706 /* component<alpha, so component/alpha is less than one and
1707 * component*reciprocal is less than 2^31.
1709 else if (component > 0 && alpha < 65535)
1711 png_uint_32 calc = component * reciprocal;
1712 calc += 16384; /* round to nearest */
1713 component = (png_uint_16)(calc >> 15);
1716 *out_ptr++ = component;
1718 while (--c > 0);
1720 /* Skip to next component (skip the intervening alpha channel) */
1721 ++in_ptr;
1722 ++out_ptr;
1725 png_write_row(png_ptr, png_voidcast(png_const_bytep, display->local_row));
1726 input_row += display->row_bytes/(sizeof (png_uint_16));
1729 return 1;
1732 /* Given 16-bit input (1 to 4 channels) write 8-bit output. If an alpha channel
1733 * is present it must be removed from the components, the components are then
1734 * written in sRGB encoding. No components are added or removed.
1736 * Calculate an alpha reciprocal to reverse pre-multiplication. As above the
1737 * calculation can be done to 15 bits of accuracy; however, the output needs to
1738 * be scaled in the range 0..255*65535, so include that scaling here.
1740 #define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+(alpha>>1))/alpha)
1742 static png_byte
1743 png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
1744 png_uint_32 reciprocal/*from the above macro*/)
1746 /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0
1747 * is represented as some other value there is more likely to be a
1748 * discontinuity which will probably damage compression when moving from a
1749 * fully transparent area to a nearly transparent one. (The assumption here
1750 * is that opaque areas tend not to be 0 intensity.)
1752 * There is a rounding problem here; if alpha is less than 128 it will end up
1753 * as 0 when scaled to 8 bits. To avoid introducing spurious colors into the
1754 * output change for this too.
1756 if (component >= alpha || alpha < 128)
1757 return 255;
1759 /* component<alpha, so component/alpha is less than one and
1760 * component*reciprocal is less than 2^31.
1762 else if (component > 0)
1764 /* The test is that alpha/257 (rounded) is less than 255, the first value
1765 * that becomes 255 is 65407.
1766 * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore,
1767 * be exact!) [Could also test reciprocal != 0]
1769 if (alpha < 65407)
1771 component *= reciprocal;
1772 component += 64; /* round to nearest */
1773 component >>= 7;
1776 else
1777 component *= 255;
1779 /* Convert the component to sRGB. */
1780 return (png_byte)PNG_sRGB_FROM_LINEAR(component);
1783 else
1784 return 0;
1787 static int
1788 png_write_image_8bit(png_voidp argument)
1790 png_image_write_control *display = png_voidcast(png_image_write_control*,
1791 argument);
1792 png_imagep image = display->image;
1793 png_structrp png_ptr = image->opaque->png_ptr;
1795 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1796 display->first_row);
1797 png_bytep output_row = png_voidcast(png_bytep, display->local_row);
1798 png_uint_32 y = image->height;
1799 const int channels = (image->format & PNG_FORMAT_FLAG_COLOR) ? 3 : 1;
1801 if (image->format & PNG_FORMAT_FLAG_ALPHA)
1803 png_bytep row_end;
1804 int aindex;
1806 if (image->format & PNG_FORMAT_FLAG_AFIRST)
1808 aindex = -1;
1809 ++input_row; /* To point to the first component */
1810 ++output_row;
1813 else
1814 aindex = channels;
1816 /* Use row_end in place of a loop counter: */
1817 row_end = output_row + image->width * (channels+1);
1819 while (y-- > 0)
1821 png_const_uint_16p in_ptr = input_row;
1822 png_bytep out_ptr = output_row;
1824 while (out_ptr < row_end)
1826 png_uint_16 alpha = in_ptr[aindex];
1827 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1828 png_uint_32 reciprocal = 0;
1829 int c;
1831 /* Scale and write the alpha channel. */
1832 out_ptr[aindex] = alphabyte;
1834 if (alphabyte > 0 && alphabyte < 255)
1835 reciprocal = UNP_RECIPROCAL(alpha);
1837 c = channels;
1838 do /* always at least one channel */
1839 *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal);
1840 while (--c > 0);
1842 /* Skip to next component (skip the intervening alpha channel) */
1843 ++in_ptr;
1844 ++out_ptr;
1845 } /* while out_ptr < row_end */
1847 png_write_row(png_ptr, png_voidcast(png_const_bytep,
1848 display->local_row));
1849 input_row += display->row_bytes/(sizeof (png_uint_16));
1850 } /* while y */
1853 else
1855 /* No alpha channel, so the row_end really is the end of the row and it
1856 * is sufficient to loop over the components one by one.
1858 png_bytep row_end = output_row + image->width * channels;
1860 while (y-- > 0)
1862 png_const_uint_16p in_ptr = input_row;
1863 png_bytep out_ptr = output_row;
1865 while (out_ptr < row_end)
1867 png_uint_32 component = *in_ptr++;
1869 component *= 255;
1870 *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component);
1873 png_write_row(png_ptr, output_row);
1874 input_row += display->row_bytes/(sizeof (png_uint_16));
1878 return 1;
1881 static void
1882 png_image_set_PLTE(png_image_write_control *display)
1884 const png_imagep image = display->image;
1885 const void *cmap = display->colormap;
1886 const int entries = image->colormap_entries > 256 ? 256 :
1887 (int)image->colormap_entries;
1889 /* NOTE: the caller must check for cmap != NULL and entries != 0 */
1890 const png_uint_32 format = image->format;
1891 const int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
1893 # ifdef PNG_FORMAT_BGR_SUPPORTED
1894 const int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1895 (format & PNG_FORMAT_FLAG_ALPHA) != 0;
1896 # else
1897 # define afirst 0
1898 # endif
1900 # ifdef PNG_FORMAT_BGR_SUPPORTED
1901 const int bgr = (format & PNG_FORMAT_FLAG_BGR) ? 2 : 0;
1902 # else
1903 # define bgr 0
1904 # endif
1906 int i, num_trans;
1907 png_color palette[256];
1908 png_byte tRNS[256];
1910 memset(tRNS, 255, (sizeof tRNS));
1911 memset(palette, 0, (sizeof palette));
1913 for (i=num_trans=0; i<entries; ++i)
1915 /* This gets automatically converted to sRGB with reversal of the
1916 * pre-multiplication if the color-map has an alpha channel.
1918 if (format & PNG_FORMAT_FLAG_LINEAR)
1920 png_const_uint_16p entry = png_voidcast(png_const_uint_16p, cmap);
1922 entry += i * channels;
1924 if (channels & 1) /* no alpha */
1926 if (channels >= 3) /* RGB */
1928 palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1929 entry[(2 ^ bgr)]);
1930 palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1931 entry[1]);
1932 palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1933 entry[bgr]);
1936 else /* Gray */
1937 palette[i].blue = palette[i].red = palette[i].green =
1938 (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry);
1941 else /* alpha */
1943 png_uint_16 alpha = entry[afirst ? 0 : channels-1];
1944 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1945 png_uint_32 reciprocal = 0;
1947 /* Calculate a reciprocal, as in the png_write_image_8bit code above
1948 * this is designed to produce a value scaled to 255*65535 when
1949 * divided by 128 (i.e. asr 7).
1951 if (alphabyte > 0 && alphabyte < 255)
1952 reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha;
1954 tRNS[i] = alphabyte;
1955 if (alphabyte < 255)
1956 num_trans = i+1;
1958 if (channels >= 3) /* RGB */
1960 palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)],
1961 alpha, reciprocal);
1962 palette[i].green = png_unpremultiply(entry[afirst + 1], alpha,
1963 reciprocal);
1964 palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha,
1965 reciprocal);
1968 else /* gray */
1969 palette[i].blue = palette[i].red = palette[i].green =
1970 png_unpremultiply(entry[afirst], alpha, reciprocal);
1974 else /* Color-map has sRGB values */
1976 png_const_bytep entry = png_voidcast(png_const_bytep, cmap);
1978 entry += i * channels;
1980 switch (channels)
1982 case 4:
1983 tRNS[i] = entry[afirst ? 0 : 3];
1984 if (tRNS[i] < 255)
1985 num_trans = i+1;
1986 /* FALL THROUGH */
1987 case 3:
1988 palette[i].blue = entry[afirst + (2 ^ bgr)];
1989 palette[i].green = entry[afirst + 1];
1990 palette[i].red = entry[afirst + bgr];
1991 break;
1993 case 2:
1994 tRNS[i] = entry[1 ^ afirst];
1995 if (tRNS[i] < 255)
1996 num_trans = i+1;
1997 /* FALL THROUGH */
1998 case 1:
1999 palette[i].blue = palette[i].red = palette[i].green =
2000 entry[afirst];
2001 break;
2003 default:
2004 break;
2009 # ifdef afirst
2010 # undef afirst
2011 # endif
2012 # ifdef bgr
2013 # undef bgr
2014 # endif
2016 png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
2017 entries);
2019 if (num_trans > 0)
2020 png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS,
2021 num_trans, NULL);
2023 image->colormap_entries = entries;
2026 static int
2027 png_image_write_main(png_voidp argument)
2029 png_image_write_control *display = png_voidcast(png_image_write_control*,
2030 argument);
2031 png_imagep image = display->image;
2032 png_structrp png_ptr = image->opaque->png_ptr;
2033 png_inforp info_ptr = image->opaque->info_ptr;
2034 png_uint_32 format = image->format;
2036 int colormap = (format & PNG_FORMAT_FLAG_COLORMAP) != 0;
2037 int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR) != 0; /* input */
2038 int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA) != 0;
2039 int write_16bit = linear && !colormap && !display->convert_to_8bit;
2041 # ifdef PNG_BENIGN_ERRORS_SUPPORTED
2042 /* Make sure we error out on any bad situation */
2043 png_set_benign_errors(png_ptr, 0/*error*/);
2044 # endif
2046 /* Default the 'row_stride' parameter if required. */
2047 if (display->row_stride == 0)
2048 display->row_stride = PNG_IMAGE_ROW_STRIDE(*image);
2050 /* Set the required transforms then write the rows in the correct order. */
2051 if (format & PNG_FORMAT_FLAG_COLORMAP)
2053 if (display->colormap != NULL && image->colormap_entries > 0)
2055 png_uint_32 entries = image->colormap_entries;
2057 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2058 entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)),
2059 PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
2060 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2062 png_image_set_PLTE(display);
2065 else
2066 png_error(image->opaque->png_ptr,
2067 "no color-map for color-mapped image");
2070 else
2071 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2072 write_16bit ? 16 : 8,
2073 ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) +
2074 ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0),
2075 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2077 /* Counter-intuitively the data transformations must be called *after*
2078 * png_write_info, not before as in the read code, but the 'set' functions
2079 * must still be called before. Just set the color space information, never
2080 * write an interlaced image.
2083 if (write_16bit)
2085 /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */
2086 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR);
2088 if (!(image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB))
2089 png_set_cHRM_fixed(png_ptr, info_ptr,
2090 /* color x y */
2091 /* white */ 31270, 32900,
2092 /* red */ 64000, 33000,
2093 /* green */ 30000, 60000,
2094 /* blue */ 15000, 6000
2098 else if (!(image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB))
2099 png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);
2101 /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit
2102 * space must still be gamma encoded.
2104 else
2105 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE);
2107 /* Write the file header. */
2108 png_write_info(png_ptr, info_ptr);
2110 /* Now set up the data transformations (*after* the header is written),
2111 * remove the handled transformations from the 'format' flags for checking.
2113 * First check for a little endian system if writing 16 bit files.
2115 if (write_16bit)
2117 PNG_CONST png_uint_16 le = 0x0001;
2119 if (*(png_const_bytep)&le)
2120 png_set_swap(png_ptr);
2123 # ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
2124 if (format & PNG_FORMAT_FLAG_BGR)
2126 if (!colormap && (format & PNG_FORMAT_FLAG_COLOR) != 0)
2127 png_set_bgr(png_ptr);
2128 format &= ~PNG_FORMAT_FLAG_BGR;
2130 # endif
2132 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
2133 if (format & PNG_FORMAT_FLAG_AFIRST)
2135 if (!colormap && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
2136 png_set_swap_alpha(png_ptr);
2137 format &= ~PNG_FORMAT_FLAG_AFIRST;
2139 # endif
2141 /* If there are 16 or fewer color-map entries we wrote a lower bit depth
2142 * above, but the application data is still byte packed.
2144 if (colormap && image->colormap_entries <= 16)
2145 png_set_packing(png_ptr);
2147 /* That should have handled all (both) the transforms. */
2148 if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR |
2149 PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0)
2150 png_error(png_ptr, "png_write_image: unsupported transformation");
2153 png_const_bytep row = png_voidcast(png_const_bytep, display->buffer);
2154 ptrdiff_t row_bytes = display->row_stride;
2156 if (linear)
2157 row_bytes *= (sizeof (png_uint_16));
2159 if (row_bytes < 0)
2160 row += (image->height-1) * (-row_bytes);
2162 display->first_row = row;
2163 display->row_bytes = row_bytes;
2166 /* Apply 'fast' options if the flag is set. */
2167 if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0)
2169 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS);
2170 /* NOTE: determined by experiment using pngstest, this reflects some
2171 * balance between the time to write the image once and the time to read
2172 * it about 50 times. The speed-up in pngstest was about 10-20% of the
2173 * total (user) time on a heavily loaded system.
2175 png_set_compression_level(png_ptr, 3);
2178 /* Check for the cases that currently require a pre-transform on the row
2179 * before it is written. This only applies when the input is 16-bit and
2180 * either there is an alpha channel or it is converted to 8-bit.
2182 if ((linear && alpha) || (!colormap && display->convert_to_8bit))
2184 png_bytep row = png_voidcast(png_bytep, png_malloc(png_ptr,
2185 png_get_rowbytes(png_ptr, info_ptr)));
2186 int result;
2188 display->local_row = row;
2189 if (write_16bit)
2190 result = png_safe_execute(image, png_write_image_16bit, display);
2191 else
2192 result = png_safe_execute(image, png_write_image_8bit, display);
2193 display->local_row = NULL;
2195 png_free(png_ptr, row);
2197 /* Skip the 'write_end' on error: */
2198 if (!result)
2199 return 0;
2202 /* Otherwise this is the case where the input is in a format currently
2203 * supported by the rest of the libpng write code; call it directly.
2205 else
2207 png_const_bytep row = png_voidcast(png_const_bytep, display->first_row);
2208 ptrdiff_t row_bytes = display->row_bytes;
2209 png_uint_32 y = image->height;
2211 while (y-- > 0)
2213 png_write_row(png_ptr, row);
2214 row += row_bytes;
2218 png_write_end(png_ptr, info_ptr);
2219 return 1;
2222 int PNGAPI
2223 png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit,
2224 const void *buffer, png_int_32 row_stride, const void *colormap)
2226 /* Write the image to the given (FILE*). */
2227 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2229 if (file != NULL)
2231 if (png_image_write_init(image))
2233 png_image_write_control display;
2234 int result;
2236 /* This is slightly evil, but png_init_io doesn't do anything other
2237 * than this and we haven't changed the standard IO functions so
2238 * this saves a 'safe' function.
2240 image->opaque->png_ptr->io_ptr = file;
2242 memset(&display, 0, (sizeof display));
2243 display.image = image;
2244 display.buffer = buffer;
2245 display.row_stride = row_stride;
2246 display.colormap = colormap;
2247 display.convert_to_8bit = convert_to_8bit;
2249 result = png_safe_execute(image, png_image_write_main, &display);
2250 png_image_free(image);
2251 return result;
2254 else
2255 return 0;
2258 else
2259 return png_image_error(image,
2260 "png_image_write_to_stdio: invalid argument");
2263 else if (image != NULL)
2264 return png_image_error(image,
2265 "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION");
2267 else
2268 return 0;
2271 int PNGAPI
2272 png_image_write_to_file(png_imagep image, const char *file_name,
2273 int convert_to_8bit, const void *buffer, png_int_32 row_stride,
2274 const void *colormap)
2276 /* Write the image to the named file. */
2277 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2279 if (file_name != NULL)
2281 FILE *fp = fopen(file_name, "wb");
2283 if (fp != NULL)
2285 if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer,
2286 row_stride, colormap))
2288 int error; /* from fflush/fclose */
2290 /* Make sure the file is flushed correctly. */
2291 if (fflush(fp) == 0 && ferror(fp) == 0)
2293 if (fclose(fp) == 0)
2294 return 1;
2296 error = errno; /* from fclose */
2299 else
2301 error = errno; /* from fflush or ferror */
2302 (void)fclose(fp);
2305 (void)remove(file_name);
2306 /* The image has already been cleaned up; this is just used to
2307 * set the error (because the original write succeeded).
2309 return png_image_error(image, strerror(error));
2312 else
2314 /* Clean up: just the opened file. */
2315 (void)fclose(fp);
2316 (void)remove(file_name);
2317 return 0;
2321 else
2322 return png_image_error(image, strerror(errno));
2325 else
2326 return png_image_error(image,
2327 "png_image_write_to_file: invalid argument");
2330 else if (image != NULL)
2331 return png_image_error(image,
2332 "png_image_write_to_file: incorrect PNG_IMAGE_VERSION");
2334 else
2335 return 0;
2337 #endif /* PNG_STDIO_SUPPORTED */
2338 #endif /* SIMPLIFIED_WRITE */
2340 #ifdef PNG_WRITE_APNG_SUPPORTED
2341 void PNGAPI
2342 png_write_frame_head(png_structp png_ptr, png_infop info_ptr,
2343 png_bytepp row_pointers, png_uint_32 width, png_uint_32 height,
2344 png_uint_32 x_offset, png_uint_32 y_offset,
2345 png_uint_16 delay_num, png_uint_16 delay_den, png_byte dispose_op,
2346 png_byte blend_op)
2348 png_debug(1, "in png_write_frame_head");
2350 /* there is a chance this has been set after png_write_info was called,
2351 * so it would be set but not written. is there a way to be sure? */
2352 if (!(info_ptr->valid & PNG_INFO_acTL))
2353 png_error(png_ptr, "png_write_frame_head(): acTL not set");
2355 png_write_reset(png_ptr);
2357 png_write_reinit(png_ptr, info_ptr, width, height);
2359 if ( !(png_ptr->num_frames_written == 0 &&
2360 (png_ptr->apng_flags & PNG_FIRST_FRAME_HIDDEN) ) )
2361 png_write_fcTL(png_ptr, width, height, x_offset, y_offset,
2362 delay_num, delay_den, dispose_op, blend_op);
2364 PNG_UNUSED(row_pointers)
2367 void PNGAPI
2368 png_write_frame_tail(png_structp png_ptr, png_infop info_ptr)
2370 png_debug(1, "in png_write_frame_tail");
2372 png_ptr->num_frames_written++;
2374 PNG_UNUSED(info_ptr)
2376 #endif /* PNG_WRITE_APNG_SUPPORTED */
2377 #endif /* PNG_WRITE_SUPPORTED */