1LIBPNG(3)                  Library Functions Manual                  LIBPNG(3)
2
3
4

NAME

6       libpng - Portable Network Graphics (PNG) Reference Library 1.6.34
7

SYNOPSIS

9        #include <png.h>
10
11       png_uint_32 png_access_version_number (void);
12
13       void png_benign_error (png_structp png_ptr, png_const_charp error);
14
15       void png_build_grayscale_palette (int bit_depth, png_colorp palette);
16
17       png_voidp png_calloc (png_structp png_ptr, png_alloc_size_t size);
18
19       void   png_chunk_benign_error   (png_structp  png_ptr,  png_const_charp
20       error);
21
22       void png_chunk_error (png_structp png_ptr, png_const_charp error);
23
24       void png_chunk_warning (png_structp png_ptr, png_const_charp message);
25
26       void png_convert_from_struct_tm  (png_timep  ptime,  struct  tm  FAR  *
27       ttime);
28
29       void png_convert_from_time_t (png_timep ptime, time_t ttime);
30
31       png_charp   png_convert_to_rfc1123   (png_structp   png_ptr,  png_timep
32       ptime);
33
34       png_infop png_create_info_struct (png_structp png_ptr);
35
36       png_structp   png_create_read_struct   (png_const_charp   user_png_ver,
37       png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn);
38
39       png_structp   png_create_read_struct_2  (png_const_charp  user_png_ver,
40       png_voidp error_ptr,  png_error_ptr  error_fn,  png_error_ptr  warn_fn,
41       png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn);
42
43       png_structp   png_create_write_struct   (png_const_charp  user_png_ver,
44       png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn);
45
46       png_structp  png_create_write_struct_2  (png_const_charp  user_png_ver,
47       png_voidp  error_ptr,  png_error_ptr  error_fn,  png_error_ptr warn_fn,
48       png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn);
49
50       void  png_data_freer  (png_structp  png_ptr,  png_infop  info_ptr,  int
51       freer, png_uint_32 mask));
52
53       void    png_destroy_info_struct    (png_structp   png_ptr,   png_infopp
54       info_ptr_ptr);
55
56       void  png_destroy_read_struct  (png_structpp  png_ptr_ptr,   png_infopp
57       info_ptr_ptr, png_infopp end_info_ptr_ptr);
58
59       void  png_destroy_write_struct  (png_structpp  png_ptr_ptr,  png_infopp
60       info_ptr_ptr);
61
62       void png_err (png_structp png_ptr);
63
64       void png_error (png_structp png_ptr, png_const_charp error);
65
66       void png_free (png_structp png_ptr, png_voidp ptr);
67
68       void png_free_chunk_list (png_structp png_ptr);
69
70       void png_free_default (png_structp png_ptr, png_voidp ptr);
71
72       void png_free_data (png_structp png_ptr, png_infop info_ptr, int num);
73
74       png_byte png_get_bit_depth (png_const_structp png_ptr,  png_const_infop
75       info_ptr);
76
77       png_uint_32    png_get_bKGD   (png_const_structp   png_ptr,   png_infop
78       info_ptr, png_color_16p *background);
79
80       png_byte png_get_channels (png_const_structp  png_ptr,  png_const_infop
81       info_ptr);
82
83       png_uint_32  png_get_cHRM  (png_const_structp  png_ptr, png_const_infop
84       info_ptr, double  *white_x,  double  *white_y,  double  *red_x,  double
85       *red_y,  double  *green_x,  double  *green_y,  double  *blue_x,  double
86       *blue_y);
87
88       png_uint_32     png_get_cHRM_fixed     (png_const_structp      png_ptr,
89       png_const_infop  info_ptr,  png_uint_32 *white_x, png_uint_32 *white_y,
90       png_uint_32   *red_x,   png_uint_32   *red_y,   png_uint_32   *green_x,
91       png_uint_32 *green_y, png_uint_32 *blue_x, png_uint_32 *blue_y);
92
93       png_uint_32   png_get_cHRM_XYZ  (png_structp  png_ptr,  png_const_infop
94       info_ptr, double *red_X, double *red_Y, double *red_Z, double *green_X,
95       double  *green_Y, double *green_Z, double *blue_X, double *blue_Y, dou‐
96       ble *blue_Z);
97
98       png_uint_32      png_get_cHRM_XYZ_fixed      (png_structp      png_ptr,
99       png_const_infop  info_ptr,  png_fixed_point *int_red_X, png_fixed_point
100       *int_red_Y, png_fixed_point *int_red_Z,  png_fixed_point  *int_green_X,
101       png_fixed_point     *int_green_Y,     png_fixed_point     *int_green_Z,
102       png_fixed_point     *int_blue_X,      png_fixed_point      *int_blue_Y,
103       png_fixed_point *int_blue_Z);
104
105       png_uint_32 png_get_chunk_cache_max (png_const_structp png_ptr);
106
107       png_alloc_size_t png_get_chunk_malloc_max (png_const_structp png_ptr);
108
109       png_byte png_get_color_type (png_const_structp png_ptr, png_const_infop
110       info_ptr);
111
112       png_uint_32     png_get_compression_buffer_size      (png_const_structp
113       png_ptr);
114
115       png_byte     png_get_compression_type    (png_const_structp    png_ptr,
116       png_const_infop info_ptr);
117
118       png_byte png_get_copyright (png_const_structp png_ptr);
119
120       png_uint_32 png_get_current_row_number (png_const_structp);
121
122       png_byte png_get_current_pass_number (png_const_structp);
123
124       png_voidp png_get_error_ptr (png_const_structp png_ptr);
125
126       png_byte      png_get_filter_type      (png_const_structp      png_ptr,
127       png_const_infop info_ptr);
128
129       png_uint_32  png_get_gAMA  (png_const_structp  png_ptr, png_const_infop
130       info_ptr, double *file_gamma);
131
132       png_uint_32     png_get_gAMA_fixed     (png_const_structp      png_ptr,
133       png_const_infop info_ptr, png_uint_32 *int_file_gamma);
134
135       png_byte png_get_header_ver (png_const_structp png_ptr);
136
137       png_byte png_get_header_version (png_const_structp png_ptr);
138
139       png_uint_32  png_get_eXIf  (png_const_structp  png_ptr, png_const_infop
140       info_ptr, png_bytep *exif);
141
142       png_uint_32 png_get_eXIf_1 (png_const_structp png_ptr,  png_const_infop
143       info_ptr, png_unit_32 *num_exif, png_bytep *exif);
144
145       png_uint_32  png_get_hIST  (png_const_structp  png_ptr, png_const_infop
146       info_ptr, png_uint_16p *hist);
147
148       png_uint_32 png_get_iCCP  (png_const_structp  png_ptr,  png_const_infop
149       info_ptr,  png_charpp  name, int *compression_type, png_bytepp profile,
150       png_uint_32 *proflen);
151
152       png_uint_32  png_get_IHDR  (png_structp  png_ptr,  png_infop  info_ptr,
153       png_uint_32   *width,   png_uint_32   *height,   int   *bit_depth,  int
154       *color_type, int  *interlace_type,  int  *compression_type,  int  *fil‐
155       ter_type);
156
157       png_uint_32     png_get_image_height     (png_const_structp    png_ptr,
158       png_const_infop info_ptr);
159
160       png_uint_32     png_get_image_width     (png_const_structp     png_ptr,
161       png_const_infop info_ptr);
162
163       png_int_32 png_get_int_32 (png_bytep buf);
164
165       png_byte     png_get_interlace_type     (png_const_structp     png_ptr,
166       png_const_infop info_ptr);
167
168       png_uint_32 png_get_io_chunk_type (png_const_structp png_ptr);
169
170       png_voidp png_get_io_ptr (png_structp png_ptr);
171
172       png_uint_32 png_get_io_state (png_structp png_ptr);
173
174       png_byte png_get_libpng_ver (png_const_structp png_ptr);
175
176       int  png_get_palette_max(png_const_structp   png_ptr,   png_const_infop
177       info_ptr);
178
179       png_voidp png_get_mem_ptr (png_const_structp png_ptr);
180
181       png_uint_32  png_get_oFFs  (png_const_structp  png_ptr, png_const_infop
182       info_ptr,   png_uint_32   *offset_x,   png_uint_32    *offset_y,    int
183       *unit_type);
184
185       png_uint_32  png_get_pCAL  (png_const_structp  png_ptr, png_const_infop
186       info_ptr, png_charp  *purpose,  png_int_32  *X0,  png_int_32  *X1,  int
187       *type, int *nparams, png_charp *units, png_charpp *params);
188
189       png_uint_32  png_get_pHYs  (png_const_structp  png_ptr, png_const_infop
190       info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type);
191
192       float    png_get_pixel_aspect_ratio     (png_const_structp     png_ptr,
193       png_const_infop info_ptr);
194
195       png_uint_32      png_get_pHYs_dpi      (png_const_structp      png_ptr,
196       png_const_infop info_ptr, png_uint_32 *res_x, png_uint_32  *res_y,  int
197       *unit_type);
198
199       png_fixed_point   png_get_pixel_aspect_ratio_fixed   (png_const_structp
200       png_ptr, png_const_infop info_ptr);
201
202       png_uint_32   png_get_pixels_per_inch    (png_const_structp    png_ptr,
203       png_const_infop info_ptr);
204
205       png_uint_32    png_get_pixels_per_meter   (png_const_structp   png_ptr,
206       png_const_infop info_ptr);
207
208       png_voidp png_get_progressive_ptr (png_const_structp png_ptr);
209
210       png_uint_32 png_get_PLTE  (png_const_structp  png_ptr,  png_const_infop
211       info_ptr, png_colorp *palette, int *num_palette);
212
213       png_byte png_get_rgb_to_gray_status (png_const_structp png_ptr);
214
215       png_uint_32      png_get_rowbytes      (png_const_structp      png_ptr,
216       png_const_infop info_ptr);
217
218       png_bytepp  png_get_rows  (png_const_structp  png_ptr,  png_const_infop
219       info_ptr);
220
221       png_uint_32    png_get_sBIT   (png_const_structp   png_ptr,   png_infop
222       info_ptr, png_color_8p *sig_bit);
223
224       void png_get_sCAL (png_const_structp png_ptr, png_const_infop info_ptr,
225       int* unit, double* width, double* height);
226
227       void  png_get_sCAL_fixed  (png_const_structp  png_ptr,  png_const_infop
228       info_ptr, int* unit, png_fixed_pointp width, png_fixed_pointp height);
229
230       void   png_get_sCAL_s   (png_const_structp   png_ptr,   png_const_infop
231       info_ptr, int* unit, png_charpp width, png_charpp height);
232
233       png_bytep   png_get_signature   (png_const_structp  png_ptr,  png_infop
234       info_ptr);
235
236       png_uint_32 png_get_sPLT  (png_const_structp  png_ptr,  png_const_infop
237       info_ptr, png_spalette_p *splt_ptr);
238
239       png_uint_32  png_get_sRGB  (png_const_structp  png_ptr, png_const_infop
240       info_ptr, int *file_srgb_intent);
241
242       png_uint_32 png_get_text  (png_const_structp  png_ptr,  png_const_infop
243       info_ptr, png_textp *text_ptr, int *num_text);
244
245       png_uint_32    png_get_tIME   (png_const_structp   png_ptr,   png_infop
246       info_ptr, png_timep *mod_time);
247
248       png_uint_32   png_get_tRNS   (png_const_structp   png_ptr,    png_infop
249       info_ptr,   png_bytep   *trans_alpha,   int  *num_trans,  png_color_16p
250       *trans_color);
251
252       /* This function is really an inline macro. */
253
254       png_uint_16 png_get_uint_16 (png_bytep buf);
255
256       png_uint_32 png_get_uint_31 (png_structp png_ptr, png_bytep buf);
257
258       /* This function is really an inline macro. */
259
260       png_uint_32 png_get_uint_32 (png_bytep buf);
261
262       png_uint_32    png_get_unknown_chunks    (png_const_structp    png_ptr,
263       png_const_infop info_ptr, png_unknown_chunkpp unknowns);
264
265       png_voidp png_get_user_chunk_ptr (png_const_structp png_ptr);
266
267       png_uint_32 png_get_user_height_max (png_const_structp png_ptr);
268
269       png_voidp png_get_user_transform_ptr (png_const_structp png_ptr);
270
271       png_uint_32 png_get_user_width_max (png_const_structp png_ptr);
272
273       png_uint_32  png_get_valid  (png_const_structp png_ptr, png_const_infop
274       info_ptr, png_uint_32 flag);
275
276       float     png_get_x_offset_inches      (png_const_structp      png_ptr,
277       png_const_infop info_ptr);
278
279       png_fixed_point   png_get_x_offset_inches_fixed  (png_structp  png_ptr,
280       png_const_infop info_ptr);
281
282       png_int_32   png_get_x_offset_microns    (png_const_structp    png_ptr,
283       png_const_infop info_ptr);
284
285       png_int_32    png_get_x_offset_pixels    (png_const_structp    png_ptr,
286       png_const_infop info_ptr);
287
288       png_uint_32   png_get_x_pixels_per_inch   (png_const_structp   png_ptr,
289       png_const_infop info_ptr);
290
291       png_uint_32   png_get_x_pixels_per_meter   (png_const_structp  png_ptr,
292       png_const_infop info_ptr);
293
294       float     png_get_y_offset_inches      (png_const_structp      png_ptr,
295       png_const_infop info_ptr);
296
297       png_fixed_point   png_get_y_offset_inches_fixed  (png_structp  png_ptr,
298       png_const_infop info_ptr);
299
300       png_int_32   png_get_y_offset_microns    (png_const_structp    png_ptr,
301       png_const_infop info_ptr);
302
303       png_int_32    png_get_y_offset_pixels    (png_const_structp    png_ptr,
304       png_const_infop info_ptr);
305
306       png_uint_32   png_get_y_pixels_per_inch   (png_const_structp   png_ptr,
307       png_const_infop info_ptr);
308
309       png_uint_32   png_get_y_pixels_per_meter   (png_const_structp  png_ptr,
310       png_const_infop info_ptr);
311
312       int png_handle_as_unknown (png_structp png_ptr, png_bytep chunk_name);
313
314       int  png_image_begin_read_from_file  (png_imagep  image,   const   char
315       *file_name);
316
317       int png_image_begin_read_from_stdio (png_imagep image, FILE* file);
318
319       int,      png_image_begin_read_from_memory      (png_imagep      image,
320       png_const_voidp memory, png_size_t size);
321
322       int png_image_finish_read  (png_imagep  image,  png_colorp  background,
323       void *buffer, png_int_32 row_stride, void *colormap);
324
325       void png_image_free (png_imagep image);
326
327       int  png_image_write_to_file  (png_imagep  image, const char *file, int
328       convert_to_8bit, const void *buffer, png_int_32 row_stride, void  *col‐
329       ormap);
330
331       int   png_image_write_to_memory   (png_imagep   image,   void  *memory,
332       png_alloc_size_t *  PNG_RESTRICT  memory_bytes,  int  convert_to_8_bit,
333       const void *buffer, png_int_32 row_stride, const void *colormap));
334
335       int  png_image_write_to_stdio  (png_imagep  image, FILE *file, int con‐
336       vert_to_8_bit, const void *buffer, png_int_32  row_stride,  void  *col‐
337       ormap));
338
339       void      png_info_init_3      (png_infopp     info_ptr,     png_size_t
340       png_info_struct_size);
341
342       void png_init_io (png_structp png_ptr, FILE *fp);
343
344       void png_longjmp (png_structp png_ptr, int val);
345
346       png_voidp png_malloc (png_structp png_ptr, png_alloc_size_t size);
347
348       png_voidp  png_malloc_default  (png_structp  png_ptr,  png_alloc_size_t
349       size);
350
351       png_voidp png_malloc_warn (png_structp png_ptr, png_alloc_size_t size);
352
353       png_uint_32  png_permit_mng_features  (png_structp png_ptr, png_uint_32
354       mng_features_permitted);
355
356       void  png_process_data  (png_structp   png_ptr,   png_infop   info_ptr,
357       png_bytep buffer, png_size_t buffer_size);
358
359       png_size_t png_process_data_pause (png_structp, int save);
360
361       png_uint_32 png_process_data_skip (png_structp);
362
363       void   png_progressive_combine_row   (png_structp   png_ptr,  png_bytep
364       old_row, png_bytep new_row);
365
366       void png_read_end (png_structp png_ptr, png_infop info_ptr);
367
368       void png_read_image (png_structp png_ptr, png_bytepp image);
369
370       void png_read_info (png_structp png_ptr, png_infop info_ptr);
371
372       void png_read_png (png_structp png_ptr, png_infop info_ptr, int  trans‐
373       forms, png_voidp params);
374
375       void  png_read_row  (png_structp png_ptr, png_bytep row, png_bytep dis‐
376       play_row);
377
378       void png_read_rows (png_structp  png_ptr,  png_bytepp  row,  png_bytepp
379       display_row, png_uint_32 num_rows);
380
381       void png_read_update_info (png_structp png_ptr, png_infop info_ptr);
382
383       int png_reset_zstream (png_structp png_ptr);
384
385       void png_save_int_32 (png_bytep buf, png_int_32 i);
386
387       void png_save_uint_16 (png_bytep buf, unsigned int i);
388
389       void png_save_uint_32 (png_bytep buf, png_uint_32 i);
390
391       void  png_set_add_alpha  (png_structp  png_ptr, png_uint_32 filler, int
392       flags);
393
394       void png_set_alpha_mode (png_structp png_ptr,  int  mode,  double  out‐
395       put_gamma);
396
397       void   png_set_alpha_mode_fixed   (png_structp   png_ptr,   int   mode,
398       png_fixed_point output_gamma);
399
400       void  png_set_background  (png_structp  png_ptr,  png_color_16p   back‐
401       ground_color,  int background_gamma_code, int need_expand, double back‐
402       ground_gamma);
403
404       void png_set_background_fixed (png_structp png_ptr, png_color_16p back‐
405       ground_color,  int  background_gamma_code, int need_expand, png_uint_32
406       background_gamma);
407
408       void png_set_benign_errors (png_structp png_ptr, int allowed);
409
410       void png_set_bgr (png_structp png_ptr);
411
412       void   png_set_bKGD   (png_structp   png_ptr,    png_infop    info_ptr,
413       png_color_16p background);
414
415       void    png_set_check_for_invalid_index(png_structrp    png_ptr,    int
416       allowed);
417
418       void png_set_cHRM  (png_structp  png_ptr,  png_infop  info_ptr,  double
419       white_x,  double  white_y,  double red_x, double red_y, double green_x,
420       double green_y, double blue_x, double blue_y);
421
422       void  png_set_cHRM_fixed  (png_structp  png_ptr,  png_infop   info_ptr,
423       png_uint_32    white_x,   png_uint_32   white_y,   png_uint_32   red_x,
424       png_uint_32   red_y,   png_uint_32   green_x,   png_uint_32    green_y,
425       png_uint_32 blue_x, png_uint_32 blue_y);
426
427       void  png_set_cHRM_XYZ (png_structp png_ptr, png_infop info_ptr, double
428       red_X, double red_Y, double red_Z, double green_X, double green_Y, dou‐
429       ble green_Z, double blue_X, double blue_Y, double blue_Z);
430
431       void  png_set_cHRM_XYZ_fixed  (png_structp png_ptr, png_infop info_ptr,
432       png_fixed_point int_red_X, png_fixed_point  int_red_Y,  png_fixed_point
433       int_red_Z,  png_fixed_point  int_green_X,  png_fixed_point int_green_Y,
434       png_fixed_point      int_green_Z,      png_fixed_point      int_blue_X,
435       png_fixed_point int_blue_Y, png_fixed_point int_blue_Z);
436
437       void    png_set_chunk_cache_max   (png_structp   png_ptr,   png_uint_32
438       user_chunk_cache_max);
439
440       void png_set_compression_level (png_structp png_ptr, int level);
441
442       void   png_set_compression_mem_level    (png_structp    png_ptr,    int
443       mem_level);
444
445       void png_set_compression_method (png_structp png_ptr, int method);
446
447       void png_set_compression_strategy (png_structp png_ptr, int strategy);
448
449       void  png_set_compression_window_bits  (png_structp  png_ptr,  int win‐
450       dow_bits);
451
452       void png_set_crc_action  (png_structp  png_ptr,  int  crit_action,  int
453       ancil_action);
454
455       void   png_set_error_fn   (png_structp  png_ptr,  png_voidp  error_ptr,
456       png_error_ptr error_fn, png_error_ptr warning_fn);
457
458       void png_set_expand (png_structp png_ptr);
459
460       void png_set_expand_16 (png_structp png_ptr);
461
462       void png_set_expand_gray_1_2_4_to_8 (png_structp png_ptr);
463
464       void  png_set_filler  (png_structp  png_ptr,  png_uint_32  filler,  int
465       flags);
466
467       void png_set_filter (png_structp png_ptr, int method, int filters);
468
469       void   png_set_filter_heuristics   (png_structp  png_ptr,  int  heuris‐
470       tic_method, int num_weights,  png_doublep  filter_weights,  png_doublep
471       filter_costs);
472
473       void  png_set_filter_heuristics_fixed (png_structp png_ptr, int heuris‐
474       tic_method,   int   num_weights,   png_fixed_point_p    filter_weights,
475       png_fixed_point_p filter_costs);
476
477       void png_set_flush (png_structp png_ptr, int nrows);
478
479       void  png_set_gamma  (png_structp  png_ptr, double screen_gamma, double
480       default_file_gamma);
481
482       void    png_set_gamma_fixed    (png_structp    png_ptr,     png_uint_32
483       screen_gamma, png_uint_32 default_file_gamma);
484
485       void  png_set_gAMA  (png_structp  png_ptr,  png_infop  info_ptr, double
486       file_gamma);
487
488       void  png_set_gAMA_fixed  (png_structp  png_ptr,  png_infop   info_ptr,
489       png_uint_32 file_gamma);
490
491       void png_set_gray_1_2_4_to_8 (png_structp png_ptr);
492
493       void png_set_gray_to_rgb (png_structp png_ptr);
494
495       void  png_set_eXIf  (png_structp png_ptr, png_infop info_ptr, png_bytep
496       exif);
497
498       void png_set_eXIf_1 (png_structp  png_ptr,  png_infop  info_ptr,  const
499       png_uint_32 num_exif, png_bytep exif);
500
501       void    png_set_hIST    (png_structp   png_ptr,   png_infop   info_ptr,
502       png_uint_16p hist);
503
504       void   png_set_iCCP   (png_structp   png_ptr,    png_infop    info_ptr,
505       png_const_charp  name,  int  compression_type, png_const_bytep profile,
506       png_uint_32 proflen);
507
508       int png_set_interlace_handling (png_structp png_ptr);
509
510       void png_set_invalid  (png_structp  png_ptr,  png_infop  info_ptr,  int
511       mask);
512
513       void png_set_invert_alpha (png_structp png_ptr);
514
515       void png_set_invert_mono (png_structp png_ptr);
516
517       void png_set_IHDR (png_structp png_ptr, png_infop info_ptr, png_uint_32
518       width, png_uint_32 height, int bit_depth, int  color_type,  int  inter‐
519       lace_type, int compression_type, int filter_type);
520
521       void   png_set_keep_unknown_chunks   (png_structp  png_ptr,  int  keep,
522       png_bytep chunk_list, int num_chunks);
523
524       jmp_buf*  png_set_longjmp_fn  (png_structp   png_ptr,   png_longjmp_ptr
525       longjmp_fn, size_t jmp_buf_size);
526
527       void  png_set_chunk_malloc_max  (png_structp  png_ptr, png_alloc_size_t
528       user_chunk_cache_max);
529
530       void png_set_compression_buffer_size (png_structp png_ptr,  png_uint_32
531       size);
532
533       void  png_set_mem_fn  (png_structp png_ptr, png_voidp mem_ptr, png_mal‐
534       loc_ptr malloc_fn, png_free_ptr free_fn);
535
536       void png_set_oFFs (png_structp png_ptr, png_infop info_ptr, png_uint_32
537       offset_x, png_uint_32 offset_y, int unit_type);
538
539       int png_set_option(png_structrp png_ptr, int option, int onoff);
540
541       void png_set_packing (png_structp png_ptr);
542
543       void png_set_packswap (png_structp png_ptr);
544
545       void png_set_palette_to_rgb (png_structp png_ptr);
546
547       void  png_set_pCAL  (png_structp png_ptr, png_infop info_ptr, png_charp
548       purpose, png_int_32 X0, png_int_32 X1, int type, int nparams, png_charp
549       units, png_charpp params);
550
551       void png_set_pHYs (png_structp png_ptr, png_infop info_ptr, png_uint_32
552       res_x, png_uint_32 res_y, int unit_type);
553
554       void png_set_progressive_read_fn (png_structp png_ptr,  png_voidp  pro‐
555       gressive_ptr, png_progressive_info_ptr info_fn, png_progressive_row_ptr
556       row_fn, png_progressive_end_ptr end_fn);
557
558       void png_set_PLTE (png_structp png_ptr, png_infop info_ptr,  png_colorp
559       palette, int num_palette);
560
561       void  png_set_quantize  (png_structp  png_ptr,  png_colorp palette, int
562       num_palette, int maximum_colors, png_uint_16p histogram, int full_quan‐
563       tize);
564
565       void png_set_read_fn (png_structp png_ptr, png_voidp io_ptr, png_rw_ptr
566       read_data_fn);
567
568       void png_set_read_status_fn (png_structp  png_ptr,  png_read_status_ptr
569       read_row_fn);
570
571       void   png_set_read_user_chunk_fn   (png_structp   png_ptr,   png_voidp
572       user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn);
573
574       void     png_set_read_user_transform_fn      (png_structp      png_ptr,
575       png_user_transform_ptr read_user_transform_fn);
576
577       void png_set_rgb_to_gray (png_structp png_ptr, int error_action, double
578       red, double green);
579
580       void png_set_rgb_to_gray_fixed (png_structp png_ptr,  int  error_action
581       png_uint_32 red, png_uint_32 green);
582
583       void  png_set_rows (png_structp png_ptr, png_infop info_ptr, png_bytepp
584       row_pointers);
585
586       void   png_set_sBIT   (png_structp   png_ptr,    png_infop    info_ptr,
587       png_color_8p sig_bit);
588
589       void  png_set_sCAL  (png_structp png_ptr, png_infop info_ptr, int unit,
590       double width, double height);
591
592       void png_set_sCAL_fixed (png_structp png_ptr, png_infop  info_ptr,  int
593       unit, png_fixed_point width, png_fixed_point height);
594
595       void png_set_sCAL_s (png_structp png_ptr, png_infop info_ptr, int unit,
596       png_charp width, png_charp height);
597
598       void png_set_scale_16 (png_structp png_ptr);
599
600       void png_set_shift (png_structp png_ptr, png_color_8p true_bits);
601
602       void png_set_sig_bytes (png_structp png_ptr, int num_bytes);
603
604       void   png_set_sPLT   (png_structp   png_ptr,    png_infop    info_ptr,
605       png_spalette_p splt_ptr, int num_spalettes);
606
607       void   png_set_sRGB   (png_structp  png_ptr,  png_infop  info_ptr,  int
608       srgb_intent);
609
610       void   png_set_sRGB_gAMA_and_cHRM   (png_structp   png_ptr,   png_infop
611       info_ptr, int srgb_intent);
612
613       void png_set_strip_16 (png_structp png_ptr);
614
615       void png_set_strip_alpha (png_structp png_ptr);
616
617       void   png_set_strip_error_numbers  (png_structp  png_ptr,  png_uint_32
618       strip_mode);
619
620       void png_set_swap (png_structp png_ptr);
621
622       void png_set_swap_alpha (png_structp png_ptr);
623
624       void png_set_text (png_structp png_ptr, png_infop  info_ptr,  png_textp
625       text_ptr, int num_text);
626
627       void png_set_text_compression_level (png_structp png_ptr, int level);
628
629       void   png_set_text_compression_mem_level   (png_structp  png_ptr,  int
630       mem_level);
631
632       void png_set_text_compression_strategy (png_structp png_ptr, int strat‐
633       egy);
634
635       void  png_set_text_compression_window_bits  (png_structp  png_ptr,  int
636       window_bits);
637
638       void   png_set_text_compression_method,   (png_structp   png_ptr,   int
639       method));
640
641       void  png_set_tIME  (png_structp png_ptr, png_infop info_ptr, png_timep
642       mod_time);
643
644       void png_set_tRNS (png_structp png_ptr, png_infop  info_ptr,  png_bytep
645       trans_alpha, int num_trans, png_color_16p trans_color);
646
647       void png_set_tRNS_to_alpha (png_structp png_ptr);
648
649       png_uint_32   png_set_unknown_chunks  (png_structp  png_ptr,  png_infop
650       info_ptr, png_unknown_chunkp unknowns, int num, int location);
651
652       void  png_set_unknown_chunk_location  (png_structp  png_ptr,  png_infop
653       info_ptr, int chunk, int location);
654
655       void     png_set_user_limits    (png_structp    png_ptr,    png_uint_32
656       user_width_max, png_uint_32 user_height_max);
657
658       void  png_set_user_transform_info   (png_structp   png_ptr,   png_voidp
659       user_transform_ptr,  int user_transform_depth, int user_transform_chan‐
660       nels);
661
662       void   png_set_write_fn   (png_structp   png_ptr,   png_voidp   io_ptr,
663       png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn);
664
665       void png_set_write_status_fn (png_structp png_ptr, png_write_status_ptr
666       write_row_fn);
667
668       void     png_set_write_user_transform_fn     (png_structp      png_ptr,
669       png_user_transform_ptr write_user_transform_fn);
670
671       int   png_sig_cmp   (png_bytep   sig,   png_size_t   start,  png_size_t
672       num_to_check);
673
674       void png_start_read_image (png_structp png_ptr);
675
676       void png_warning (png_structp png_ptr, png_const_charp message);
677
678       void  png_write_chunk  (png_structp  png_ptr,   png_bytep   chunk_name,
679       png_bytep data, png_size_t length);
680
681       void   png_write_chunk_data   (png_structp   png_ptr,  png_bytep  data,
682       png_size_t length);
683
684       void png_write_chunk_end (png_structp png_ptr);
685
686       void png_write_chunk_start (png_structp png_ptr, png_bytep  chunk_name,
687       png_uint_32 length);
688
689       void png_write_end (png_structp png_ptr, png_infop info_ptr);
690
691       void png_write_flush (png_structp png_ptr);
692
693       void png_write_image (png_structp png_ptr, png_bytepp image);
694
695       void png_write_info (png_structp png_ptr, png_infop info_ptr);
696
697       void   png_write_info_before_PLTE   (png_structp   png_ptr,   png_infop
698       info_ptr);
699
700       void png_write_png (png_structp png_ptr, png_infop info_ptr, int trans‐
701       forms, png_voidp params);
702
703       void png_write_row (png_structp png_ptr, png_bytep row);
704
705       void  png_write_rows  (png_structp png_ptr, png_bytepp row, png_uint_32
706       num_rows);
707
708       void png_write_sig (png_structp png_ptr);
709
710

DESCRIPTION

712       The libpng library supports encoding, decoding, and  various  manipula‐
713       tions  of  the  Portable Network Graphics (PNG) format image files.  It
714       uses the zlib(3) compression library.   Following  is  a  copy  of  the
715       libpng-manual.txt file that accompanies libpng.
716

LIBPNG.TXT

718       libpng-manual.txt - A description on how to use and modify libpng
719
720        libpng version 1.6.34 - September 29, 2017
721        Updated and distributed by Glenn Randers-Pehrson
722        <glennrp at users.sourceforge.net>
723        Copyright (c) 1998-2017 Glenn Randers-Pehrson
724
725        This document is released under the libpng license.
726        For conditions of distribution and use, see the disclaimer
727        and license in png.h
728
729        Based on:
730
731        libpng  versions  0.97,  January  1998, through 1.6.34 - September 29,
732       2017
733        Updated and distributed by Glenn Randers-Pehrson
734        Copyright (c) 1998-2017 Glenn Randers-Pehrson
735
736        libpng 1.0 beta 6 - version 0.96 - May 28, 1997
737        Updated and distributed by Andreas Dilger
738        Copyright (c) 1996, 1997 Andreas Dilger
739
740        libpng 1.0 beta 2 - version 0.88 - January 26, 1996
741        For conditions of distribution and use, see copyright
742        notice in png.h. Copyright (c) 1995, 1996 Guy Eric
743        Schalnat, Group 42, Inc.
744
745        Updated/rewritten per request in the libpng FAQ
746        Copyright (c) 1995, 1996 Frank J. T. Wojcik
747        December 18, 1995 & January 20, 1996
748
749        TABLE OF CONTENTS
750
751           I. Introduction
752          II. Structures
753         III. Reading
754          IV. Writing
755           V. Simplified API
756          VI. Modifying/Customizing libpng
757         VII. MNG support
758        VIII. Changes to Libpng from version 0.88
759          IX. Changes to Libpng from version 1.0.x to 1.2.x
760           X. Changes to Libpng from version 1.0.x/1.2.x to 1.4.x
761          XI. Changes to Libpng from version 1.4.x to 1.5.x
762         XII. Changes to Libpng from version 1.5.x to 1.6.x
763        XIII. Detecting libpng
764         XIV. Source code repository
765          XV. Coding style
766         XVI. Y2K Compliance in libpng
767
768

I. Introduction

770       This file describes how to use and modify  the  PNG  reference  library
771       (known  as  libpng)  for your own use.  In addition to this file, exam‐
772       ple.c is a good starting point for using the library, as it is  heavily
773       commented  and  should  include  everything  most people will need.  We
774       assume that libpng is already  installed;  see  the  INSTALL  file  for
775       instructions on how to configure and install libpng.
776
777       For  examples  of libpng usage, see the files "example.c", "pngtest.c",
778       and the files in the "contrib" directory, all of which are included  in
779       the libpng distribution.
780
781       Libpng was written as a companion to the PNG specification, as a way of
782       reducing the amount of time and effort it takes to support the PNG file
783       format in application programs.
784
785       The  PNG specification (second edition), November 2003, is available as
786       a W3C Recommendation and as an ISO Standard (ISO/IEC 15948:2004 (E)) at
787       <https://www.w3.org/TR/2003/REC-PNG-20031110/ The W3C and ISO documents
788       have identical technical content.
789
790       The PNG-1.2  specification  is  available  at  <https://png-mng.source
791       forge.io/pub/png/spec/1.2/>.   It  is technically equivalent to the PNG
792       specification (second edition) but has some additional material.
793
794       The PNG-1.0  specification  is  available  as  RFC  2083  <https://png-
795       mng.sourceforge.io/pub/png/spec/1.0/>   and  as  a  W3C  Recommendation
796       <https://www.w3.org/TR/REC-png-961001>.
797
798       Some additional chunks are  described  in  the  special-purpose  public
799       chunks documents at <http://www.libpng.org/pub/png/spec/register/>
800
801       Other  information  about PNG, and the latest version of libpng, can be
802       found at the PNG home page, <http://www.libpng.org/pub/png/>.
803
804       Most users will not have to modify the library significantly;  advanced
805       users may want to modify it more.  All attempts were made to make it as
806       complete as possible, while keeping the code easy to understand.   Cur‐
807       rently,  this  library only supports C.  Support for other languages is
808       being considered.
809
810       Libpng has been designed to handle multiple sessions at one time, to be
811       easily  modifiable,  to  be  portable  to the vast majority of machines
812       (ANSI, K&R, 16-, 32-, and 64-bit) available, and to  be  easy  to  use.
813       The  ultimate  goal  of  libpng is to promote the acceptance of the PNG
814       file format in whatever way possible.  While there is still work to  be
815       done (see the TODO file), libpng should cover the majority of the needs
816       of its users.
817
818       Libpng uses zlib for its compression and decompression  of  PNG  files.
819       Further  information about zlib, and the latest version of zlib, can be
820       found at the zlib home page, <https://zlib.net/>.  The zlib compression
821       utility  is  a general purpose utility that is useful for more than PNG
822       files, and can be used without libpng.  See the documentation delivered
823       with  zlib for more details.  You can usually find the source files for
824       the zlib utility wherever you find the libpng source files.
825
826       Libpng is  thread  safe,  provided  the  threads  are  using  different
827       instances   of  the  structures.   Each  thread  should  have  its  own
828       png_struct and png_info instances, and thus its own image.  Libpng does
829       not  protect  itself  against  two threads using the same instance of a
830       structure.
831
832

II. Structures

834       There are two main structures that are important to libpng,  png_struct
835       and  png_info.  Both are internal structures that are no longer exposed
836       in the libpng interface (as of libpng 1.5.0).
837
838       The png_info structure is designed to provide information about the PNG
839       file.  At one time, the fields of png_info were intended to be directly
840       accessible to the user.  However, this tended to  cause  problems  with
841       applications  using dynamically loaded libraries, and as a result a set
842       of interface functions for png_info (the  png_get_*()  and  png_set_*()
843       functions)  was developed, and direct access to the png_info fields was
844       deprecated..
845
846       The png_struct structure is the object used by the library to decode  a
847       single image.  As of 1.5.0 this structure is also not exposed.
848
849       Almost  all  libpng APIs require a pointer to a png_struct as the first
850       argument.  Many (in particular  the  png_set  and  png_get  APIs)  also
851       require a pointer to png_info as the second argument.  Some application
852       visible macros defined in png.h designed for basic data access (reading
853       and  writing integers in the PNG format) don't take a png_info pointer,
854       but it's almost always safe to assume that a (png_struct*)  has  to  be
855       passed to call an API function.
856
857       You can have more than one png_info structure associated with an image,
858       as illustrated in pngtest.c, one for information  valid  prior  to  the
859       IDAT  chunks  and  another  (called  "end_info" below) for things after
860       them.
861
862       The png.h header file is an invaluable reference for  programming  with
863       libpng.   And  while I'm on the topic, make sure you include the libpng
864       header file:
865
866       #include <png.h>
867
868       and also (as of libpng-1.5.0) the zlib header file, if you need it:
869
870       #include <zlib.h>
871
872
873   Types
874       The png.h header file defines a number of integral types  used  by  the
875       APIs.   Most of these are fairly obvious; for example types correspond‐
876       ing to integers of particular sizes and types for passing color values.
877
878       One exception is how non-integral numbers are handled.  For application
879       convenience most APIs that take such numbers have C (double) arguments;
880       however, internally PNG, and libpng, use 32  bit  signed  integers  and
881       encode  the value by multiplying by 100,000.  As of libpng 1.5.0 a con‐
882       venience  macro  PNG_FP_1  is  defined  in  png.h  along  with  a  type
883       (png_fixed_point) which is simply (png_int_32).
884
885       All  APIs  that  take  (double) arguments also have a matching API that
886       takes the corresponding fixed point integer arguments.  The fixed point
887       API has the same name as the floating point one with "_fixed" appended.
888       The actual range of values permitted in the  APIs  is  frequently  less
889       than the full range of (png_fixed_point) (-21474 to +21474).  When APIs
890       require a non-negative argument the type  is  recorded  as  png_uint_32
891       above.   Consult  the  header file and the text below for more informa‐
892       tion.
893
894       Special care must be take with sCAL chunk handling  because  the  chunk
895       itself  uses  non-integral values encoded as strings containing decimal
896       floating point numbers.  See the comments in the header file.
897
898
899   Configuration
900       The main header file function declarations are frequently protected  by
901       C preprocessing directives of the form:
902
903           #ifdef PNG_feature_SUPPORTED
904           declare-function
905           #endif
906           ...
907           #ifdef PNG_feature_SUPPORTED
908           use-function
909           #endif
910
911       The  library  can  be  built without support for these APIs, although a
912       standard build will have all implemented  APIs.   Application  programs
913       should  check the feature macros before using an API for maximum porta‐
914       bility.  From libpng 1.5.0 the feature macros set during the  build  of
915       libpng  are recorded in the header file "pnglibconf.h" and this file is
916       always included by png.h.
917
918       If you don't need to change the library configuration from the default,
919       skip to the next section ("Reading").
920
921       Notice  that  some  of the makefiles in the 'scripts' directory and (in
922       1.5.0) all of the build project files in the 'projects' directory  sim‐
923       ply  copy  scripts/pnglibconf.h.prebuilt  to  pnglibconf.h.  This means
924       that these build systems do not permit easy auto-configuration  of  the
925       library - they only support the default configuration.
926
927       The  easiest way to make minor changes to the libpng configuration when
928       auto-configuration is supported is to add definitions  to  the  command
929       line using (typically) CPPFLAGS.  For example:
930
931       CPPFLAGS=-DPNG_NO_FLOATING_ARITHMETIC
932
933       will  change  the internal libpng math implementation for gamma correc‐
934       tion and other arithmetic calculations to  fixed  point,  avoiding  the
935       need  for  fast  floating point support.  The result can be seen in the
936       generated pnglibconf.h - make sure  it  contains  the  changed  feature
937       macro setting.
938
939       If  you  need  to make more extensive configuration changes - more than
940       one or two feature macro settings - you can either add  -DPNG_USER_CON‐
941       FIG  to the build command line and put a list of feature macro settings
942       in pngusr.h or you can set DFA_XTRA (a makefile  variable)  to  a  file
943       containing the same information in the form of 'option' settings.
944
945       A. Changing pnglibconf.h
946
947       A  variety  of methods exist to build libpng.  Not all of these support
948       reconfiguration of pnglibconf.h.  To reconfigure pnglibconf.h  it  must
949       either  be  rebuilt from scripts/pnglibconf.dfa using awk or it must be
950       edited by hand.
951
952       Hand editing is achieved by  copying  scripts/pnglibconf.h.prebuilt  to
953       pnglibconf.h  and  changing  the lines defining the supported features,
954       paying  very  close  attention   to   the   'option'   information   in
955       scripts/pnglibconf.dfa that describes those features and their require‐
956       ments.  This is easy to get wrong.
957
958       B. Configuration using DFA_XTRA
959
960       Rebuilding from pnglibconf.dfa is easy if a  functioning  'awk',  or  a
961       later  variant  such  as 'nawk' or 'gawk', is available.  The configure
962       build will automatically find an  appropriate  awk  and  build  pnglib‐
963       conf.h.   The  scripts/pnglibconf.mak file contains a set of make rules
964       for doing the same thing if configure is not  used,  and  many  of  the
965       makefiles in the scripts directory use this approach.
966
967       When  rebuilding simply write a new file containing changed options and
968       set DFA_XTRA to the name of this file.  This causes the build to append
969       the new file to the end of scripts/pnglibconf.dfa.  The pngusr.dfa file
970       should contain lines of the following forms:
971
972       everything = off
973
974       This turns all optional features off.   Include  it  at  the  start  of
975       pngusr.dfa  to  make  it  easier to build a minimal configuration.  You
976       will need to turn at least some features on afterward to enable  either
977       reading or writing code, or both.
978
979       option feature on option feature off
980
981       Enable  or  disable  a  single feature.  This will automatically enable
982       other features required by a feature that is turned on or disable other
983       features  that require a feature which is turned off.  Conflicting set‐
984       tings will cause an error message to be emitted by awk.
985
986       setting feature default value
987
988       Changes the default value of setting 'feature' to 'value'.  There are a
989       small  number  of  settings listed at the top of pnglibconf.h, they are
990       documented in the source code.  Most of these values  have  performance
991       implications for the library but most of them have no visible effect on
992       the API.  Some can also be overridden from the API.
993
994       This method of building a customized  pnglibconf.h  is  illustrated  in
995       contrib/pngminim/*.   See  the "$(PNGCONF):" target in the makefile and
996       pngusr.dfa in these directories.
997
998       C. Configuration using PNG_USER_CONFIG
999
1000       If -DPNG_USER_CONFIG is added to  the  CPPFLAGS  when  pnglibconf.h  is
1001       built,  the  file  pngusr.h  will  automatically be included before the
1002       options in scripts/pnglibconf.dfa are processed.   Your  pngusr.h  file
1003       should  contain  only  macro  definitions turning features on or off or
1004       setting settings.
1005
1006       Apart from the global setting "everything = off" all the options listed
1007       above can be set using macros in pngusr.h:
1008
1009       #define PNG_feature_SUPPORTED
1010
1011       is equivalent to:
1012
1013       option feature on
1014
1015       #define PNG_NO_feature
1016
1017       is equivalent to:
1018
1019       option feature off
1020
1021       #define PNG_feature value
1022
1023       is equivalent to:
1024
1025       setting feature default value
1026
1027       Notice that in both cases, pngusr.dfa and pngusr.h, the contents of the
1028       pngusr file you supply override the contents of scripts/pnglibconf.dfa
1029
1030       If confusing or incomprehensible behavior results  it  is  possible  to
1031       examine  the  intermediate  file pnglibconf.dfn to find the full set of
1032       dependency information for each setting and option.  Simply locate  the
1033       feature in the file and read the C comments that precede it.
1034
1035       This method is also illustrated in the contrib/pngminim/* makefiles and
1036       pngusr.h.
1037
1038

III. Reading

1040       We'll now walk you through the possible functions to call when  reading
1041       in  a  PNG file sequentially, briefly explaining the syntax and purpose
1042       of each one.  See example.c and png.h for more detail.  While  progres‐
1043       sive  reading  is covered in the next section, you will still need some
1044       of the functions discussed in this section to read a PNG file.
1045
1046
1047   Setup
1048       You will want to do the  I/O  initialization(*)  before  you  get  into
1049       libpng, so if it doesn't work, you don't have much to undo.  Of course,
1050       you will also want to insure that you are, in fact, dealing with a  PNG
1051       file.   Libpng  provides a simple check to see if a file is a PNG file.
1052       To use it, pass in the first 1 to 8 bytes of the file to  the  function
1053       png_sig_cmp(), and it will return 0 (false) if the bytes match the cor‐
1054       responding bytes of the PNG signature, or nonzero (true) otherwise.  Of
1055       course,  the  more  bytes  you pass in, the greater the accuracy of the
1056       prediction.
1057
1058       If you are intending to keep the file pointer open for use  in  libpng,
1059       you  must ensure you don't read more than 8 bytes from the beginning of
1060       the file, and you also have to make a call to png_set_sig_bytes()  with
1061       the number of bytes you read from the beginning.  Libpng will then only
1062       check the bytes (if any) that your program didn't read.
1063
1064       (*): If you are not using the standard I/O functions, you will need  to
1065       replace them with custom functions.  See the discussion under Customiz‐
1066       ing libpng.
1067
1068           FILE *fp = fopen(file_name, "rb");
1069           if (!fp)
1070           {
1071              return (ERROR);
1072           }
1073
1074           if (fread(header, 1, number, fp) != number)
1075           {
1076              return (ERROR);
1077           }
1078
1079           is_png = !png_sig_cmp(header, 0, number);
1080           if (!is_png)
1081           {
1082              return (NOT_PNG);
1083           }
1084
1085       Next, png_struct and png_info need to be allocated and initialized.  In
1086       order  to ensure that the size of these structures is correct even with
1087       a dynamically linked libpng, there  are  functions  to  initialize  and
1088       allocate  the  structures.   We also pass the library version, optional
1089       pointers to error handling functions, and a pointer to  a  data  struct
1090       for use by the error functions, if necessary (the pointer and functions
1091       can be NULL if the default error handlers are to  be  used).   See  the
1092       section  on  Changes  to  Libpng below regarding the old initialization
1093       functions.  The structure allocation functions quietly return  NULL  if
1094       they fail to create the structure, so your application should check for
1095       that.
1096
1097           png_structp png_ptr = png_create_read_struct
1098               (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1099               user_error_fn, user_warning_fn);
1100
1101           if (!png_ptr)
1102              return (ERROR);
1103
1104           png_infop info_ptr = png_create_info_struct(png_ptr);
1105
1106           if (!info_ptr)
1107           {
1108              png_destroy_read_struct(&png_ptr,
1109                  (png_infopp)NULL, (png_infopp)NULL);
1110              return (ERROR);
1111           }
1112
1113       If you want to use your own memory allocation routines,  use  a  libpng
1114       that  was  built  with PNG_USER_MEM_SUPPORTED defined, and use png_cre‐
1115       ate_read_struct_2() instead of png_create_read_struct():
1116
1117           png_structp png_ptr = png_create_read_struct_2
1118               (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1119               user_error_fn, user_warning_fn, (png_voidp)
1120               user_mem_ptr, user_malloc_fn, user_free_fn);
1121
1122       The error handling routines passed to png_create_read_struct() and  the
1123       memory  alloc/free  routines  passed  to png_create_struct_2() are only
1124       necessary if you are not using the libpng supplied error  handling  and
1125       memory alloc/free functions.
1126
1127       When  libpng  encounters  an  error, it expects to longjmp back to your
1128       routine.  Therefore, you  will  need  to  call  setjmp  and  pass  your
1129       png_jmpbuf(png_ptr).  If you read the file from different routines, you
1130       will need to update the longjmp buffer every time you enter a new  rou‐
1131       tine that will call a png_*() function.
1132
1133       See  your  documentation  of  setjmp/longjmp for your compiler for more
1134       information on setjmp/longjmp.  See the discussion on libpng error han‐
1135       dling  in  the Customizing Libpng section below for more information on
1136       the libpng error handling.  If an error occurs,  and  libpng  longjmp's
1137       back to your setjmp, you will want to call png_destroy_read_struct() to
1138       free any memory.
1139
1140           if (setjmp(png_jmpbuf(png_ptr)))
1141           {
1142              png_destroy_read_struct(&png_ptr, &info_ptr,
1143                  &end_info);
1144              fclose(fp);
1145              return (ERROR);
1146           }
1147
1148       Pass (png_infopp)NULL instead of &end_info  if  you  didn't  create  an
1149       end_info structure.
1150
1151       If  you would rather avoid the complexity of setjmp/longjmp issues, you
1152       can compile libpng with PNG_NO_SETJMP, in which case errors will result
1153       in a call to PNG_ABORT() which defaults to abort().
1154
1155       You can #define PNG_ABORT() to a function that does something more use‐
1156       ful than abort(), as long as your function does not return.
1157
1158       Now you need to set up the input code.  The default for  libpng  is  to
1159       use  the  C function fread().  If you use this, you will need to pass a
1160       valid FILE * in the function png_init_io().  Be sure that the  file  is
1161       opened  in  binary mode.  If you wish to handle reading data in another
1162       way, you need not call the png_init_io() function, but  you  must  then
1163       implement  the  libpng  I/O methods discussed in the Customizing Libpng
1164       section below.
1165
1166           png_init_io(png_ptr, fp);
1167
1168       If you had previously opened the file and read  any  of  the  signature
1169       from  the beginning in order to see if this was a PNG file, you need to
1170       let libpng know that there are some bytes missing from the start of the
1171       file.
1172
1173           png_set_sig_bytes(png_ptr, number);
1174
1175       You  can change the zlib compression buffer size to be used while read‐
1176       ing compressed data with
1177
1178           png_set_compression_buffer_size(png_ptr, buffer_size);
1179
1180       where the default size is 8192 bytes.  Note that  the  buffer  size  is
1181       changed  immediately and the buffer is reallocated immediately, instead
1182       of setting a flag to be acted upon later.
1183
1184       If you want CRC errors to be handled in a  different  manner  than  the
1185       default, use
1186
1187           png_set_crc_action(png_ptr, crit_action, ancil_action);
1188
1189       The  values  for  png_set_crc_action()  say how libpng is to handle CRC
1190       errors in ancillary and critical chunks, and whether to  use  the  data
1191       contained  therein.  Starting with libpng-1.6.26, this also governs how
1192       an ADLER32 error is handled while reading the IDAT chunk. Note that  it
1193       is impossible to "discard" data in a critical chunk.
1194
1195       Choices for (int) crit_action are
1196          PNG_CRC_DEFAULT      0  error/quit
1197          PNG_CRC_ERROR_QUIT   1  error/quit
1198          PNG_CRC_WARN_USE     3  warn/use data
1199          PNG_CRC_QUIET_USE    4  quiet/use data
1200          PNG_CRC_NO_CHANGE    5  use the current value
1201
1202       Choices for (int) ancil_action are
1203          PNG_CRC_DEFAULT      0  error/quit
1204          PNG_CRC_ERROR_QUIT   1  error/quit
1205          PNG_CRC_WARN_DISCARD 2  warn/discard data
1206          PNG_CRC_WARN_USE     3  warn/use data
1207          PNG_CRC_QUIET_USE    4  quiet/use data
1208          PNG_CRC_NO_CHANGE    5  use the current value
1209
1210       When  the  setting  for  crit_action  is PNG_CRC_QUIET_USE, the CRC and
1211       ADLER32 checksums are not only ignored, but they are not evaluated.
1212
1213
1214   Setting up callback code
1215       You can set up a callback function to handle any unknown chunks in  the
1216       input stream. You must supply the function
1217
1218           read_chunk_callback(png_structp png_ptr,
1219                png_unknown_chunkp chunk);
1220           {
1221              /* The unknown chunk structure contains your
1222                 chunk data, along with similar data for any other
1223                 unknown chunks: */
1224
1225                  png_byte name[5];
1226                  png_byte *data;
1227                  png_size_t size;
1228
1229              /* Note that libpng has already taken care of
1230                 the CRC handling */
1231
1232              /* put your code here.  Search for your chunk in the
1233                 unknown chunk structure, process it, and return one
1234                 of the following: */
1235
1236              return (-n); /* chunk had an error */
1237              return (0); /* did not recognize */
1238              return (n); /* success */
1239           }
1240
1241       (You  can  give  your  function  another  name that you like instead of
1242       "read_chunk_callback")
1243
1244       To inform libpng about your function, use
1245
1246           png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr,
1247               read_chunk_callback);
1248
1249       This names not only the callback function, but also a user pointer that
1250       you can retrieve with
1251
1252           png_get_user_chunk_ptr(png_ptr);
1253
1254       If you call the png_set_read_user_chunk_fn() function, then all unknown
1255       chunks which the callback does not handle will be saved when read.  You
1256       can  cause them to be discarded by returning '1' ("handled") instead of
1257       '0'.  This behavior will change in libpng 1.7 and the default  handling
1258       set  by  the  png_set_keep_unknown_chunks()  function, described below,
1259       will be used when the callback returns 0.  If  you  want  the  existing
1260       behavior  you should set the global default to PNG_HANDLE_CHUNK_IF_SAFE
1261       now; this is compatible with all current versions of  libpng  and  with
1262       1.7.   Libpng 1.6 issues a warning if you keep the default, or PNG_HAN‐
1263       DLE_CHUNK_NEVER, and the callback returns 0.
1264
1265       At this point, you can set up a callback function that will  be  called
1266       after  each  row has been read, which you can use to control a progress
1267       meter or the like.  It's demonstrated in pngtest.c.  You must supply  a
1268       function
1269
1270           void read_row_callback(png_structp png_ptr,
1271              png_uint_32 row, int pass);
1272           {
1273             /* put your code here */
1274           }
1275
1276       (You  can give it another name that you like instead of "read_row_call‐
1277       back")
1278
1279       To inform libpng about your function, use
1280
1281           png_set_read_status_fn(png_ptr, read_row_callback);
1282
1283       When this function is called the row has already been  completely  pro‐
1284       cessed  and  the  'row' and 'pass' refer to the next row to be handled.
1285       For the non-interlaced case the row that was just handled is simply one
1286       less than the passed in row number, and pass will always be 0.  For the
1287       interlaced case the same applies unless the row value is  0,  in  which
1288       case  the  row  just handled was the last one from one of the preceding
1289       passes.  Because interlacing may skip a pass you cannot  be  sure  that
1290       the  preceding  pass  is just 'pass-1'; if you really need to know what
1291       the last pass is record (row,pass) from the callback and use  the  last
1292       recorded value each time.
1293
1294       As  with  the  user  transform  you  can  find the output row using the
1295       PNG_ROW_FROM_PASS_ROW macro.
1296
1297
1298   Unknown-chunk handling
1299       Now you get to set the way the library processes unknown chunks in  the
1300       input  PNG  stream. Both known and unknown chunks will be read.  Normal
1301       behavior is that known chunks will be parsed into information in  vari‐
1302       ous  info_ptr  members  while  unknown  chunks  will be discarded. This
1303       behavior can be wasteful if your application will never use some  known
1304       chunk types. To change this, you can call:
1305
1306           png_set_keep_unknown_chunks(png_ptr, keep,
1307               chunk_list, num_chunks);
1308
1309           keep       - 0: default unknown chunk handling
1310                        1: ignore; do not keep
1311                        2: keep only if safe-to-copy
1312                        3: keep even if unsafe-to-copy
1313
1314                      You can use these definitions:
1315                        PNG_HANDLE_CHUNK_AS_DEFAULT   0
1316                        PNG_HANDLE_CHUNK_NEVER        1
1317                        PNG_HANDLE_CHUNK_IF_SAFE      2
1318                        PNG_HANDLE_CHUNK_ALWAYS       3
1319
1320           chunk_list - list of chunks affected (a byte string,
1321                        five bytes per chunk, NULL or ' ' if
1322                        num_chunks is positive; ignored if
1323                        numchunks <= 0).
1324
1325           num_chunks - number of chunks affected; if 0, all
1326                        unknown chunks are affected.  If positive,
1327                        only the chunks in the list are affected,
1328                        and if negative all unknown chunks and
1329                        all known chunks except for the IHDR,
1330                        PLTE, tRNS, IDAT, and IEND chunks are
1331                        affected.
1332
1333       Unknown  chunks  declared  in this way will be saved as raw data onto a
1334       list of png_unknown_chunk structures.  If  a  chunk  that  is  normally
1335       known  to  libpng  is named in the list, it will be handled as unknown,
1336       according to the "keep" directive.  If a chunk is named  in  successive
1337       instances  of  png_set_keep_unknown_chunks(),  the  final instance will
1338       take precedence.  The IHDR and IEND  chunks  should  not  be  named  in
1339       chunk_list;  if they are, libpng will process them normally anyway.  If
1340       you know that your application will never make use of  some  particular
1341       chunks, use PNG_HANDLE_CHUNK_NEVER (or 1) as demonstrated below.
1342
1343       Here is an example of the usage of png_set_keep_unknown_chunks(), where
1344       the private "vpAg" chunk will later be processed by a user chunk  call‐
1345       back function:
1346
1347           png_byte vpAg[5]={118, 112,  65, 103, (png_byte) ' '};
1348
1349           #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
1350             png_byte unused_chunks[]=
1351             {
1352               104,  73,  83,  84, (png_byte) ' ',   /* hIST */
1353               105,  84,  88, 116, (png_byte) ' ',   /* iTXt */
1354               112,  67,  65,  76, (png_byte) ' ',   /* pCAL */
1355               115,  67,  65,  76, (png_byte) ' ',   /* sCAL */
1356               115,  80,  76,  84, (png_byte) ' ',   /* sPLT */
1357               116,  73,  77,  69, (png_byte) ' ',   /* tIME */
1358             };
1359           #endif
1360
1361           ...
1362
1363           #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
1364             /* ignore all unknown chunks
1365              * (use global setting "2" for libpng16 and earlier):
1366              */
1367             png_set_keep_unknown_chunks(read_ptr, 2, NULL, 0);
1368
1369             /* except for vpAg: */
1370             png_set_keep_unknown_chunks(read_ptr, 2, vpAg, 1);
1371
1372             /* also ignore unused known chunks: */
1373             png_set_keep_unknown_chunks(read_ptr, 1, unused_chunks,
1374                (int)(sizeof unused_chunks)/5);
1375           #endif
1376
1377
1378   User limits
1379       The  PNG specification allows the width and height of an image to be as
1380       large as 2^(31-1 (0x7fffffff), or about 2.147 billion rows and columns.
1381       For  safety,  libpng imposes a default limit of 1 million rows and col‐
1382       umns.  Larger images will be rejected immediately  with  a  png_error()
1383       call. If you wish to change these limits, you can use
1384
1385          png_set_user_limits(png_ptr, width_max, height_max);
1386
1387       to  set your own limits (libpng may reject some very wide images anyway
1388       because of potential buffer overflow conditions).
1389
1390       You should put this statement after you create the  PNG  structure  and
1391       before calling png_read_info(), png_read_png(), or png_process_data().
1392
1393       When  writing  a  PNG  datastream,  put  this  statement before calling
1394       png_write_info() or png_write_png().
1395
1396       If you need to retrieve the limits that are being applied, use
1397
1398          width_max = png_get_user_width_max(png_ptr);
1399          height_max = png_get_user_height_max(png_ptr);
1400
1401       The PNG specification sets no limit on the number of  ancillary  chunks
1402       allowed  in  a PNG datastream.  By default, libpng imposes a limit of a
1403       total of 1000 sPLT, tEXt, iTXt, zTXt, and unknown chunks to be  stored.
1404       If  you  have  set up both info_ptr and end_info_ptr, the limit applies
1405       separately to each.  You can change the limit on the  total  number  of
1406       such chunks that will be stored, with
1407
1408          png_set_chunk_cache_max(png_ptr, user_chunk_cache_max);
1409
1410       where 0x7fffffffL means unlimited.  You can retrieve this limit with
1411
1412          chunk_cache_max = png_get_chunk_cache_max(png_ptr);
1413
1414       Libpng  imposes  a limit of 8 Megabytes (8,000,000 bytes) on the amount
1415       of memory that any chunk other than IDAT can occupy, originally or when
1416       decompressed (prior to libpng-1.6.32 the limit was only applied to com‐
1417       pressed chunks after decompression). You can change this limit with
1418
1419          png_set_chunk_malloc_max(png_ptr, user_chunk_malloc_max);
1420
1421       and you can retrieve the limit with
1422
1423          chunk_malloc_max = png_get_chunk_malloc_max(png_ptr);
1424
1425       Any chunks that would cause either of these limits to be exceeded  will
1426       be ignored.
1427
1428
1429   Information about your system
1430       If  you  intend  to display the PNG or to incorporate it in other image
1431       data you need to tell libpng information about your display or  drawing
1432       surface so that libpng can convert the values in the image to match the
1433       display.
1434
1435       From libpng-1.5.4 this information can be set before  reading  the  PNG
1436       file  header.   In earlier versions png_set_gamma() existed but behaved
1437       incorrectly if called before the PNG file  header  had  been  read  and
1438       png_set_alpha_mode() did not exist.
1439
1440       If  you need to support versions prior to libpng-1.5.4 test the version
1441       number as illustrated below using "PNG_LIBPNG_VER >= 10504" and  follow
1442       the procedures described in the appropriate manual page.
1443
1444       You  give  libpng  the  encoding expected by your system expressed as a
1445       'gamma' value.  You can also specify a default  encoding  for  the  PNG
1446       file  in  case  the  required information is missing from the file.  By
1447       default libpng assumes that the PNG data matches your system,  to  keep
1448       this default call:
1449
1450          png_set_gamma(png_ptr, screen_gamma, output_gamma);
1451
1452       or you can use the fixed point equivalent:
1453
1454          png_set_gamma_fixed(png_ptr, PNG_FP_1*screen_gamma,
1455             PNG_FP_1*output_gamma);
1456
1457       If you don't know the gamma for your system it is probably 2.2 - a good
1458       approximation to the IEC  standard  for  display  systems  (sRGB).   If
1459       images  are too contrasty or washed out you got the value wrong - check
1460       your system documentation!
1461
1462       Many systems permit the system gamma to be changed via a  lookup  table
1463       in  the display driver, a few systems, including older Macs, change the
1464       response by default.  As of 1.5.4 three special values are available to
1465       handle common situations:
1466
1467          PNG_DEFAULT_sRGB: Indicates that the system conforms to the
1468                            IEC 61966-2-1 standard.  This matches almost
1469                            all systems.
1470          PNG_GAMMA_MAC_18: Indicates that the system is an older
1471                            (pre Mac OS 10.6) Apple Macintosh system with
1472                            the default settings.
1473          PNG_GAMMA_LINEAR: Just the fixed point value for 1.0 - indicates
1474                            that the system expects data with no gamma
1475                            encoding.
1476
1477       You  would  use the linear (unencoded) value if you need to process the
1478       pixel values further because this avoids the need  to  decode  and  re-
1479       encode each component value whenever arithmetic is performed.  A lot of
1480       graphics software uses linear values for this reason, often with higher
1481       precision component values to preserve overall accuracy.
1482
1483
1484       The  output_gamma  value expresses how to decode the output values, not
1485       how they are encoded.  The values used correspond to the normal numbers
1486       used  to  describe  the overall gamma of a computer display system; for
1487       example 2.2 for an sRGB conformant system.  The values  are  scaled  by
1488       100000 in the _fixed version of the API (so 220000 for sRGB.)
1489
1490       The  inverse  of  the value is always used to provide a default for the
1491       PNG file encoding if it has no gAMA chunk and  if  png_set_gamma()  has
1492       not been called to override the PNG gamma information.
1493
1494       When  the  ALPHA_OPTIMIZED mode is selected the output gamma is used to
1495       encode opaque pixels however pixels with lower  alpha  values  are  not
1496       encoded, regardless of the output gamma setting.
1497
1498       When  the  standard  Porter  Duff handling is requested with mode 1 the
1499       output encoding is set to be linear and the output_gamma value is  only
1500       relevant  as  a  default  for input data that has no gamma information.
1501       The linear output encoding will be  overridden  if  png_set_gamma()  is
1502       called - the results may be highly unexpected!
1503
1504       The  following  numbers  are  derived  from  the  sRGB standard and the
1505       research behind it.  sRGB is defined to be approximated by a  PNG  gAMA
1506       chunk  value of 0.45455 (1/2.2) for PNG.  The value implicitly includes
1507       any viewing correction required to take account of any  differences  in
1508       the  color  environment  of the original scene and the intended display
1509       environment; the value expresses how to *decode* the image for display,
1510       not how the original data was *encoded*.
1511
1512       sRGB provides a peg for the PNG standard by defining a viewing environ‐
1513       ment.  sRGB itself, and earlier TV standards, actually use a more  com‐
1514       plex  transform  (a linear portion then a gamma 2.4 power law) than PNG
1515       can express.  (PNG is limited to simple power laws.)  By saying that an
1516       image  for direct display on an sRGB conformant system should be stored
1517       with a gAMA chunk value of 45455 (11.3.3.2 and 11.3.3.5 of the ISO  PNG
1518       specification) the PNG specification makes it possible to derive values
1519       for other display systems and environments.
1520
1521       The Mac value is deduced from the sRGB based on an assumption that  the
1522       actual  extra  viewing correction used in early Mac display systems was
1523       implemented as a power 1.45 lookup table.
1524
1525       Any system where a programmable lookup  table  is  used  or  where  the
1526       behavior  of  the  final  display device characteristics can be changed
1527       requires system specific code to  obtain  the  current  characteristic.
1528       However  this  can  be  difficult  and  most  PNG gamma correction only
1529       requires an approximate value.
1530
1531       By default, if png_set_alpha_mode() is not called, libpng assumes  that
1532       all  values  are  unencoded,  linear, values and that the output device
1533       also has a linear characteristic.  This is only very rarely  correct  -
1534       it   is   invariably   better   to   call   png_set_alpha_mode()   with
1535       PNG_DEFAULT_sRGB than rely on the default if you don't  know  what  the
1536       right answer is!
1537
1538       The  special  value PNG_GAMMA_MAC_18 indicates an older Mac system (pre
1539       Mac OS 10.6) which used a correction  table  to  implement  a  somewhat
1540       lower gamma on an otherwise sRGB system.
1541
1542       Both  these  values  are reserved (not simple gamma values) in order to
1543       allow more precise correction internally in the future.
1544
1545       NOTE: the values can be passed to either the fixed  or  floating  point
1546       APIs,  but  the floating point API will also accept floating point val‐
1547       ues.
1548
1549       The second thing you may need to tell libpng about is how  your  system
1550       handles  alpha  channel information.  Some, but not all, PNG files con‐
1551       tain an alpha channel.  To display these files correctly  you  need  to
1552       compose  the  data  onto a suitable background, as described in the PNG
1553       specification.
1554
1555       Libpng only supports composing onto a single color (using png_set_back‐
1556       ground;  see  below).   Otherwise  you must do the composition yourself
1557       and, in this case, you may need to call png_set_alpha_mode:
1558
1559          #if PNG_LIBPNG_VER >= 10504
1560             png_set_alpha_mode(png_ptr, mode, screen_gamma);
1561          #else
1562             png_set_gamma(png_ptr, screen_gamma, 1.0/screen_gamma);
1563          #endif
1564
1565       The screen_gamma value is the same as the  argument  to  png_set_gamma;
1566       however,   how   it   affects   the   output   depends   on  the  mode.
1567       png_set_alpha_mode() sets the file gamma default to 1/screen_gamma,  so
1568       normally  you  don't need to call png_set_gamma.  If you need different
1569       defaults call png_set_gamma() before png_set_alpha_mode() - if you call
1570       it after it will override the settings made by png_set_alpha_mode().
1571
1572       The mode is as follows:
1573
1574           PNG_ALPHA_PNG:  The data is encoded according to the PNG specifica‐
1575       tion.  Red, green and blue, or gray, components are gamma encoded color
1576       values  and  are not premultiplied by the alpha value.  The alpha value
1577       is a linear measure of the contribution of the pixel to the correspond‐
1578       ing final output pixel.
1579
1580       You should normally use this format if you intend to perform color cor‐
1581       rection on the color values; most, maybe all, color correction software
1582       has  no  handling for the alpha channel and, anyway, the math to handle
1583       pre-multiplied component values is unnecessarily complex.
1584
1585       Before you do any arithmetic on the component values you need to remove
1586       the  gamma  encoding  and  multiply out the alpha channel.  See the PNG
1587       specification for more detail.  It is important to note  that  when  an
1588       image  with  an alpha channel is scaled, linear encoded, pre-multiplied
1589       component values must be used!
1590
1591       The remaining modes assume you don't need to do any further color  cor‐
1592       rection  or  that  if  you do, your color correction software knows all
1593       about alpha (it probably doesn't!).  They 'associate'  the  alpha  with
1594       the  color  information  by storing color channel values that have been
1595       scaled by the alpha.  The advantage is that the color channels  can  be
1596       resampled  (the image can be scaled) in this form.  The disadvantage is
1597       that normal practice is to store linear, not  (gamma)  encoded,  values
1598       and  this  requires  16-bit  channels  for still images rather than the
1599       8-bit channels that are just about  sufficient  if  gamma  encoding  is
1600       used.   In  addition  all  non-transparent pixel values, including com‐
1601       pletely opaque ones, must be gamma encoded to produce the final  image.
1602       These   are  the  'STANDARD',  'ASSOCIATED'  or  'PREMULTIPLIED'  modes
1603       described below (the latter being the two common names  for  associated
1604       alpha  color  channels). Note that PNG files always contain non-associ‐
1605       ated color channels; png_set_alpha_mode() with one of the modes  causes
1606       the  decoder to convert the pixels to an associated form before return‐
1607       ing them to your application.
1608
1609       Since it is not necessary to perform arithmetic on opaque color  values
1610       so  long  as  they  are  not to be resampled and are in the final color
1611       space it is possible to optimize the handling of alpha by  storing  the
1612       opaque  pixels  in the PNG format (adjusted for the output color space)
1613       while storing partially opaque pixels in the standard, linear,  format.
1614       The accuracy required for standard alpha composition is relatively low,
1615       because the pixels are isolated, therefore typically the accuracy  loss
1616       in storing 8-bit linear values is acceptable.  (This is not true if the
1617       alpha channel is used to simulate transparency over large areas  -  use
1618       16  bits  or the PNG mode in this case!)  This is the 'OPTIMIZED' mode.
1619       For this mode a pixel is treated as opaque only if the alpha  value  is
1620       equal to the maximum value.
1621
1622           PNG_ALPHA_STANDARD:   The  data  libpng  produces is encoded in the
1623       standard way assumed by most correctly written graphics software.   The
1624       gamma  encoding will be removed by libpng and the linear component val‐
1625       ues will be pre-multiplied by the alpha channel.
1626
1627       With this format the final image must be re-encoded to match  the  dis‐
1628       play  gamma  before  the image is displayed.  If your system doesn't do
1629       that, yet still seems to  perform  arithmetic  on  the  pixels  without
1630       decoding them, it is broken - check out the modes below.
1631
1632       With PNG_ALPHA_STANDARD libpng always produces linear component values,
1633       whatever screen_gamma you supply.  The screen_gamma value is,  however,
1634       used  as  a  default  for  the  file gamma if the PNG file has no gamma
1635       information.
1636
1637       If you call png_set_gamma() after png_set_alpha_mode() you  will  over‐
1638       ride the linear encoding.  Instead the pre-multiplied pixel values will
1639       be gamma encoded but the alpha channel will still be linear.  This  may
1640       actually  match  the  requirements  of  some broken software, but it is
1641       unlikely.
1642
1643       While linear 8-bit data is often used it has insufficient precision for
1644       any  image  with a reasonable dynamic range.  To avoid problems, and if
1645       your software supports it, use png_set_expand_16() to force all  compo‐
1646       nents to 16 bits.
1647
1648           PNG_ALPHA_OPTIMIZED:  This  mode  is the same as PNG_ALPHA_STANDARD
1649       except that completely opaque pixels are gamma encoded according to the
1650       screen_gamma  value.   Pixels  with alpha less than 1.0 will still have
1651       linear components.
1652
1653       Use this format if you have control over your compositing software  and
1654       so don't do other arithmetic (such as scaling) on the data you get from
1655       libpng.  Your compositing software can simply copy opaque pixels to the
1656       output but still has linear values for the non-opaque pixels.
1657
1658       In  normal  compositing,  where the alpha channel encodes partial pixel
1659       coverage (as opposed to broad area translucency), the  inaccuracies  of
1660       the 8-bit representation of non-opaque pixels are irrelevant.
1661
1662       You  can also try this format if your software is broken; it might look
1663       better.
1664
1665           PNG_ALPHA_BROKEN: This is PNG_ALPHA_STANDARD; however,  all  compo‐
1666       nent  values,  including  the alpha channel are gamma encoded.  This is
1667       broken because, in practice, no implementation that  uses  this  choice
1668       correctly  undoes  the encoding before handling alpha composition.  Use
1669       this choice only if other serious errors in the  software  or  hardware
1670       you  use  mandate it.  In most cases of broken software or hardware the
1671       bug in the final display manifests as a subtle halo  around  composited
1672       parts of the image.  You may not even perceive this as a halo; the com‐
1673       posited part of the image may simply appear  separate  from  the  back‐
1674       ground, as though it had been cut out of paper and pasted on afterward.
1675
1676       If  you don't have to deal with bugs in software or hardware, or if you
1677       can  fix  them,   there   are   three   recommended   ways   of   using
1678       png_set_alpha_mode():
1679
1680          png_set_alpha_mode(png_ptr, PNG_ALPHA_PNG,
1681              screen_gamma);
1682
1683       You  can  do  color correction on the result (libpng does not currently
1684       support color correction internally).  When you handle the alpha  chan‐
1685       nel you need to undo the gamma encoding and multiply out the alpha.
1686
1687          png_set_alpha_mode(png_ptr, PNG_ALPHA_STANDARD,
1688              screen_gamma);
1689          png_set_expand_16(png_ptr);
1690
1691       If   you   are   using   the   high   level   interface,   don't   call
1692       png_set_expand_16(); instead pass PNG_TRANSFORM_EXPAND_16 to the inter‐
1693       face.
1694
1695       With  this  mode  you  can't do color correction, but you can do arith‐
1696       metic, including composition and scaling, on the data  without  further
1697       processing.
1698
1699          png_set_alpha_mode(png_ptr, PNG_ALPHA_OPTIMIZED,
1700              screen_gamma);
1701
1702       You  can  avoid  the expansion to 16-bit components with this mode, but
1703       you lose the ability to scale the image or perform other linear  arith‐
1704       metic.   All  you  can do is compose the result onto a matching output.
1705       Since this mode is libpng-specific you also need to write your own com‐
1706       position software.
1707
1708       The  following  are  examples of calls to png_set_alpha_mode to achieve
1709       the required overall gamma correction and, where necessary, alpha  pre‐
1710       multiplication.
1711
1712           png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB);
1713
1714       Choices for the alpha_mode are
1715
1716           PNG_ALPHA_PNG           0 /* according to the PNG standard */
1717           PNG_ALPHA_STANDARD      1 /* according to Porter/Duff */
1718           PNG_ALPHA_ASSOCIATED     1 /* as above; this is the normal practice
1719       */
1720           PNG_ALPHA_PREMULTIPLIED 1 /* as above */
1721           PNG_ALPHA_OPTIMIZED     2 /* 'PNG' for opaque pixels,  else  'STAN‐
1722       DARD' */
1723           PNG_ALPHA_BROKEN        3 /* the alpha channel is gamma encoded */
1724
1725       PNG_ALPHA_PNG  is  the default libpng handling of the alpha channel. It
1726       is not pre-multiplied into the color components. In addition  the  call
1727       states  that  the  output is for a sRGB system and causes all PNG files
1728       without gAMA chunks to be assumed to be encoded using sRGB.
1729
1730           png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC);
1731
1732       In this case the output is assumed to be something like an sRGB confor‐
1733       mant display preceeded by a power-law lookup table of power 1.45.  This
1734       is how early Mac systems behaved.
1735
1736           png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_GAMMA_LINEAR);
1737
1738       This is the classic Jim Blinn approach and will work in academic  envi‐
1739       ronments  where everything is done by the book.  It has the shortcoming
1740       of assuming that input PNG data with no gamma information is  linear  -
1741       this  is  unlikely  to  be  correct unless the PNG files were generated
1742       locally.  Most of the time the output precision will be so  low  as  to
1743       show significant banding in dark areas of the image.
1744
1745           png_set_expand_16(pp);
1746           png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_DEFAULT_sRGB);
1747
1748       This  is  a  somewhat  more realistic Jim Blinn inspired approach.  PNG
1749       files are assumed to have the sRGB encoding if not marked with a  gamma
1750       value  and  the  output  is always 16 bits per component.  This permits
1751       accurate scaling and processing of the data.  If  you  know  that  your
1752       input  PNG  files  were  generated  locally  you  might need to replace
1753       PNG_DEFAULT_sRGB with the correct value for your system.
1754
1755           png_set_alpha_mode(pp, PNG_ALPHA_OPTIMIZED, PNG_DEFAULT_sRGB);
1756
1757       If you just need to composite the PNG image onto an existing background
1758       and if you control the code that does this you can use the optimization
1759       setting.  In this case you just copy completely opaque  pixels  to  the
1760       output.   For pixels that are not completely transparent (you just skip
1761       those) you do the composition math using png_composite  or  png_compos‐
1762       ite_16  below then encode the resultant 8-bit or 16-bit values to match
1763       the output encoding.
1764
1765           Other cases
1766
1767       If neither the PNG nor  the  standard  linear  encoding  work  for  you
1768       because  of  the software or hardware you use then you have a big prob‐
1769       lem.  The PNG case will probably result in halos around the image.  The
1770       linear encoding will probably result in a washed out, too bright, image
1771       (it's actually too contrasty.)  Try the ALPHA_OPTIMIZED  mode  above  -
1772       this will probably substantially reduce the halos.  Alternatively try:
1773
1774           png_set_alpha_mode(pp, PNG_ALPHA_BROKEN, PNG_DEFAULT_sRGB);
1775
1776       This  option  will also reduce the halos, but there will be slight dark
1777       halos round the opaque parts of  the  image  where  the  background  is
1778       light.   In  the OPTIMIZED mode the halos will be light halos where the
1779       background is dark.  Take your pick - the halos are unavoidable  unless
1780       you  can  get your hardware/software fixed!  (The OPTIMIZED approach is
1781       slightly faster.)
1782
1783       When the default gamma of PNG files doesn't match the output gamma.  If
1784       you  have PNG files with no gamma information png_set_alpha_mode allows
1785       you to provide a default gamma, but it also sets the ouput gamma to the
1786       matching  value.   If you know your PNG files have a gamma that doesn't
1787       match  the  output  you  can  take   advantage   of   the   fact   that
1788       png_set_alpha_mode  always  sets the output gamma but only sets the PNG
1789       default if it is not already set:
1790
1791           png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB);
1792           png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC);
1793
1794       The first call sets both the default and the output gamma  values,  the
1795       second  call  overrides  the output gamma without changing the default.
1796       This is easier than achieving the same effect with png_set_gamma.   You
1797       must  use  PNG_ALPHA_PNG  for  the  first  call  - internal checking in
1798       png_set_alpha will fire if more than one call to png_set_alpha_mode and
1799       png_set_background is made in the same read operation, however multiple
1800       calls with PNG_ALPHA_PNG are ignored.
1801
1802       If you don't need, or can't handle, the  alpha  channel  you  can  call
1803       png_set_background() to remove it by compositing against a fixed color.
1804       Don't call png_set_strip_alpha() to do this - it  will  leave  spurious
1805       pixel values in transparent parts of this image.
1806
1807          png_set_background(png_ptr, &background_color,
1808              PNG_BACKGROUND_GAMMA_SCREEN, 0, 1);
1809
1810       The background_color is an RGB or grayscale value according to the data
1811       format libpng will produce for you.  Because you  don't  yet  know  the
1812       format  of  the  PNG file, if you call png_set_background at this point
1813       you must arrange for the format produced by libpng to always have 8-bit
1814       or  16-bit  components  and  then store the color as an 8-bit or 16-bit
1815       color as appropriate.  The color contains separate gray and RGB  compo‐
1816       nent values, so you can let libpng produce gray or RGB output according
1817       to the input format, but low bit depth grayscale images must always  be
1818       converted  to  at  least  8-bit  format.   (Even  though  low bit depth
1819       grayscale images can't have an alpha channel they can have a  transpar‐
1820       ent color!)
1821
1822       You  set  the  transforms  you  need later, either as flags to the high
1823       level interface or libpng API calls for the low level  interface.   For
1824       reference the settings and API calls required are:
1825
1826       8-bit values:
1827          PNG_TRANSFORM_SCALE_16 | PNG_EXPAND
1828          png_set_expand(png_ptr); png_set_scale_16(png_ptr);
1829
1830          If you must get exactly the same inaccurate results
1831          produced by default in versions prior to libpng-1.5.4,
1832          use PNG_TRANSFORM_STRIP_16 and png_set_strip_16(png_ptr)
1833          instead.
1834
1835       16-bit values:
1836          PNG_TRANSFORM_EXPAND_16
1837          png_set_expand_16(png_ptr);
1838
1839       In either case palette image data will be expanded to RGB.  If you just
1840       want   color   data   you   can   add   PNG_TRANSFORM_GRAY_TO_RGB    or
1841       png_set_gray_to_rgb(png_ptr) to the list.
1842
1843       Calling  png_set_background before the PNG file header is read will not
1844       work prior to libpng-1.5.4.  Because the failure may  result  in  unex‐
1845       pected   warnings  or  errors  it  is  therefore  much  safer  to  call
1846       png_set_background after the head has been  read.   Unfortunately  this
1847       means  that prior to libpng-1.5.4 it cannot be used with the high level
1848       interface.
1849
1850
1851   The high-level read interface
1852       At this point there are two ways to  proceed;  through  the  high-level
1853       read  interface,  or  through  a sequence of low-level read operations.
1854       You can use the high-level interface if (a) you are willing to read the
1855       entire image into memory, and (b) the input transformations you want to
1856       do are limited to the following set:
1857
1858           PNG_TRANSFORM_IDENTITY      No transformation
1859           PNG_TRANSFORM_SCALE_16      Strip 16-bit samples to
1860                                       8-bit accurately
1861           PNG_TRANSFORM_STRIP_16      Chop 16-bit samples to
1862                                       8-bit less accurately
1863           PNG_TRANSFORM_STRIP_ALPHA   Discard the alpha channel
1864           PNG_TRANSFORM_PACKING       Expand 1, 2 and 4-bit
1865                                       samples to bytes
1866           PNG_TRANSFORM_PACKSWAP      Change order of packed
1867                                       pixels to LSB first
1868           PNG_TRANSFORM_EXPAND        Perform set_expand()
1869           PNG_TRANSFORM_INVERT_MONO   Invert monochrome images
1870           PNG_TRANSFORM_SHIFT         Normalize pixels to the
1871                                       sBIT depth
1872           PNG_TRANSFORM_BGR           Flip RGB to BGR, RGBA
1873                                       to BGRA
1874           PNG_TRANSFORM_SWAP_ALPHA    Flip RGBA to ARGB or GA
1875                                       to AG
1876           PNG_TRANSFORM_INVERT_ALPHA  Change alpha from opacity
1877                                       to transparency
1878           PNG_TRANSFORM_SWAP_ENDIAN   Byte-swap 16-bit samples
1879           PNG_TRANSFORM_GRAY_TO_RGB   Expand grayscale samples
1880                                       to RGB (or GA to RGBA)
1881           PNG_TRANSFORM_EXPAND_16     Expand samples to 16 bits
1882
1883       (This excludes setting a background color, doing gamma  transformation,
1884       quantizing, and setting filler.)  If this is the case, simply do this:
1885
1886           png_read_png(png_ptr, info_ptr, png_transforms, NULL)
1887
1888       where  png_transforms  is  an integer containing the bitwise OR of some
1889       set  of   transformation   flags.    This   call   is   equivalent   to
1890       png_read_info(),  followed  the set of transformations indicated by the
1891       transform mask, then png_read_image(), and finally png_read_end().
1892
1893       (The final parameter of this call is not yet used.   Someday  it  might
1894       point to transformation parameters required by some future input trans‐
1895       form.)
1896
1897       You must use png_transforms and not call any png_set_transform()  func‐
1898       tions when you use png_read_png().
1899
1900       After  you  have called png_read_png(), you can retrieve the image data
1901       with
1902
1903          row_pointers = png_get_rows(png_ptr, info_ptr);
1904
1905       where row_pointers is an array of pointers to the pixel data  for  each
1906       row:
1907
1908          png_bytep row_pointers[height];
1909
1910       If you know your image size and pixel size ahead of time, you can allo‐
1911       cate row_pointers prior to calling png_read_png() with
1912
1913          if (height > PNG_UINT_32_MAX/(sizeof (png_byte)))
1914             png_error (png_ptr,
1915                 "Image is too tall to process in memory");
1916
1917          if (width > PNG_UINT_32_MAX/pixel_size)
1918             png_error (png_ptr,
1919                 "Image is too wide to process in memory");
1920
1921          row_pointers = png_malloc(png_ptr,
1922              height*(sizeof (png_bytep)));
1923
1924          for (int i=0; i<height, i++)
1925             row_pointers[i]=NULL;  /* security precaution */
1926
1927          for (int i=0; i<height, i++)
1928             row_pointers[i]=png_malloc(png_ptr,
1929                 width*pixel_size);
1930
1931          png_set_rows(png_ptr, info_ptr, &row_pointers);
1932
1933       Alternatively you could allocate your image in one big block and define
1934       row_pointers[i]  to  point  into  the  proper places in your block, but
1935       first be sure that your platform is able to allocate such a large  buf‐
1936       fer:
1937
1938          /* Guard against integer overflow */
1939          if (height > PNG_SIZE_MAX/(width*pixel_size)) {
1940               png_error(png_ptr,"image_data buffer would be too large");
1941          }
1942
1943          png_bytep buffer=png_malloc(png_ptr,height*width*pixel_size);
1944
1945          for (int i=0; i<height, i++)
1946             row_pointers[i]=buffer+i*width*pixel_size;
1947
1948          png_set_rows(png_ptr, info_ptr, &row_pointers);
1949
1950       If  you  use png_set_rows(), the application is responsible for freeing
1951       row_pointers (and row_pointers[i], if they were separately allocated).
1952
1953       If you don't allocate row_pointers ahead of time,  png_read_png()  will
1954       do it, and it'll be free'ed by libpng when you call png_destroy_*().
1955
1956
1957   The low-level read interface
1958       If you are going the low-level route, you are now ready to read all the
1959       file information up to the actual image data.  You do this with a  call
1960       to png_read_info().
1961
1962           png_read_info(png_ptr, info_ptr);
1963
1964       This will process all chunks up to but not including the image data.
1965
1966       This  also  copies  some  of the data from the PNG file into the decode
1967       structure for use  in  later  transformations.   Important  information
1968       copied in is:
1969
1970       1) The PNG file gamma from the gAMA chunk.  This overwrites the default
1971       value   provided   by   an   earlier   call   to    png_set_gamma    or
1972       png_set_alpha_mode.
1973
1974       2)  Prior to libpng-1.5.4 the background color from a bKGd chunk.  This
1975       damages the information provided by an earlier  call  to  png_set_back‐
1976       ground  resulting  in unexpected behavior.  Libpng-1.5.4 no longer does
1977       this.
1978
1979       3) The number of significant bits in each component value.  Libpng uses
1980       this  to  optimize gamma handling by reducing the internal lookup table
1981       sizes.
1982
1983       4) The transparent color information from a tRNS chunk.   This  can  be
1984       modified by a later call to png_set_tRNS.
1985
1986
1987   Querying the info structure
1988       Functions are used to get the information from the info_ptr once it has
1989       been read.  Note that these fields may  not  be  completely  filled  in
1990       until png_read_end() has read the chunk data following the image.
1991
1992           png_get_IHDR(png_ptr, info_ptr, &width, &height,
1993              &bit_depth, &color_type, &interlace_type,
1994              &compression_type, &filter_method);
1995
1996           width          - holds the width of the image
1997                            in pixels (up to 2^31).
1998
1999           height         - holds the height of the image
2000                            in pixels (up to 2^31).
2001
2002           bit_depth      - holds the bit depth of one of the
2003                            image channels.  (valid values are
2004                            1, 2, 4, 8, 16 and depend also on
2005                            the color_type.  See also
2006                            significant bits (sBIT) below).
2007
2008           color_type     - describes which color/alpha channels
2009                                are present.
2010                            PNG_COLOR_TYPE_GRAY
2011                               (bit depths 1, 2, 4, 8, 16)
2012                            PNG_COLOR_TYPE_GRAY_ALPHA
2013                               (bit depths 8, 16)
2014                            PNG_COLOR_TYPE_PALETTE
2015                               (bit depths 1, 2, 4, 8)
2016                            PNG_COLOR_TYPE_RGB
2017                               (bit_depths 8, 16)
2018                            PNG_COLOR_TYPE_RGB_ALPHA
2019                               (bit_depths 8, 16)
2020
2021                            PNG_COLOR_MASK_PALETTE
2022                            PNG_COLOR_MASK_COLOR
2023                            PNG_COLOR_MASK_ALPHA
2024
2025           interlace_type - (PNG_INTERLACE_NONE or
2026                            PNG_INTERLACE_ADAM7)
2027
2028           compression_type - (must be PNG_COMPRESSION_TYPE_BASE
2029                            for PNG 1.0)
2030
2031           filter_method  - (must be PNG_FILTER_TYPE_BASE
2032                            for PNG 1.0, and can also be
2033                            PNG_INTRAPIXEL_DIFFERENCING if
2034                            the PNG datastream is embedded in
2035                            a MNG-1.0 datastream)
2036
2037           Any of width, height, color_type, bit_depth,
2038           interlace_type, compression_type, or filter_method can
2039           be NULL if you are not interested in their values.
2040
2041           Note that png_get_IHDR() returns 32-bit data into
2042           the application's width and height variables.
2043           This is an unsafe situation if these are not png_uint_32
2044           variables.  In such situations, the
2045           png_get_image_width() and png_get_image_height()
2046           functions described below are safer.
2047
2048           width            = png_get_image_width(png_ptr,
2049                                info_ptr);
2050
2051           height           = png_get_image_height(png_ptr,
2052                                info_ptr);
2053
2054           bit_depth        = png_get_bit_depth(png_ptr,
2055                                info_ptr);
2056
2057           color_type       = png_get_color_type(png_ptr,
2058                                info_ptr);
2059
2060           interlace_type   = png_get_interlace_type(png_ptr,
2061                                info_ptr);
2062
2063           compression_type = png_get_compression_type(png_ptr,
2064                                info_ptr);
2065
2066           filter_method    = png_get_filter_type(png_ptr,
2067                                info_ptr);
2068
2069           channels = png_get_channels(png_ptr, info_ptr);
2070
2071           channels       - number of channels of info for the
2072                            color type (valid values are 1 (GRAY,
2073                            PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
2074                            4 (RGB_ALPHA or RGB + filler byte))
2075
2076           rowbytes = png_get_rowbytes(png_ptr, info_ptr);
2077
2078           rowbytes       - number of bytes needed to hold a row
2079                            This value, the bit_depth, color_type,
2080                            and the number of channels can change
2081                            if you use transforms such as
2082                            png_set_expand(). See
2083                            png_read_update_info(), below.
2084
2085           signature = png_get_signature(png_ptr, info_ptr);
2086
2087           signature      - holds the signature read from the
2088                            file (if any).  The data is kept in
2089                            the same offset it would be if the
2090                            whole signature were read (i.e. if an
2091                            application had already read in 4
2092                            bytes of signature before starting
2093                            libpng, the remaining 4 bytes would
2094                            be in signature[4] through signature[7]
2095                            (see png_set_sig_bytes())).
2096
2097       These  are  also  important,  but their validity depends on whether the
2098       chunk   has   been   read.    The   png_get_valid(png_ptr,    info_ptr,
2099       PNG_INFO_<chunk>) and png_get_<chunk>(png_ptr, info_ptr, ...) functions
2100       return non-zero if the data has been read, or zero if  it  is  missing.
2101       The parameters to the png_get_<chunk> are set directly if they are sim‐
2102       ple data types, or a pointer into the info_ptr is returned for any com‐
2103       plex types.
2104
2105       The  colorspace  data  from  gAMA, cHRM, sRGB, iCCP, and sBIT chunks is
2106       simply returned to give the application information about how the image
2107       was  encoded.   Libpng  itself only does transformations using the file
2108       gamma when combining semitransparent pixels with the background  color,
2109       and,  since libpng-1.6.0, when converting between 8-bit sRGB and 16-bit
2110       linear pixels within the simplified API.  Libpng  also  uses  the  file
2111       gamma  when converting RGB to gray, beginning with libpng-1.0.5, if the
2112       application calls png_set_rgb_to_gray()).
2113
2114           png_get_PLTE(png_ptr, info_ptr, &palette,
2115                            &num_palette);
2116
2117           palette        - the palette for the file
2118                            (array of png_color)
2119
2120           num_palette    - number of entries in the palette
2121
2122           png_get_gAMA(png_ptr, info_ptr, &file_gamma);
2123           png_get_gAMA_fixed(png_ptr, info_ptr, &int_file_gamma);
2124
2125           file_gamma     - the gamma at which the file is
2126                            written (PNG_INFO_gAMA)
2127
2128           int_file_gamma - 100,000 times the gamma at which the
2129                            file is written
2130
2131           png_get_cHRM(png_ptr, info_ptr,  &white_x, &white_y, &red_x,
2132                            &red_y, &green_x, &green_y, &blue_x, &blue_y)
2133           png_get_cHRM_XYZ(png_ptr, info_ptr, &red_X, &red_Y, &red_Z,
2134                            &green_X, &green_Y, &green_Z, &blue_X, &blue_Y,
2135                            &blue_Z)
2136           png_get_cHRM_fixed(png_ptr, info_ptr, &int_white_x,
2137                            &int_white_y, &int_red_x, &int_red_y,
2138                            &int_green_x, &int_green_y, &int_blue_x,
2139                            &int_blue_y)
2140           png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &int_red_X, &int_red_Y,
2141                            &int_red_Z, &int_green_X, &int_green_Y,
2142                            &int_green_Z, &int_blue_X, &int_blue_Y,
2143                            &int_blue_Z)
2144
2145           {white,red,green,blue}_{x,y}
2146                            A color space encoding specified using the
2147                            chromaticities of the end points and the
2148                            white point. (PNG_INFO_cHRM)
2149
2150           {red,green,blue}_{X,Y,Z}
2151                            A color space encoding specified using the
2152                            encoding end points - the CIE tristimulus
2153                            specification of the intended color of the red,
2154                            green and blue channels in the PNG RGB data.
2155                            The white point is simply the sum of the three
2156                            end points. (PNG_INFO_cHRM)
2157
2158           png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
2159
2160           srgb_intent -    the rendering intent (PNG_INFO_sRGB)
2161                            The presence of the sRGB chunk
2162                            means that the pixel data is in the
2163                            sRGB color space.  This chunk also
2164                            implies specific values of gAMA and
2165                            cHRM.
2166
2167           png_get_iCCP(png_ptr, info_ptr, &name,
2168              &compression_type, &profile, &proflen);
2169
2170           name             - The profile name.
2171
2172           compression_type - The compression type; always
2173                              PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
2174                              You may give NULL to this argument to
2175                              ignore it.
2176
2177           profile          - International Color Consortium color
2178                              profile data. May contain NULs.
2179
2180           proflen          - length of profile data in bytes.
2181
2182           png_get_sBIT(png_ptr, info_ptr, &sig_bit);
2183
2184           sig_bit        - the number of significant bits for
2185                            (PNG_INFO_sBIT) each of the gray,
2186                            red, green, and blue channels,
2187                            whichever are appropriate for the
2188                            given color type (png_color_16)
2189
2190           png_get_tRNS(png_ptr, info_ptr, &trans_alpha,
2191                            &num_trans, &trans_color);
2192
2193           trans_alpha    - array of alpha (transparency)
2194                            entries for palette (PNG_INFO_tRNS)
2195
2196           num_trans      - number of transparent entries
2197                            (PNG_INFO_tRNS)
2198
2199           trans_color    - graylevel or color sample values of
2200                            the single transparent color for
2201                            non-paletted images (PNG_INFO_tRNS)
2202
2203           png_get_eXIf_1(png_ptr, info_ptr, &num_exif, &exif);
2204                            (PNG_INFO_eXIf)
2205
2206           exif           - Exif profile (array of png_byte)
2207
2208           png_get_hIST(png_ptr, info_ptr, &hist);
2209                            (PNG_INFO_hIST)
2210
2211           hist           - histogram of palette (array of
2212                            png_uint_16)
2213
2214           png_get_tIME(png_ptr, info_ptr, &mod_time);
2215
2216           mod_time       - time image was last modified
2217                           (PNG_VALID_tIME)
2218
2219           png_get_bKGD(png_ptr, info_ptr, &background);
2220
2221           background     - background color (of type
2222                            png_color_16p) (PNG_VALID_bKGD)
2223                            valid 16-bit red, green and blue
2224                            values, regardless of color_type
2225
2226           num_comments   = png_get_text(png_ptr, info_ptr,
2227                            &text_ptr, &num_text);
2228
2229           num_comments   - number of comments
2230
2231           text_ptr       - array of png_text holding image
2232                            comments
2233
2234           text_ptr[i].compression - type of compression used
2235                        on "text" PNG_TEXT_COMPRESSION_NONE
2236                                  PNG_TEXT_COMPRESSION_zTXt
2237                                  PNG_ITXT_COMPRESSION_NONE
2238                                  PNG_ITXT_COMPRESSION_zTXt
2239
2240           text_ptr[i].key   - keyword for comment.  Must contain
2241                                1-79 characters.
2242
2243           text_ptr[i].text  - text comments for current
2244                                keyword.  Can be empty.
2245
2246           text_ptr[i].text_length - length of text string,
2247                        after decompression, 0 for iTXt
2248
2249           text_ptr[i].itxt_length - length of itxt string,
2250                        after decompression, 0 for tEXt/zTXt
2251
2252           text_ptr[i].lang  - language of comment (empty
2253                                string for unknown).
2254
2255           text_ptr[i].lang_key  - keyword in UTF-8
2256                                (empty string for unknown).
2257
2258           Note that the itxt_length, lang, and lang_key
2259           members of the text_ptr structure only exist when the
2260           library is built with iTXt chunk support.  Prior to
2261           libpng-1.4.0 the library was built by default without
2262           iTXt support. Also note that when iTXt is supported,
2263           they contain NULL pointers when the "compression"
2264           field contains PNG_TEXT_COMPRESSION_NONE or
2265           PNG_TEXT_COMPRESSION_zTXt.
2266
2267           num_text       - number of comments (same as
2268                            num_comments; you can put NULL here
2269                            to avoid the duplication)
2270
2271           Note while png_set_text() will accept text, language,
2272           and translated keywords that can be NULL pointers, the
2273           structure returned by png_get_text will always contain
2274           regular zero-terminated C strings.  They might be
2275           empty strings but they will never be NULL pointers.
2276
2277           num_spalettes = png_get_sPLT(png_ptr, info_ptr,
2278              &palette_ptr);
2279
2280           num_spalettes  - number of sPLT chunks read.
2281
2282           palette_ptr    - array of palette structures holding
2283                            contents of one or more sPLT chunks
2284                            read.
2285
2286           png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
2287              &unit_type);
2288
2289           offset_x       - positive offset from the left edge
2290                            of the screen (can be negative)
2291
2292           offset_y       - positive offset from the top edge
2293                            of the screen (can be negative)
2294
2295           unit_type      - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
2296
2297           png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
2298              &unit_type);
2299
2300           res_x          - pixels/unit physical resolution in
2301                            x direction
2302
2303           res_y          - pixels/unit physical resolution in
2304                            x direction
2305
2306           unit_type      - PNG_RESOLUTION_UNKNOWN,
2307                            PNG_RESOLUTION_METER
2308
2309           png_get_sCAL(png_ptr, info_ptr, &unit, &width,
2310              &height)
2311
2312           unit        - physical scale units (an integer)
2313
2314           width       - width of a pixel in physical scale units
2315
2316           height      - height of a pixel in physical scale units
2317                        (width and height are doubles)
2318
2319           png_get_sCAL_s(png_ptr, info_ptr, &unit, &width,
2320              &height)
2321
2322           unit        - physical scale units (an integer)
2323
2324           width       - width of a pixel in physical scale units
2325                         (expressed as a string)
2326
2327           height      - height of a pixel in physical scale units
2328                        (width and height are strings like "2.54")
2329
2330           num_unknown_chunks = png_get_unknown_chunks(png_ptr,
2331              info_ptr, &unknowns)
2332
2333           unknowns          - array of png_unknown_chunk
2334                               structures holding unknown chunks
2335
2336           unknowns[i].name  - name of unknown chunk
2337
2338           unknowns[i].data  - data of unknown chunk
2339
2340           unknowns[i].size  - size of unknown chunk's data
2341
2342           unknowns[i].location - position of chunk in file
2343
2344           The value of "i" corresponds to the order in which the
2345           chunks were read from the PNG file or inserted with the
2346           png_set_unknown_chunks() function.
2347
2348           The value of "location" is a bitwise "or" of
2349
2350                PNG_HAVE_IHDR  (0x01)
2351                PNG_HAVE_PLTE  (0x02)
2352                PNG_AFTER_IDAT (0x08)
2353
2354       The data from the pHYs chunk can be  retrieved  in  several  convenient
2355       forms:
2356
2357           res_x = png_get_x_pixels_per_meter(png_ptr,
2358              info_ptr)
2359
2360           res_y = png_get_y_pixels_per_meter(png_ptr,
2361              info_ptr)
2362
2363           res_x_and_y = png_get_pixels_per_meter(png_ptr,
2364              info_ptr)
2365
2366           res_x = png_get_x_pixels_per_inch(png_ptr,
2367              info_ptr)
2368
2369           res_y = png_get_y_pixels_per_inch(png_ptr,
2370              info_ptr)
2371
2372           res_x_and_y = png_get_pixels_per_inch(png_ptr,
2373              info_ptr)
2374
2375           aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
2376              info_ptr)
2377
2378           Each of these returns 0 [signifying "unknown"] if
2379              the data is not present or if res_x is 0;
2380              res_x_and_y is 0 if res_x != res_y
2381
2382           Note that because of the way the resolutions are
2383              stored internally, the inch conversions won't
2384              come out to exactly even number.  For example,
2385              72 dpi is stored as 0.28346 pixels/meter, and
2386              when this is retrieved it is 71.9988 dpi, so
2387              be sure to round the returned value appropriately
2388              if you want to display a reasonable-looking result.
2389
2390       The  data  from  the  oFFs chunk can be retrieved in several convenient
2391       forms:
2392
2393           x_offset = png_get_x_offset_microns(png_ptr, info_ptr);
2394
2395           y_offset = png_get_y_offset_microns(png_ptr, info_ptr);
2396
2397           x_offset = png_get_x_offset_inches(png_ptr, info_ptr);
2398
2399           y_offset = png_get_y_offset_inches(png_ptr, info_ptr);
2400
2401           Each of these returns 0 [signifying "unknown" if both
2402              x and y are 0] if the data is not present or if the
2403              chunk is present but the unit is the pixel.  The
2404              remark about inexact inch conversions applies here
2405              as well, because a value in inches can't always be
2406              converted to microns and back without some loss
2407              of precision.
2408
2409       For more information, see the PNG specification for chunk contents.  Be
2410       careful  with  trusting  rowbytes, as some of the transformations could
2411       increase the space needed to hold a row (expand,  filler,  gray_to_rgb,
2412       etc.).  See png_read_update_info(), below.
2413
2414       A  quick word about text_ptr and num_text.  PNG stores comments in key‐
2415       word/text pairs, one pair per chunk, with no limit  on  the  number  of
2416       text chunks, and a 2^31 byte limit on their size.  While there are sug‐
2417       gested keywords, there is no requirement to restrict the use  to  these
2418       strings.   It  is strongly suggested that keywords and text be sensible
2419       to humans (that's the point), so don't use abbreviations.  Non-printing
2420       symbols  are  not allowed.  See the PNG specification for more details.
2421       There is also no requirement to have text after the keyword.
2422
2423       Keywords should be limited to 79 Latin-1 characters without leading  or
2424       trailing spaces, but non-consecutive spaces are allowed within the key‐
2425       word.  It is possible to have the same keyword  any  number  of  times.
2426       The text_ptr is an array of png_text structures, each holding a pointer
2427       to a language string, a pointer to a keyword and a pointer  to  a  text
2428       string.   The text string, language code, and translated keyword may be
2429       empty or NULL pointers.  The keyword/text pairs are put into the  array
2430       in  the order that they are received.  However, some or all of the text
2431       chunks may be after the image, so, to make sure you have read  all  the
2432       text chunks, don't mess with these until after you read the stuff after
2433       the image.  This will be mentioned again below in the  discussion  that
2434       goes with png_read_end().
2435
2436
2437   Input transformations
2438       After you've read the header information, you can set up the library to
2439       handle any special transformations of the image data.  The various ways
2440       to  transform  the data will be described in the order that they should
2441       occur.  This is important, as some  of  these  change  the  color  type
2442       and/or  bit  depth  of  the  data, and some others only work on certain
2443       color types and bit depths.
2444
2445       Transformations you request are ignored if they don't have any  meaning
2446       for  a  particular input data format.  However some transformations can
2447       have an effect as a result of a previous transformation.  If you  spec‐
2448       ify a contradictory set of transformations, for example both adding and
2449       removing the alpha channel, you cannot predict the final result.
2450
2451       The color used for the transparency values should be  supplied  in  the
2452       same  format/depth as the current image data.  It is stored in the same
2453       format/depth as the image data in a tRNS chunk, so this is what  libpng
2454       expects for this data.
2455
2456       The  color  used  for  the  background value depends on the need_expand
2457       argument as described below.
2458
2459       Data will be decoded into the supplied row buffers  packed  into  bytes
2460       unless  the  library has been told to transform it into another format.
2461       For example, 4 bit/pixel paletted or grayscale data will be returned  2
2462       pixels/byte with the leftmost pixel in the high-order bits of the byte,
2463       unless png_set_packing() is called.  8-bit RGB data will be  stored  in
2464       RGB  RGB  RGB  format unless png_set_filler() or png_set_add_alpha() is
2465       called to insert filler bytes, either before or after each RGB triplet.
2466
2467       16-bit RGB data will be returned RRGGBB RRGGBB, with the most  signifi‐
2468       cant byte of the color value first, unless png_set_scale_16() is called
2469       to transform it to regular RGB RGB  triplets,  or  png_set_filler()  or
2470       png_set_add alpha() is called to insert two filler bytes, either before
2471       or after each RRGGBB triplet.  Similarly,  8-bit  or  16-bit  grayscale
2472       data   can  be  modified  with  png_set_filler(),  png_set_add_alpha(),
2473       png_set_strip_16(), or png_set_scale_16().
2474
2475       The following code transforms grayscale images of  less  than  8  to  8
2476       bits,  changes paletted images to RGB, and adds a full alpha channel if
2477       there is transparency information in a tRNS chunk.  This is most useful
2478       on  grayscale  images with bit depths of 2 or 4 or if there is a multi‐
2479       ple-image viewing application that wishes to treat all  images  in  the
2480       same way.
2481
2482           if (color_type == PNG_COLOR_TYPE_PALETTE)
2483               png_set_palette_to_rgb(png_ptr);
2484
2485           if (png_get_valid(png_ptr, info_ptr,
2486               PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
2487
2488           if (color_type == PNG_COLOR_TYPE_GRAY &&
2489               bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png_ptr);
2490
2491       The  first  two  functions  are  actually aliases for png_set_expand(),
2492       added in libpng version 1.0.4, with  the  function  names  expanded  to
2493       improve  code readability.  In some future version they may actually do
2494       different things.
2495
2496       As of libpng version 1.2.9, png_set_expand_gray_1_2_4_to_8() was added.
2497       It expands the sample depth without changing tRNS to alpha.
2498
2499       As  of libpng version 1.5.2, png_set_expand_16() was added.  It behaves
2500       as png_set_expand(); however,  the  resultant  channels  have  16  bits
2501       rather  than  8.   Use  this when the output color or gray channels are
2502       made linear to avoid fairly severe accuracy loss.
2503
2504          if (bit_depth < 16)
2505             png_set_expand_16(png_ptr);
2506
2507       PNG can have files with 16 bits per channel.  If you only can handle  8
2508       bits per channel, this will strip the pixels down to 8-bit.
2509
2510           if (bit_depth == 16) #if PNG_LIBPNG_VER >= 10504
2511              png_set_scale_16(png_ptr); #else
2512              png_set_strip_16(png_ptr); #endif
2513
2514       (The  more accurate "png_set_scale_16()" API became available in libpng
2515       version 1.5.4).
2516
2517       If you need to process the alpha channel on the image  separately  from
2518       the  image  data (for example if you convert it to a bitmap mask) it is
2519       possible to have libpng strip the channel  leaving  just  RGB  or  gray
2520       data:
2521
2522           if (color_type & PNG_COLOR_MASK_ALPHA)
2523              png_set_strip_alpha(png_ptr);
2524
2525       If you strip the alpha channel you need to find some other way of deal‐
2526       ing with the information.  If, instead, you want to convert  the  image
2527       to  an opaque version with no alpha channel use png_set_background; see
2528       below.
2529
2530       As of libpng version 1.5.2, almost all useful expansions are supported,
2531       the  major  ommissions  are  conversion  of grayscale to indexed images
2532       (which can be done trivially in  the  application)  and  conversion  of
2533       indexed  to  grayscale  (which can be done by a trivial manipulation of
2534       the palette.)
2535
2536       In the following table, the 01 means grayscale with depth<8,  31  means
2537       indexed  with  depth<8,  other  numerals  represent the color type, "T"
2538       means the tRNS chunk is present, A means an alpha channel  is  present,
2539       and  O  means  tRNS or alpha is present but all pixels in the image are
2540       opaque.
2541
2542         FROM  01  31   0  0T  0O   2  2T  2O   3  3T  3O  4A  4O  6A  6O
2543          TO
2544          01    -  [G]  -   -   -   -   -   -   -   -   -   -   -   -   -
2545          31   [Q]  Q  [Q] [Q] [Q]  Q   Q   Q   Q   Q   Q  [Q] [Q]  Q   Q
2546           0    1   G   +   .   .   G   G   G   G   G   G   B   B  GB  GB
2547          0T    lt  Gt  t   +   .   Gt  G   G   Gt  G   G   Bt  Bt GBt GBt
2548          0O    lt  Gt  t   .   +   Gt  Gt  G   Gt  Gt  G   Bt  Bt GBt GBt
2549           2    C   P   C   C   C   +   .   .   C   -   -  CB  CB   B   B
2550          2T    Ct  -   Ct  C   C   t   +   t   -   -   -  CBt CBt  Bt  Bt
2551          2O    Ct  -   Ct  C   C   t   t   +   -   -   -  CBt CBt  Bt  Bt
2552           3   [Q]  p  [Q] [Q] [Q]  Q   Q   Q   +   .   .  [Q] [Q]  Q   Q
2553          3T   [Qt] p  [Qt][Q] [Q]  Qt  Qt  Qt  t   +   t  [Qt][Qt] Qt  Qt
2554          3O   [Qt] p  [Qt][Q] [Q]  Qt  Qt  Qt  t   t   +  [Qt][Qt] Qt  Qt
2555          4A    lA  G   A   T   T   GA  GT  GT  GA  GT  GT  +   BA  G  GBA
2556          4O    lA GBA  A   T   T   GA  GT  GT  GA  GT  GT  BA  +  GBA  G
2557          6A    CA  PA  CA  C   C   A   T  tT   PA  P   P   C  CBA  +   BA
2558          6O    CA PBA  CA  C   C   A  tT   T   PA  P   P  CBA  C   BA  +
2559
2560       Within the matrix,
2561            "+" identifies entries where 'from' and 'to' are the same.
2562            "-" means the transformation is not supported.
2563            "." means nothing is necessary (a tRNS chunk can just be ignored).
2564            "t" means the transformation is obtained by png_set_tRNS.
2565            "A" means the transformation is obtained by png_set_add_alpha().
2566            "X" means the transformation is obtained by png_set_expand().
2567            "1" means the transformation is obtained by
2568                png_set_expand_gray_1_2_4_to_8() (and by png_set_expand()
2569                if there is no transparency in the original or the final
2570                format).
2571            "C" means the transformation is obtained by png_set_gray_to_rgb().
2572            "G" means the transformation is obtained by png_set_rgb_to_gray().
2573            "P" means the transformation is obtained by
2574                png_set_expand_palette_to_rgb().
2575            "p" means the transformation is obtained by png_set_packing().
2576            "Q" means the transformation is obtained by png_set_quantize().
2577            "T" means the transformation is obtained by
2578                png_set_tRNS_to_alpha().
2579            "B" means the transformation is obtained by
2580                png_set_background(), or png_strip_alpha().
2581
2582       When an entry has multiple transforms listed all are required to  cause
2583       the right overall transformation.  When two transforms are separated by
2584       a comma either will do the job.  When transforms are enclosed in [] the
2585       transform  should  do  the  job but this is currently unimplemented - a
2586       different format will result if the suggested transformations are used.
2587
2588       In PNG files, the alpha channel in an image is the  level  of  opacity.
2589       If  you  need  the  alpha channel in an image to be the level of trans‐
2590       parency instead of opacity, you can invert the alpha  channel  (or  the
2591       tRNS chunk data) after it's read, so that 0 is fully opaque and 255 (in
2592       8-bit or paletted images) or 65535 (in 16-bit images) is  fully  trans‐
2593       parent, with
2594
2595           png_set_invert_alpha(png_ptr);
2596
2597       PNG  files pack pixels of bit depths 1, 2, and 4 into bytes as small as
2598       they can, resulting in, for example, 8 pixels per byte for 1 bit files.
2599       This  code  expands  to 1 pixel per byte without changing the values of
2600       the pixels:
2601
2602           if (bit_depth < 8)
2603              png_set_packing(png_ptr);
2604
2605       PNG files have possible bit depths of 1, 2, 4, 8, and 16.   All  pixels
2606       stored  in  a  PNG image have been "scaled" or "shifted" up to the next
2607       higher possible bit depth (e.g. from 5 bits/sample in the range  [0,31]
2608       to  8 bits/sample in the range [0, 255]).  However, it is also possible
2609       to convert the PNG pixel data back to the original  bit  depth  of  the
2610       image.   This  call  reduces  the  pixels back down to the original bit
2611       depth:
2612
2613           png_color_8p sig_bit;
2614
2615           if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
2616              png_set_shift(png_ptr, sig_bit);
2617
2618       PNG files store 3-color pixels in red, green, blue  order.   This  code
2619       changes the storage of the pixels to blue, green, red:
2620
2621           if (color_type == PNG_COLOR_TYPE_RGB ||
2622               color_type == PNG_COLOR_TYPE_RGB_ALPHA)
2623              png_set_bgr(png_ptr);
2624
2625       PNG  files store RGB pixels packed into 3 or 6 bytes. This code expands
2626       them into 4 or 8 bytes for windowing systems that  need  them  in  this
2627       format:
2628
2629           if (color_type == PNG_COLOR_TYPE_RGB)
2630              png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
2631
2632       where  "filler"  is  the  8-bit  or 16-bit number to fill with, and the
2633       location is either  PNG_FILLER_BEFORE  or  PNG_FILLER_AFTER,  depending
2634       upon  whether you want the filler before the RGB or after. When filling
2635       an 8-bit pixel, the least significant 8 bits of the number are used, if
2636       a  16-bit  number  is  supplied.   This  transformation does not affect
2637       images that already have full alpha channels.  To add an  opaque  alpha
2638       channel,  use  filler=0xffff  and  PNG_FILLER_AFTER which will generate
2639       RGBA pixels.
2640
2641       Note that png_set_filler() does not change the color type.  If you want
2642       to do that, you can add a true alpha channel with
2643
2644           if (color_type == PNG_COLOR_TYPE_RGB ||
2645              color_type == PNG_COLOR_TYPE_GRAY)
2646              png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER);
2647
2648       where  "filler"  contains the alpha value to assign to each pixel.  The
2649       png_set_add_alpha() function was added in libpng-1.2.7.
2650
2651       If you are reading an image with an alpha channel,  and  you  need  the
2652       data as ARGB instead of the normal PNG format RGBA:
2653
2654           if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
2655              png_set_swap_alpha(png_ptr);
2656
2657       For some uses, you may want a grayscale image to be represented as RGB.
2658       This code will do that conversion:
2659
2660           if (color_type == PNG_COLOR_TYPE_GRAY ||
2661               color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
2662              png_set_gray_to_rgb(png_ptr);
2663
2664       Conversely, you can convert an  RGB  or  RGBA  image  to  grayscale  or
2665       grayscale with alpha.
2666
2667           if (color_type == PNG_COLOR_TYPE_RGB ||
2668               color_type == PNG_COLOR_TYPE_RGB_ALPHA)
2669              png_set_rgb_to_gray(png_ptr, error_action,
2670                 double red_weight, double green_weight);
2671
2672           error_action = 1: silently do the conversion
2673
2674           error_action = 2: issue a warning if the original
2675                             image has any pixel where
2676                             red != green or red != blue
2677
2678           error_action = 3: issue an error and abort the
2679                             conversion if the original
2680                             image has any pixel where
2681                             red != green or red != blue
2682
2683           red_weight:       weight of red component
2684
2685           green_weight:     weight of green component
2686                             If either weight is negative, default
2687                             weights are used.
2688
2689       In  the  corresponding  fixed point API the red_weight and green_weight
2690       values are simply scaled by 100,000:
2691
2692           png_set_rgb_to_gray(png_ptr, error_action,
2693              png_fixed_point red_weight,
2694              png_fixed_point green_weight);
2695
2696       If you have set error_action = 1 or 2, you can later check whether  the
2697       image  really  was  gray,  after  processing  the  image rows, with the
2698       png_get_rgb_to_gray_status(png_ptr)  function.   It   will   return   a
2699       png_byte that is zero if the image was gray or 1 if there were any non-
2700       gray pixels.  Background and sBIT data will be  silently  converted  to
2701       grayscale,  using  the  green  channel data for sBIT, regardless of the
2702       error_action setting.
2703
2704       The default values come from the PNG file cHRM chunk if present; other‐
2705       wise, the defaults correspond to the ITU-R recommendation 709, and also
2706       the sRGB color space, as recommended in the  Charles  Poynton's  Colour
2707       FAQ, Copyright (c) 2006-11-28 Charles Poynton, in section 9:
2708
2709       <http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html#RTFToC9>
2710
2711           Y = 0.2126 * R + 0.7152 * G + 0.0722 * B
2712
2713       Previous  versions  of  this document, 1998 through 2002, recommended a
2714       slightly different formula:
2715
2716           Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
2717
2718       Libpng uses an integer approximation:
2719
2720           Y = (6968 * R + 23434 * G + 2366 * B)/32768
2721
2722       The calculation is done in a linear colorspace, if the image gamma  can
2723       be determined.
2724
2725       The  png_set_background() function has been described already; it tells
2726       libpng to composite images with alpha or  simple  transparency  against
2727       the  supplied  background  color.   For  compatibility with versions of
2728       libpng earlier than libpng-1.5.4 it is recommended that  you  call  the
2729       function  after  reading the file header, even if you don't want to use
2730       the color in a bKGD chunk, if one exists.
2731
2732       If the PNG file contains a bKGD chunk (PNG_INFO_bKGD  valid),  you  may
2733       use  this  color, or supply another color more suitable for the current
2734       display (e.g., the background color from a web page).  You need to tell
2735       libpng  how  the color is represented, both the format of the component
2736       values in the color (the number of bits) and the gamma encoding of  the
2737       color.   The  function  takes  two arguments, background_gamma_mode and
2738       need_expand to convey this information; however, only two  combinations
2739       are likely to be useful:
2740
2741           png_color_16 my_background;
2742           png_color_16p image_background;
2743
2744           if (png_get_bKGD(png_ptr, info_ptr, &image_background))
2745              png_set_background(png_ptr, image_background,
2746                  PNG_BACKGROUND_GAMMA_FILE, 1/*needs to be expanded*/, 1);
2747           else
2748              png_set_background(png_ptr, &my_background,
2749                  PNG_BACKGROUND_GAMMA_SCREEN, 0/*do not expand*/, 1);
2750
2751       The second call was described above - my_background is in the format of
2752       the final, display, output produced by libpng.  Because  you  now  know
2753       the format of the PNG it is possible to avoid the need to choose either
2754       8-bit or 16-bit output and to retain palette images (the palette colors
2755       will  be  modified appropriately and the tRNS chunk removed.)  However,
2756       if you are doing this, take great care not to ask  for  transformations
2757       without checking first that they apply!
2758
2759       In  the  first call the background color has the original bit depth and
2760       color type of the PNG file.  So, for palette images the color  is  sup‐
2761       plied  as a palette index and for low bit greyscale images the color is
2762       a reduced bit value in image_background->gray.
2763
2764       If you didn't call png_set_gamma() before reading the file header,  for
2765       example  if you need your code to remain compatible with older versions
2766       of libpng prior to libpng-1.5.4, this is the place to call it.
2767
2768       Do not call it if you called png_set_alpha_mode(); doing so will damage
2769       the    settings    put   in   place   by   png_set_alpha_mode().    (If
2770       png_set_alpha_mode()  is  supported   then   you   can   certainly   do
2771       png_set_gamma() before reading the PNG header.)
2772
2773       This  API  unconditionally sets the screen and file gamma values, so it
2774       will override the value in the PNG file unless it is called before  the
2775       PNG  file reading starts.  For this reason you must always call it with
2776       the PNG file value when you call it in this position:
2777
2778          if (png_get_gAMA(png_ptr, info_ptr, &file_gamma))
2779             png_set_gamma(png_ptr, screen_gamma, file_gamma);
2780
2781          else
2782             png_set_gamma(png_ptr, screen_gamma, 0.45455);
2783
2784       If you need to reduce an RGB file to a paletted file, or if a  paletted
2785       file  has more entries than will fit on your screen, png_set_quantize()
2786       will do that.  Note that this  is  a  simple  match  quantization  that
2787       merely finds the closest color available.  This should work fairly well
2788       with optimized palettes, but fairly badly with linear color cubes.   If
2789       you  pass  a  palette that is larger than maximum_colors, the file will
2790       reduce the number of colors in the palette so it will  fit  into  maxi‐
2791       mum_colors.   If  there is a histogram, libpng will use it to make more
2792       intelligent choices when reducing the palette.  If  there  is  no  his‐
2793       togram, it may not do as good a job.
2794
2795          if (color_type & PNG_COLOR_MASK_COLOR)
2796          {
2797             if (png_get_valid(png_ptr, info_ptr,
2798                 PNG_INFO_PLTE))
2799             {
2800                png_uint_16p histogram = NULL;
2801
2802                png_get_hIST(png_ptr, info_ptr,
2803                    &histogram);
2804                png_set_quantize(png_ptr, palette, num_palette,
2805                   max_screen_colors, histogram, 1);
2806             }
2807
2808             else
2809             {
2810                png_color std_color_cube[MAX_SCREEN_COLORS] =
2811                   { ... colors ... };
2812
2813                png_set_quantize(png_ptr, std_color_cube,
2814                   MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
2815                   NULL,0);
2816             }
2817          }
2818
2819       PNG  files describe monochrome as black being zero and white being one.
2820       The following code will reverse this (make black be one  and  white  be
2821       zero):
2822
2823          if (bit_depth == 1 && color_type == PNG_COLOR_TYPE_GRAY)
2824             png_set_invert_mono(png_ptr);
2825
2826       This  function  can  also  be  used  to invert grayscale and gray-alpha
2827       images:
2828
2829          if (color_type == PNG_COLOR_TYPE_GRAY ||
2830              color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
2831             png_set_invert_mono(png_ptr);
2832
2833       PNG files store 16-bit pixels in network byte  order  (big-endian,  ie.
2834       most  significant  bits  first).   This code changes the storage to the
2835       other way (little-endian, i.e. least significant bits  first,  the  way
2836       PCs store them):
2837
2838           if (bit_depth == 16)
2839              png_set_swap(png_ptr);
2840
2841       If  you  are using packed-pixel images (1, 2, or 4 bits/pixel), and you
2842       need to change the order the pixels are packed into bytes, you can use:
2843
2844           if (bit_depth < 8)
2845              png_set_packswap(png_ptr);
2846
2847       Finally, you can write your own transformation function if none of  the
2848       existing  ones  meets  your  needs.  This is done by setting a callback
2849       with
2850
2851           png_set_read_user_transform_fn(png_ptr,
2852               read_transform_fn);
2853
2854       You must supply the function
2855
2856           void read_transform_fn(png_structp png_ptr, png_row_infop
2857               row_info, png_bytep data)
2858
2859       See pngtest.c for a working example.   Your  function  will  be  called
2860       after  all of the other transformations have been processed.  Take care
2861       with interlaced images if you do the interlace yourself - the width  of
2862       the row is the width in 'row_info', not the overall image width.
2863
2864       If supported, libpng provides two information routines that you can use
2865       to find where you are in processing the image:
2866
2867          png_get_current_pass_number(png_structp png_ptr);
2868          png_get_current_row_number(png_structp png_ptr);
2869
2870       Don't try using these outside a transform callback - firstly  they  are
2871       only supported if user transforms are supported, secondly they may well
2872       return unexpected results unless the row is actually being processed at
2873       the moment they are called.
2874
2875       With  interlaced images the value returned is the row in the input sub-
2876       image    image.     Use    PNG_ROW_FROM_PASS_ROW(row,     pass)     and
2877       PNG_COL_FROM_PASS_COL(col,  pass)  to find the output pixel (x,y) given
2878       an interlaced sub-image pixel (row,col,pass).
2879
2880       The discussion of interlace handling above contains more information on
2881       how to use these values.
2882
2883       You can also set up a pointer to a user structure for use by your call‐
2884       back function, and you can inform libpng that your  transform  function
2885       will change the number of channels or bit depth with the function
2886
2887           png_set_user_transform_info(png_ptr, user_ptr,
2888               user_depth, user_channels);
2889
2890       The  user's  application, not libpng, is responsible for allocating and
2891       freeing any memory required for the user structure.
2892
2893       You can retrieve  the  pointer  via  the  function  png_get_user_trans‐
2894       form_ptr().  For example:
2895
2896           voidp read_user_transform_ptr =
2897               png_get_user_transform_ptr(png_ptr);
2898
2899       The  last  thing  to  handle  is interlacing; this is covered in detail
2900       below, but you must call the function here if you want libpng to handle
2901       expansion of the interlaced image.
2902
2903           number_of_passes = png_set_interlace_handling(png_ptr);
2904
2905       After  setting  the  transformations,  libpng  can update your png_info
2906       structure to reflect any transformations  you've  requested  with  this
2907       call.
2908
2909           png_read_update_info(png_ptr, info_ptr);
2910
2911       This  is  most  useful to update the info structure's rowbytes field so
2912       you can use it to allocate your image memory.  This function will  also
2913       update  your  palette  with  the correct screen_gamma and background if
2914       these have been  given  with  the  calls  above.   You  may  only  call
2915       png_read_update_info() once with a particular info_ptr.
2916
2917       After  you call png_read_update_info(), you can allocate any memory you
2918       need to hold the image.  The row data is simply raw byte data  for  all
2919       forms  of  images.  As the actual allocation varies among applications,
2920       no example will be given.  If you are allocating one large  chunk,  you
2921       will  need  to  build  an  array of pointers to each row, as it will be
2922       needed for some of the functions below.
2923
2924       Be sure that your platform can allocate the buffer  that  you'll  need.
2925       libpng internally checks for oversize width, but you'll need to do your
2926       own check for number_of_rows*width*pixel_size if you are using a multi‐
2927       ple-row buffer:
2928
2929          /* Guard against integer overflow */
2930          if (number_of_rows > PNG_SIZE_MAX/(width*pixel_size)) {
2931               png_error(png_ptr,"image_data buffer would be too large");
2932          }
2933
2934       Remember: Before you call png_read_update_info(), the png_get_*() func‐
2935       tions return the values corresponding to the original PNG image.  After
2936       you call png_read_update_info the values refer to the image that libpng
2937       will output.  Consequently you must call  all  the  png_set_  functions
2938       before you call png_read_update_info().  This is particularly important
2939       for  png_set_interlace_handling()  -  if  you   are   going   to   call
2940       png_read_update_info()   you   must  call  png_set_interlace_handling()
2941       before it unless you want to receive interlaced output.
2942
2943
2944   Reading image data
2945       After you've allocated memory, you can read the image data.   The  sim‐
2946       plest  way  to  do this is in one function call.  If you are allocating
2947       enough  memory  to  hold  the  whole   image,   you   can   just   call
2948       png_read_image()  and libpng will read in all the image data and put it
2949       in the memory area supplied.  You will need to  pass  in  an  array  of
2950       pointers to each row.
2951
2952       This  function  automatically handles interlacing, so you don't need to
2953       call      png_set_interlace_handling()      (unless      you       call
2954       png_read_update_info()) or call this function multiple times, or any of
2955       that other stuff necessary with png_read_rows().
2956
2957          png_read_image(png_ptr, row_pointers);
2958
2959       where row_pointers is:
2960
2961          png_bytep row_pointers[height];
2962
2963       You can point to void or char or whatever you use for pixels.
2964
2965       If you don't want to read in the whole  image  at  once,  you  can  use
2966       png_read_rows()  instead.   If  there  is  no interlacing (check inter‐
2967       lace_type == PNG_INTERLACE_NONE), this is simple:
2968
2969           png_read_rows(png_ptr, row_pointers, NULL,
2970               number_of_rows);
2971
2972       where row_pointers is the same as in the png_read_image() call.
2973
2974       If you are doing this just one row at a time, you can do  this  with  a
2975       single row_pointer instead of an array of row_pointers:
2976
2977           png_bytep row_pointer = row;
2978           png_read_row(png_ptr, row_pointer, NULL);
2979
2980       If  the  file  is  interlaced  (interlace_type != 0 in the IHDR chunk),
2981       things get somewhat harder.  The only current (PNG  Specification  ver‐
2982       sion  1.2)  interlacing  type  for PNG is (interlace_type == PNG_INTER‐
2983       LACE_ADAM7); a somewhat  complicated  2D  interlace  scheme,  known  as
2984       Adam7,  that  breaks down an image into seven smaller images of varying
2985       size, based on an 8x8 grid.  This number is defined (from  libpng  1.5)
2986       as PNG_INTERLACE_ADAM7_PASSES in png.h
2987
2988       libpng  can  fill  out those images or it can give them to you "as is".
2989       It is almost always better to have libpng handle  the  interlacing  for
2990       you.  If you want the images filled out, there are two ways to do that.
2991       The one mentioned in the PNG specification is to expand each  pixel  to
2992       cover  those  pixels  that  have  not  been  read  yet (the "rectangle"
2993       method).  This results in a blocky image  for  the  first  pass,  which
2994       gradually smooths out as more pixels are read.  The other method is the
2995       "sparkle" method, where pixels are drawn only in their final locations,
2996       with the rest of the image remaining whatever colors they were initial‐
2997       ized to before the start of the read.  The first method  usually  looks
2998       better,  but tends to be slower, as there are more pixels to put in the
2999       rows.
3000
3001       If, as is likely, you want libpng  to  expand  the  images,  call  this
3002       before calling png_start_read_image() or png_read_update_info():
3003
3004           if (interlace_type == PNG_INTERLACE_ADAM7)
3005              number_of_passes
3006                  = png_set_interlace_handling(png_ptr);
3007
3008       This  will  return  the  number  of  passes needed.  Currently, this is
3009       seven, but may change if another interlace type is added.   This  func‐
3010       tion  can  be  called even if the file is not interlaced, where it will
3011       return one  pass.   You  then  need  to  read  the  whole  image  'num‐
3012       ber_of_passes'  times.   Each  time will distribute the pixels from the
3013       current pass to the correct place in the output image, so you  need  to
3014       supply the same rows to png_read_rows in each pass.
3015
3016       If  you  are  not  going  to display the image after each pass, but are
3017       going to wait until the entire  image  is  read  in,  use  the  sparkle
3018       effect.   This  effect is faster and the end result of either method is
3019       exactly the same.  If you are planning on displaying  the  image  after
3020       each  pass,  the  "rectangle" effect is generally considered the better
3021       looking one.
3022
3023       If you only want the "sparkle"  effect,  just  call  png_read_row()  or
3024       png_read_rows()  as  normal,  with the third parameter NULL.  Make sure
3025       you make pass over the image  number_of_passes  times,  and  you  don't
3026       change  the  data  in the rows between calls.  You can change the loca‐
3027       tions of the data, just not the data.  Each pass only writes the pixels
3028       appropriate for that pass, and assumes the data from previous passes is
3029       still valid.
3030
3031           png_read_rows(png_ptr, row_pointers, NULL,
3032               number_of_rows);
3033           or
3034           png_read_row(png_ptr, row_pointers, NULL);
3035
3036       If you only want the first effect (the  rectangles),  do  the  same  as
3037       before except pass the row buffer in the third parameter, and leave the
3038       second parameter NULL.
3039
3040           png_read_rows(png_ptr, NULL, row_pointers,
3041               number_of_rows);
3042           or
3043           png_read_row(png_ptr, NULL, row_pointers);
3044
3045       If you don't want libpng to handle the interlacing details,  just  call
3046       png_read_rows()  PNG_INTERLACE_ADAM7_PASSES  times  to  read in all the
3047       images.  Each of the images is a valid image by  itself;  however,  you
3048       will almost certainly need to distribute the pixels from each sub-image
3049       to the correct place.  This is where everything gets very tricky.
3050
3051       If you want to retrieve the separate images you must pass  the  correct
3052       number  of rows to each successive call of png_read_rows().  The calcu‐
3053       lation gets pretty complicated for small images, where some  sub-images
3054       may  not  even exist because either their width or height ends up zero.
3055       libpng provides two macros to help you in 1.5 and later versions:
3056
3057          png_uint_32 width = PNG_PASS_COLS(image_width, pass_number);
3058          png_uint_32 height = PNG_PASS_ROWS(image_height, pass_number);
3059
3060       Respectively these tell you the width and height of the sub-image  cor‐
3061       responding  to  the  numbered pass.  'pass' is in in the range 0 to 6 -
3062       this can be confusing because the  specification  refers  to  the  same
3063       passes as 1 to 7!  Be careful, you must check both the width and height
3064       before calling png_read_rows() and not call it for that pass if  either
3065       is zero.
3066
3067       You  can,  of  course,  read each sub-image row by row.  If you want to
3068       produce optimal code to make  a  pixel-by-pixel  transformation  of  an
3069       interlaced image this is the best approach; read each row of each pass,
3070       transform it, and write it out to a new interlaced image.
3071
3072       If you want to de-interlace the image yourself libpng provides  further
3073       macros  to  help  that tell you where to place the pixels in the output
3074       image.  Because the interlacing scheme is rectangular - sub-image  pix‐
3075       els  are  always  arranged on a rectangular grid - all you need to know
3076       for each pass is the starting column and row in the output image of the
3077       first  pixel  plus  the  spacing  between each pixel.  As of libpng 1.5
3078       there are four macros to retrieve this information:
3079
3080          png_uint_32 x = PNG_PASS_START_COL(pass);
3081          png_uint_32 y = PNG_PASS_START_ROW(pass);
3082          png_uint_32 xStep = 1U << PNG_PASS_COL_SHIFT(pass);
3083          png_uint_32 yStep = 1U << PNG_PASS_ROW_SHIFT(pass);
3084
3085       These allow you to write the obvious loop:
3086
3087          png_uint_32 input_y = 0;
3088          png_uint_32 output_y = PNG_PASS_START_ROW(pass);
3089
3090          while (output_y < output_image_height)
3091          {
3092             png_uint_32 input_x = 0;
3093             png_uint_32 output_x = PNG_PASS_START_COL(pass);
3094
3095             while (output_x < output_image_width)
3096             {
3097                image[output_y][output_x] =
3098                    subimage[pass][input_y][input_x++];
3099
3100                output_x += xStep;
3101             }
3102
3103             ++input_y;
3104             output_y += yStep;
3105          }
3106
3107       Notice that the steps between successive output rows  and  columns  are
3108       returned  as shifts.  This is possible because the pixels in the subim‐
3109       ages are always a power of 2 apart - 1, 2, 4 or 8 pixels - in the orig‐
3110       inal  image.  In practice you may need to directly calculate the output
3111       coordinate given an input  coordinate.   libpng  provides  two  further
3112       macros for this purpose:
3113
3114          png_uint_32 output_x = PNG_COL_FROM_PASS_COL(input_x, pass);
3115          png_uint_32 output_y = PNG_ROW_FROM_PASS_ROW(input_y, pass);
3116
3117       Finally a pair of macros are provided to tell you if a particular image
3118       row or column appears in a given pass:
3119
3120          int col_in_pass = PNG_COL_IN_INTERLACE_PASS(output_x, pass);
3121          int row_in_pass = PNG_ROW_IN_INTERLACE_PASS(output_y, pass);
3122
3123       Bear in mind that you will probably also need to check  the  width  and
3124       height  of  the  pass in addition to the above to be sure the pass even
3125       exists!
3126
3127       With any luck you are convinced by now that you don't want to  do  your
3128       own  interlace  handling.  In reality normally the only good reason for
3129       doing this is if you are processing PNG files on a pixel-by-pixel basis
3130       and  don't  want  to  load the whole file into memory when it is inter‐
3131       laced.
3132
3133       libpng includes a test program, pngvalid, that illustrates reading  and
3134       writing  of interlaced images.  If you can't get interlacing to work in
3135       your code and don't  want  to  leave  it  to  libpng  (the  recommended
3136       approach), see how pngvalid.c does it.
3137
3138
3139   Finishing a sequential read
3140       After  you  are finished reading the image through the low-level inter‐
3141       face, you can finish reading the file.
3142
3143       If you want to use a different crc action for handling  CRC  errors  in
3144       chunks after the image data, you can call png_set_crc_action() again at
3145       this point.
3146
3147       If you are interested in comments or time, which may be  stored  either
3148       before  or  after the image data, you should pass the separate png_info
3149       struct if you want to keep the comments from before and after the image
3150       separate.
3151
3152           png_infop end_info = png_create_info_struct(png_ptr);
3153
3154           if (!end_info)
3155           {
3156              png_destroy_read_struct(&png_ptr, &info_ptr,
3157                  (png_infopp)NULL);
3158              return (ERROR);
3159           }
3160
3161          png_read_end(png_ptr, end_info);
3162
3163       If you are not interested, you should still call png_read_end() but you
3164       can pass NULL, avoiding the need to create an end_info  structure.   If
3165       you  do  this, libpng will not process any chunks after IDAT other than
3166       skipping over them and perhaps (depending on whether  you  have  called
3167       png_set_crc_action)  checking  their  CRCs  while  looking for the IEND
3168       chunk.
3169
3170          png_read_end(png_ptr, (png_infop)NULL);
3171
3172       If you don't call png_read_end(), then your file pointer will  be  left
3173       pointing  to the first chunk after the last IDAT, which is probably not
3174       what you want if you expect to read something beyond the end of the PNG
3175       datastream.
3176
3177       When  you  are  done,  you can free all memory allocated by libpng like
3178       this:
3179
3180          png_destroy_read_struct(&png_ptr, &info_ptr,
3181              &end_info);
3182
3183       or, if you didn't create an end_info structure,
3184
3185          png_destroy_read_struct(&png_ptr, &info_ptr,
3186              (png_infopp)NULL);
3187
3188       It is also possible to individually  free  the  info_ptr  members  that
3189       point to libpng-allocated storage with the following function:
3190
3191           png_free_data(png_ptr, info_ptr, mask, seq)
3192
3193           mask - identifies data to be freed, a mask
3194                  containing the bitwise OR of one or
3195                  more of
3196                    PNG_FREE_PLTE, PNG_FREE_TRNS,
3197                    PNG_FREE_HIST, PNG_FREE_ICCP,
3198                    PNG_FREE_PCAL, PNG_FREE_ROWS,
3199                    PNG_FREE_SCAL, PNG_FREE_SPLT,
3200                    PNG_FREE_TEXT, PNG_FREE_UNKN,
3201                  or simply PNG_FREE_ALL
3202
3203           seq  - sequence number of item to be freed
3204                  (-1 for all items)
3205
3206       This  function  may  be  safely  called  when  the relevant storage has
3207       already been freed, or has not yet been allocated, or was allocated  by
3208       the  user  and not by libpng,  and will in those cases do nothing.  The
3209       "seq" parameter is ignored if only one item of the selected data  type,
3210       such  as  PLTE, is allowed.  If "seq" is not -1, and multiple items are
3211       allowed for the data type identified in the mask, such as text or sPLT,
3212       only the n'th item in the structure is freed, where n is "seq".
3213
3214       The default behavior is only to free data that was allocated internally
3215       by libpng.  This can be changed, so that libpng will not free the data,
3216       or  so  that  it  will  free  data  that was allocated by the user with
3217       png_malloc() or png_calloc() and passed in via a png_set_*()  function,
3218       with
3219
3220           png_data_freer(png_ptr, info_ptr, freer, mask)
3221
3222           freer  - one of
3223                      PNG_DESTROY_WILL_FREE_DATA
3224                      PNG_SET_WILL_FREE_DATA
3225                      PNG_USER_WILL_FREE_DATA
3226
3227           mask   - which data elements are affected
3228                    same choices as in png_free_data()
3229
3230       This  function  only affects data that has already been allocated.  You
3231       can call this function after reading the PNG data  but  before  calling
3232       any   png_set_*()  functions,  to  control  whether  the  user  or  the
3233       png_set_*() function is responsible for freeing any existing data  that
3234       might  be present, and again after the png_set_*() functions to control
3235       whether the user or png_destroy_*() is supposed to free the data.  When
3236       the user assumes responsibility for libpng-allocated data, the applica‐
3237       tion must use png_free() to  free  it,  and  when  the  user  transfers
3238       responsibility to libpng for data that the user has allocated, the user
3239       must have used png_malloc() or png_calloc() to allocate it.
3240
3241       If you allocated your row_pointers in  a  single  block,  as  suggested
3242       above in the description of the high level read interface, you must not
3243       transfer  responsibility  for  freeing  it  to  the   png_set_rows   or
3244       png_read_destroy  function,  because  they  would  also try to free the
3245       individual row_pointers[i].
3246
3247       If you  allocated  text_ptr.text,  text_ptr.lang,  and  text_ptr.trans‐
3248       lated_keyword  separately,  do  not transfer responsibility for freeing
3249       text_ptr to libpng, because when libpng fills a png_text  structure  it
3250       combines  these  members  with the key member, and png_free_data() will
3251       free only text_ptr.key.  Similarly, if you transfer responsibility  for
3252       free'ing  text_ptr  from  libpng  to your application, your application
3253       must not separately free those members.
3254
3255       The png_free_data() function will turn off the "valid"  flag  for  any‐
3256       thing  it frees.  If you need to turn the flag off for a chunk that was
3257       freed by your application instead of by libpng, you can use
3258
3259           png_set_invalid(png_ptr, info_ptr, mask);
3260
3261           mask - identifies the chunks to be made invalid,
3262                  containing the bitwise OR of one or
3263                  more of
3264                    PNG_INFO_gAMA, PNG_INFO_sBIT,
3265                    PNG_INFO_cHRM, PNG_INFO_PLTE,
3266                    PNG_INFO_tRNS, PNG_INFO_bKGD,
3267                    PNG_INFO_eXIf,
3268                    PNG_INFO_hIST, PNG_INFO_pHYs,
3269                    PNG_INFO_oFFs, PNG_INFO_tIME,
3270                    PNG_INFO_pCAL, PNG_INFO_sRGB,
3271                    PNG_INFO_iCCP, PNG_INFO_sPLT,
3272                    PNG_INFO_sCAL, PNG_INFO_IDAT
3273
3274       For a more compact example of reading a PNG image, see the  file  exam‐
3275       ple.c.
3276
3277
3278   Reading PNG files progressively
3279       The  progressive  reader is slightly different from the non-progressive
3280       reader.   Instead  of  calling  png_read_info(),  png_read_rows(),  and
3281       png_read_end(),  you  make  one call to png_process_data(), which calls
3282       callbacks when it has the info, a row, or the end of  the  image.   You
3283       set  up  these callbacks with png_set_progressive_read_fn().  You don't
3284       have to worry about the input/output functions of libpng,  as  you  are
3285       giving  the  library  the  data directly in png_process_data().  I will
3286       assume that you have read the section on reading PNG files above, so  I
3287       will  only  highlight  the differences (although I will show all of the
3288       code).
3289
3290       png_structp png_ptr; png_infop info_ptr;
3291
3292        /*  An example code fragment of how you would
3293            initialize the progressive reader in your
3294            application. */
3295        int
3296        initialize_png_reader()
3297        {
3298           png_ptr = png_create_read_struct
3299               (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
3300                user_error_fn, user_warning_fn);
3301
3302           if (!png_ptr)
3303               return (ERROR);
3304
3305           info_ptr = png_create_info_struct(png_ptr);
3306
3307           if (!info_ptr)
3308           {
3309              png_destroy_read_struct(&png_ptr,
3310                 (png_infopp)NULL, (png_infopp)NULL);
3311              return (ERROR);
3312           }
3313
3314           if (setjmp(png_jmpbuf(png_ptr)))
3315           {
3316              png_destroy_read_struct(&png_ptr, &info_ptr,
3317                 (png_infopp)NULL);
3318              return (ERROR);
3319           }
3320
3321           /* This one's new.  You can provide functions
3322              to be called when the header info is valid,
3323              when each row is completed, and when the image
3324              is finished.  If you aren't using all functions,
3325              you can specify NULL parameters.  Even when all
3326              three functions are NULL, you need to call
3327              png_set_progressive_read_fn().  You can use
3328              any struct as the user_ptr (cast to a void pointer
3329              for the function call), and retrieve the pointer
3330              from inside the callbacks using the function
3331
3332                 png_get_progressive_ptr(png_ptr);
3333
3334              which will return a void pointer, which you have
3335              to cast appropriately.
3336            */
3337           png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
3338               info_callback, row_callback, end_callback);
3339
3340           return 0;
3341        }
3342
3343        /* A code fragment that you call as you receive blocks
3344          of data */
3345        int
3346        process_data(png_bytep buffer, png_uint_32 length)
3347        {
3348           if (setjmp(png_jmpbuf(png_ptr)))
3349           {
3350              png_destroy_read_struct(&png_ptr, &info_ptr,
3351                  (png_infopp)NULL);
3352              return (ERROR);
3353           }
3354
3355           /* This one's new also.  Simply give it a chunk
3356              of data from the file stream (in order, of
3357              course).  On machines with segmented memory
3358              models machines, don't give it any more than
3359              64K.  The library seems to run fine with sizes
3360              of 4K. Although you can give it much less if
3361              necessary (I assume you can give it chunks of
3362              1 byte, I haven't tried less than 256 bytes
3363              yet).  When this function returns, you may
3364              want to display any rows that were generated
3365              in the row callback if you don't already do
3366              so there.
3367            */
3368           png_process_data(png_ptr, info_ptr, buffer, length);
3369
3370           /* At this point you can call png_process_data_skip if
3371              you want to handle data the library will skip yourself;
3372              it simply returns the number of bytes to skip (and stops
3373              libpng skipping that number of bytes on the next
3374              png_process_data call).
3375           return 0;
3376        }
3377
3378        /* This function is called (as set by
3379           png_set_progressive_read_fn() above) when enough data
3380           has been supplied so all of the header has been
3381           read.
3382        */
3383        void
3384        info_callback(png_structp png_ptr, png_infop info)
3385        {
3386           /* Do any setup here, including setting any of
3387              the transformations mentioned in the Reading
3388              PNG files section.  For now, you _must_ call
3389              either png_start_read_image() or
3390              png_read_update_info() after all the
3391              transformations are set (even if you don't set
3392              any).  You may start getting rows before
3393              png_process_data() returns, so this is your
3394              last chance to prepare for that.
3395
3396              This is where you turn on interlace handling,
3397              assuming you don't want to do it yourself.
3398
3399              If you need to you can stop the processing of
3400              your original input data at this point by calling
3401              png_process_data_pause.  This returns the number
3402              of unprocessed bytes from the last png_process_data
3403              call - it is up to you to ensure that the next call
3404              sees these bytes again.  If you don't want to bother
3405              with this you can get libpng to cache the unread
3406              bytes by setting the 'save' parameter (see png.h) but
3407              then libpng will have to copy the data internally.
3408            */
3409        }
3410
3411        /* This function is called when each row of image
3412           data is complete */
3413        void
3414        row_callback(png_structp png_ptr, png_bytep new_row,
3415           png_uint_32 row_num, int pass)
3416        {
3417           /* If the image is interlaced, and you turned
3418              on the interlace handler, this function will
3419              be called for every row in every pass.  Some
3420              of these rows will not be changed from the
3421              previous pass.  When the row is not changed,
3422              the new_row variable will be NULL.  The rows
3423              and passes are called in order, so you don't
3424              really need the row_num and pass, but I'm
3425              supplying them because it may make your life
3426              easier.
3427
3428              If you did not turn on interlace handling then
3429              the callback is called for each row of each
3430              sub-image when the image is interlaced.  In this
3431              case 'row_num' is the row in the sub-image, not
3432              the row in the output image as it is in all other
3433              cases.
3434
3435              For the non-NULL rows of interlaced images when
3436              you have switched on libpng interlace handling,
3437              you must call png_progressive_combine_row()
3438              passing in the row and the old row.  You can
3439              call this function for NULL rows (it will just
3440              return) and for non-interlaced images (it just
3441              does the memcpy for you) if it will make the
3442              code easier.  Thus, you can just do this for
3443              all cases if you switch on interlace handling;
3444            */
3445
3446               png_progressive_combine_row(png_ptr, old_row,
3447                 new_row);
3448
3449           /* where old_row is what was displayed
3450              previously for the row.  Note that the first
3451              pass (pass == 0, really) will completely cover
3452              the old row, so the rows do not have to be
3453              initialized.  After the first pass (and only
3454              for interlaced images), you will have to pass
3455              the current row, and the function will combine
3456              the old row and the new row.
3457
3458              You can also call png_process_data_pause in this
3459              callback - see above.
3460           */
3461        }
3462
3463        void
3464        end_callback(png_structp png_ptr, png_infop info)
3465        {
3466           /* This function is called after the whole image
3467              has been read, including any chunks after the
3468              image (up to and including the IEND).  You
3469              will usually have the same info chunk as you
3470              had in the header, although some data may have
3471              been added to the comments and time fields.
3472
3473              Most people won't do much here, perhaps setting
3474              a flag that marks the image as finished.
3475            */
3476        }
3477
3478
3479
3480

IV. Writing

3482       Much of this is very similar to reading.  However, everything of impor‐
3483       tance is repeated here, so you won't have to constantly look back up in
3484       the reading section to understand writing.
3485
3486
3487   Setup
3488       You will want to do the I/O initialization before you get into  libpng,
3489       so  if it doesn't work, you don't have anything to undo. If you are not
3490       using the standard I/O functions, you will need to  replace  them  with
3491       custom writing functions.  See the discussion under Customizing libpng.
3492
3493           FILE *fp = fopen(file_name, "wb");
3494
3495           if (!fp)
3496              return (ERROR);
3497
3498       Next, png_struct and png_info need to be allocated and initialized.  As
3499       these can be both relatively large, you may not want to store these  on
3500       the  stack,  unless you have stack space to spare.  Of course, you will
3501       want to check if they return NULL.  If you are also reading, you  won't
3502       want  to  name  your  read  structure  and  your  write  structure both
3503       "png_ptr"; you can call them anything you like, such as "read_ptr"  and
3504       "write_ptr".  Look at pngtest.c, for example.
3505
3506           png_structp png_ptr = png_create_write_struct
3507              (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
3508               user_error_fn, user_warning_fn);
3509
3510           if (!png_ptr)
3511              return (ERROR);
3512
3513           png_infop info_ptr = png_create_info_struct(png_ptr);
3514           if (!info_ptr)
3515           {
3516              png_destroy_write_struct(&png_ptr,
3517                  (png_infopp)NULL);
3518              return (ERROR);
3519           }
3520
3521       If  you  want  to  use  your  own  memory  allocation  routines, define
3522       PNG_USER_MEM_SUPPORTED and use png_create_write_struct_2()  instead  of
3523       png_create_write_struct():
3524
3525           png_structp png_ptr = png_create_write_struct_2
3526              (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
3527               user_error_fn, user_warning_fn, (png_voidp)
3528               user_mem_ptr, user_malloc_fn, user_free_fn);
3529
3530       After you have these structures, you will need to set up the error han‐
3531       dling.  When libpng encounters an error, it expects to  longjmp()  back
3532       to  your  routine.   Therefore, you will need to call setjmp() and pass
3533       the png_jmpbuf(png_ptr).  If you write the  file  from  different  rou‐
3534       tines,  you  will need to update the png_jmpbuf(png_ptr) every time you
3535       enter a new routine that will call a png_*() function.  See your  docu‐
3536       mentation  of  setjmp/longjmp for your compiler for more information on
3537       setjmp/longjmp.  See the discussion on libpng  error  handling  in  the
3538       Customizing  Libpng  section  below  for more information on the libpng
3539       error handling.
3540
3541           if (setjmp(png_jmpbuf(png_ptr)))
3542           {
3543           png_destroy_write_struct(&png_ptr, &info_ptr);
3544              fclose(fp);
3545              return (ERROR);
3546           }
3547           ...
3548           return;
3549
3550       If you would rather avoid the complexity of setjmp/longjmp issues,  you
3551       can compile libpng with PNG_NO_SETJMP, in which case errors will result
3552       in a call to PNG_ABORT() which defaults to abort().
3553
3554       You can #define PNG_ABORT() to a function that does something more use‐
3555       ful than abort(), as long as your function does not return.
3556
3557       Checking for invalid palette index on write was added at libpng 1.5.10.
3558       If a pixel contains an invalid (out-of-range)  index  libpng  issues  a
3559       benign  error.  This is enabled by default because this condition is an
3560       error according to the PNG specification, Clause 11.3.2, but the  error
3561       can be ignored in each png_ptr with
3562
3563          png_set_check_for_invalid_index(png_ptr, 0);
3564
3565       If  the error is ignored, or if png_benign_error() treats it as a warn‐
3566       ing, any invalid pixels are written as-is by the encoder, resulting  in
3567       an  invalid  PNG datastream as output.  In this case the application is
3568       responsible for ensuring that the pixel indexes are in  range  when  it
3569       writes a PLTE chunk with fewer entries than the bit depth would allow.
3570
3571       Now  you  need to set up the output code.  The default for libpng is to
3572       use the C function fwrite().  If you use this, you will need to pass  a
3573       valid  FILE  * in the function png_init_io().  Be sure that the file is
3574       opened in binary mode.  Again, if you wish to handle  writing  data  in
3575       another way, see the discussion on libpng I/O handling in the Customiz‐
3576       ing Libpng section below.
3577
3578           png_init_io(png_ptr, fp);
3579
3580       If you are embedding your PNG into a datastream such as MNG, and  don't
3581       want libpng to write the 8-byte signature, or if you have already writ‐
3582       ten the signature in your application, use
3583
3584           png_set_sig_bytes(png_ptr, 8);
3585
3586       to inform libpng that it should not write a signature.
3587
3588
3589   Write callbacks
3590       At this point, you can set up a callback function that will  be  called
3591       after  each  row  has  been  written,  which  you  can use to control a
3592       progress meter or the like.  It's demonstrated in pngtest.c.  You  must
3593       supply a function
3594
3595           void write_row_callback(png_structp png_ptr, png_uint_32 row,
3596              int pass);
3597           {
3598             /* put your code here */
3599           }
3600
3601       (You can give it another name that you like instead of "write_row_call‐
3602       back")
3603
3604       To inform libpng about your function, use
3605
3606           png_set_write_status_fn(png_ptr, write_row_callback);
3607
3608       When this function is called the row has already been  completely  pro‐
3609       cessed and it has also been written out.  The 'row' and 'pass' refer to
3610       the next row to be handled.  For the non-interlaced case the  row  that
3611       was  just handled is simply one less than the passed in row number, and
3612       pass will always be 0.  For the interlaced case the same applies unless
3613       the row value is 0, in which case the row just handled was the last one
3614       from one of the preceding passes.  Because interlacing may skip a  pass
3615       you  cannot  be  sure  that the preceding pass is just 'pass-1', if you
3616       really need to know what the last pass is record  (row,pass)  from  the
3617       callback and use the last recorded value each time.
3618
3619       As  with  the  user  transform  you  can  find the output row using the
3620       PNG_ROW_FROM_PASS_ROW macro.
3621
3622       You now have the option of modifying how the compression  library  will
3623       run.  The following functions are mainly for testing, but may be useful
3624       in some cases, like if you need to write PNG files extremely  fast  and
3625       are willing to give up some compression, or if you want to get the max‐
3626       imum possible compression at the expense of  slower  writing.   If  you
3627       have no special needs in this area, let the library do what it wants by
3628       not calling this function at all, as it has been  tuned  to  deliver  a
3629       good  speed/compression ratio. The second parameter to png_set_filter()
3630       is the filter method, for which the only valid values are 0 (as of  the
3631       July  1999  PNG specification, version 1.2) or 64 (if you are writing a
3632       PNG datastream that is to be embedded in a MNG datastream).  The  third
3633       parameter  is  a  flag  that  indicates  which filter type(s) are to be
3634       tested for each scanline.  See the PNG specification for details on the
3635       specific filter types.
3636
3637
3638           /* turn on or off filtering, and/or choose
3639              specific filters.  You can use either a single
3640              PNG_FILTER_VALUE_NAME or the bitwise OR of one
3641              or more PNG_FILTER_NAME masks.
3642            */
3643           png_set_filter(png_ptr, 0,
3644              PNG_FILTER_NONE  | PNG_FILTER_VALUE_NONE |
3645              PNG_FILTER_SUB   | PNG_FILTER_VALUE_SUB  |
3646              PNG_FILTER_UP    | PNG_FILTER_VALUE_UP   |
3647              PNG_FILTER_AVG   | PNG_FILTER_VALUE_AVG  |
3648              PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH|
3649              PNG_ALL_FILTERS  | PNG_FAST_FILTERS);
3650
3651       If an application wants to start and stop using particular filters dur‐
3652       ing compression, it should start out with all of the filters (to ensure
3653       that  the  previous  row  of  pixels will be stored in case it's needed
3654       later), and then add and remove them after the start of compression.
3655
3656       If you are writing a PNG datastream that is to be  embedded  in  a  MNG
3657       datastream, the second parameter can be either 0 or 64.
3658
3659       The png_set_compression_*() functions interface to the zlib compression
3660       library, and should mostly be ignored unless you really know  what  you
3661       are   doing.   The  only  generally  useful  call  is  png_set_compres‐
3662       sion_level() which changes how much time zlib spends on trying to  com‐
3663       press  the  image  data.  See the Compression Library (zlib.h and algo‐
3664       rithm.txt, distributed with zlib) for details on the  compression  lev‐
3665       els.
3666
3667           #include zlib.h
3668
3669           /* Set the zlib compression level */
3670           png_set_compression_level(png_ptr,
3671               Z_BEST_COMPRESSION);
3672
3673           /* Set other zlib parameters for compressing IDAT */
3674           png_set_compression_mem_level(png_ptr, 8);
3675           png_set_compression_strategy(png_ptr,
3676               Z_DEFAULT_STRATEGY);
3677           png_set_compression_window_bits(png_ptr, 15);
3678           png_set_compression_method(png_ptr, 8);
3679           png_set_compression_buffer_size(png_ptr, 8192)
3680
3681           /* Set zlib parameters for text compression
3682            * If you don't call these, the parameters
3683            * fall back on those defined for IDAT chunks
3684            */
3685           png_set_text_compression_mem_level(png_ptr, 8);
3686           png_set_text_compression_strategy(png_ptr,
3687               Z_DEFAULT_STRATEGY);
3688           png_set_text_compression_window_bits(png_ptr, 15);
3689           png_set_text_compression_method(png_ptr, 8);
3690
3691
3692   Setting the contents of info for output
3693       You  now  need  to fill in the png_info structure with all the data you
3694       wish to write before the actual image.  Note that the  only  thing  you
3695       are  allowed  to  write after the image is the text chunks and the time
3696       chunk (as of PNG Specification 1.2, anyway).  See  png_write_end()  and
3697       the latest PNG specification for more information on that.  If you wish
3698       to write them before the image, fill them in now, and flag that data as
3699       being valid.  If you want to wait until after the data, don't fill them
3700       until png_write_end().  For all the fields in png_info and  their  data
3701       types, see png.h.  For explanations of what the fields contain, see the
3702       PNG specification.
3703
3704       Some of the more important parts of the png_info are:
3705
3706           png_set_IHDR(png_ptr, info_ptr, width, height,
3707              bit_depth, color_type, interlace_type,
3708              compression_type, filter_method)
3709
3710           width          - holds the width of the image
3711                            in pixels (up to 2^31).
3712
3713           height         - holds the height of the image
3714                            in pixels (up to 2^31).
3715
3716           bit_depth      - holds the bit depth of one of the
3717                            image channels.
3718                            (valid values are 1, 2, 4, 8, 16
3719                            and depend also on the
3720                            color_type.  See also significant
3721                            bits (sBIT) below).
3722
3723           color_type     - describes which color/alpha
3724                            channels are present.
3725                            PNG_COLOR_TYPE_GRAY
3726                               (bit depths 1, 2, 4, 8, 16)
3727                            PNG_COLOR_TYPE_GRAY_ALPHA
3728                               (bit depths 8, 16)
3729                            PNG_COLOR_TYPE_PALETTE
3730                               (bit depths 1, 2, 4, 8)
3731                            PNG_COLOR_TYPE_RGB
3732                               (bit_depths 8, 16)
3733                            PNG_COLOR_TYPE_RGB_ALPHA
3734                               (bit_depths 8, 16)
3735
3736                            PNG_COLOR_MASK_PALETTE
3737                            PNG_COLOR_MASK_COLOR
3738                            PNG_COLOR_MASK_ALPHA
3739
3740           interlace_type - PNG_INTERLACE_NONE or
3741                            PNG_INTERLACE_ADAM7
3742
3743           compression_type - (must be
3744                            PNG_COMPRESSION_TYPE_DEFAULT)
3745
3746           filter_method  - (must be PNG_FILTER_TYPE_DEFAULT
3747                            or, if you are writing a PNG to
3748                            be embedded in a MNG datastream,
3749                            can also be
3750                            PNG_INTRAPIXEL_DIFFERENCING)
3751
3752       If you call png_set_IHDR(), the call must  appear  before  any  of  the
3753       other  png_set_*() functions, because they might require access to some
3754       of the IHDR settings.   The  remaining  png_set_*()  functions  can  be
3755       called in any order.
3756
3757       If  you  wish,  you  can reset the compression_type, interlace_type, or
3758       filter_method later by calling png_set_IHDR() again; if  you  do  this,
3759       the  width,  height, bit_depth, and color_type must be the same in each
3760       call.
3761
3762           png_set_PLTE(png_ptr, info_ptr, palette,
3763              num_palette);
3764
3765           palette        - the palette for the file
3766                            (array of png_color)
3767           num_palette    - number of entries in the palette
3768
3769
3770           png_set_gAMA(png_ptr, info_ptr, file_gamma);
3771           png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
3772
3773           file_gamma     - the gamma at which the image was
3774                            created (PNG_INFO_gAMA)
3775
3776           int_file_gamma - 100,000 times the gamma at which
3777                            the image was created
3778
3779           png_set_cHRM(png_ptr, info_ptr,  white_x, white_y, red_x, red_y,
3780                            green_x, green_y, blue_x, blue_y)
3781           png_set_cHRM_XYZ(png_ptr, info_ptr, red_X, red_Y, red_Z, green_X,
3782                            green_Y, green_Z, blue_X, blue_Y, blue_Z)
3783           png_set_cHRM_fixed(png_ptr, info_ptr, int_white_x, int_white_y,
3784                            int_red_x, int_red_y, int_green_x, int_green_y,
3785                            int_blue_x, int_blue_y)
3786           png_set_cHRM_XYZ_fixed(png_ptr, info_ptr, int_red_X, int_red_Y,
3787                            int_red_Z, int_green_X, int_green_Y, int_green_Z,
3788                            int_blue_X, int_blue_Y, int_blue_Z)
3789
3790           {white,red,green,blue}_{x,y}
3791                            A color space encoding specified using  the  chro‐
3792       maticities
3793                            of the end points and the white point.
3794
3795           {red,green,blue}_{X,Y,Z}
3796                            A  color space encoding specified using the encod‐
3797       ing end
3798                            points - the CIE tristimulus specification of  the
3799       intended
3800                            color  of  the red, green and blue channels in the
3801       PNG RGB
3802                            data.  The white point is simply the  sum  of  the
3803       three end
3804                            points.
3805
3806           png_set_sRGB(png_ptr, info_ptr, srgb_intent);
3807
3808           srgb_intent    - the rendering intent
3809                            (PNG_INFO_sRGB) The presence of
3810                            the sRGB chunk means that the pixel
3811                            data is in the sRGB color space.
3812                            This chunk also implies specific
3813                            values of gAMA and cHRM.  Rendering
3814                            intent is the CSS-1 property that
3815                            has been defined by the International
3816                            Color Consortium
3817                            (http://www.color.org).
3818                            It can be one of
3819                            PNG_sRGB_INTENT_SATURATION,
3820                            PNG_sRGB_INTENT_PERCEPTUAL,
3821                            PNG_sRGB_INTENT_ABSOLUTE, or
3822                            PNG_sRGB_INTENT_RELATIVE.
3823
3824
3825           png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
3826              srgb_intent);
3827
3828           srgb_intent    - the rendering intent
3829                            (PNG_INFO_sRGB) The presence of the
3830                            sRGB chunk means that the pixel
3831                            data is in the sRGB color space.
3832                            This function also causes gAMA and
3833                            cHRM chunks with the specific values
3834                            that are consistent with sRGB to be
3835                            written.
3836
3837           png_set_iCCP(png_ptr, info_ptr, name, compression_type,
3838                              profile, proflen);
3839
3840           name             - The profile name.
3841
3842           compression_type - The compression type; always
3843                              PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
3844                              You may give NULL to this argument to
3845                              ignore it.
3846
3847           profile          - International Color Consortium color
3848                              profile data. May contain NULs.
3849
3850           proflen          - length of profile data in bytes.
3851
3852           png_set_sBIT(png_ptr, info_ptr, sig_bit);
3853
3854           sig_bit        - the number of significant bits for
3855                            (PNG_INFO_sBIT) each of the gray, red,
3856                            green, and blue channels, whichever are
3857                            appropriate for the given color type
3858                            (png_color_16)
3859
3860           png_set_tRNS(png_ptr, info_ptr, trans_alpha,
3861              num_trans, trans_color);
3862
3863           trans_alpha    - array of alpha (transparency)
3864                            entries for palette (PNG_INFO_tRNS)
3865
3866           num_trans      - number of transparent entries
3867                            (PNG_INFO_tRNS)
3868
3869           trans_color    - graylevel or color sample values
3870                            (in order red, green, blue) of the
3871                            single transparent color for
3872                            non-paletted images (PNG_INFO_tRNS)
3873
3874           png_set_eXIf_1(png_ptr, info_ptr, num_exif, exif);
3875
3876           exif           - Exif profile (array of
3877                            png_byte) (PNG_INFO_eXIf)
3878
3879           png_set_hIST(png_ptr, info_ptr, hist);
3880
3881           hist           - histogram of palette (array of
3882                            png_uint_16) (PNG_INFO_hIST)
3883
3884           png_set_tIME(png_ptr, info_ptr, mod_time);
3885
3886           mod_time       - time image was last modified
3887                            (PNG_VALID_tIME)
3888
3889           png_set_bKGD(png_ptr, info_ptr, background);
3890
3891           background     - background color (of type
3892                            png_color_16p) (PNG_VALID_bKGD)
3893
3894           png_set_text(png_ptr, info_ptr, text_ptr, num_text);
3895
3896           text_ptr       - array of png_text holding image
3897                            comments
3898
3899           text_ptr[i].compression - type of compression used
3900                        on "text" PNG_TEXT_COMPRESSION_NONE
3901                                  PNG_TEXT_COMPRESSION_zTXt
3902                                  PNG_ITXT_COMPRESSION_NONE
3903                                  PNG_ITXT_COMPRESSION_zTXt
3904           text_ptr[i].key   - keyword for comment.  Must contain
3905                        1-79 characters.
3906           text_ptr[i].text  - text comments for current
3907                                keyword.  Can be NULL or empty.
3908           text_ptr[i].text_length - length of text string,
3909                        after decompression, 0 for iTXt
3910           text_ptr[i].itxt_length - length of itxt string,
3911                        after decompression, 0 for tEXt/zTXt
3912           text_ptr[i].lang  - language of comment (NULL or
3913                                empty for unknown).
3914           text_ptr[i].translated_keyword  - keyword in UTF-8 (NULL
3915                                or empty for unknown).
3916
3917           Note that the itxt_length, lang, and lang_key
3918           members of the text_ptr structure only exist when the
3919           library is built with iTXt chunk support.  Prior to
3920           libpng-1.4.0 the library was built by default without
3921           iTXt support. Also note that when iTXt is supported,
3922           they contain NULL pointers when the "compression"
3923           field contains PNG_TEXT_COMPRESSION_NONE or
3924           PNG_TEXT_COMPRESSION_zTXt.
3925
3926           num_text       - number of comments
3927
3928           png_set_sPLT(png_ptr, info_ptr, &palette_ptr,
3929              num_spalettes);
3930
3931           palette_ptr    - array of png_sPLT_struct structures
3932                            to be added to the list of palettes
3933                            in the info structure.
3934           num_spalettes  - number of palette structures to be
3935                            added.
3936
3937           png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
3938               unit_type);
3939
3940           offset_x  - positive offset from the left
3941                            edge of the screen
3942
3943           offset_y  - positive offset from the top
3944                            edge of the screen
3945
3946           unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
3947
3948           png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
3949               unit_type);
3950
3951           res_x       - pixels/unit physical resolution
3952                         in x direction
3953
3954           res_y       - pixels/unit physical resolution
3955                         in y direction
3956
3957           unit_type   - PNG_RESOLUTION_UNKNOWN,
3958                         PNG_RESOLUTION_METER
3959
3960           png_set_sCAL(png_ptr, info_ptr, unit, width, height)
3961
3962           unit        - physical scale units (an integer)
3963
3964           width       - width of a pixel in physical scale units
3965
3966           height      - height of a pixel in physical scale units
3967                         (width and height are doubles)
3968
3969           png_set_sCAL_s(png_ptr, info_ptr, unit, width, height)
3970
3971           unit        - physical scale units (an integer)
3972
3973           width       - width of a pixel in physical scale units
3974                         expressed as a string
3975
3976           height      - height of a pixel in physical scale units
3977                        (width and height are strings like "2.54")
3978
3979           png_set_unknown_chunks(png_ptr, info_ptr, &unknowns,
3980              num_unknowns)
3981
3982           unknowns          - array of png_unknown_chunk
3983                               structures holding unknown chunks
3984           unknowns[i].name  - name of unknown chunk
3985           unknowns[i].data  - data of unknown chunk
3986           unknowns[i].size  - size of unknown chunk's data
3987           unknowns[i].location - position to write chunk in file
3988                                  0: do not write chunk
3989                                  PNG_HAVE_IHDR: before PLTE
3990                                  PNG_HAVE_PLTE: before IDAT
3991                                  PNG_AFTER_IDAT: after IDAT
3992
3993       The  "location"  member  is set automatically according to what part of
3994       the output file has already been written.  You  can  change  its  value
3995       after  calling  png_set_unknown_chunks()  as demonstrated in pngtest.c.
3996       Within each of the "locations", the chunks are sequenced  according  to
3997       their  position  in  the structure (that is, the value of "i", which is
3998       the order in which the chunk was either read from  the  input  file  or
3999       defined with png_set_unknown_chunks).
4000
4001       A  quick  word  about  text and num_text.  text is an array of png_text
4002       structures.  num_text is the number of valid structures in  the  array.
4003       Each png_text structure holds a language code, a keyword, a text value,
4004       and a compression type.
4005
4006       The compression types have the same valid numbers  as  the  compression
4007       types  of  the  image  data.  Currently, the only valid number is zero.
4008       However, you can store text either compressed or  uncompressed,  unlike
4009       images,  which  always have to be compressed.  So if you don't want the
4010       text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
4011       Because  tEXt and zTXt chunks don't have a language field, if you spec‐
4012       ify PNG_TEXT_COMPRESSION_NONE or PNG_TEXT_COMPRESSION_zTXt any language
4013       code or translated keyword will not be written out.
4014
4015       Until text gets around a few hundred bytes, it is not worth compressing
4016       it.  After the text has been written out to the file,  the  compression
4017       type   is  set  to  PNG_TEXT_COMPRESSION_NONE_WR  or  PNG_TEXT_COMPRES‐
4018       SION_zTXt_WR, so that it isn't written out again at the  end  (in  case
4019       you are calling png_write_end() with the same struct).
4020
4021       The keywords that are given in the PNG Specification are:
4022
4023           Title            Short (one line) title or
4024                            caption for image
4025
4026           Author           Name of image's creator
4027
4028           Description      Description of image (possibly long)
4029
4030           Copyright        Copyright notice
4031
4032           Creation Time    Time of original image creation
4033                            (usually RFC 1123 format, see below)
4034
4035           Software         Software used to create the image
4036
4037           Disclaimer       Legal disclaimer
4038
4039           Warning          Warning of nature of content
4040
4041           Source           Device used to create the image
4042
4043           Comment          Miscellaneous comment; conversion
4044                            from other image format
4045
4046       The keyword-text pairs work like this.  Keywords should be short simple
4047       descriptions of what the comment is about.  Some typical  keywords  are
4048       found in the PNG specification, as is some recommendations on keywords.
4049       You can repeat keywords in a file.  You can even write some text before
4050       the  image and some after.  For example, you may want to put a descrip‐
4051       tion of the image before the image,  but  leave  the  disclaimer  until
4052       after, so viewers working over modem connections don't have to wait for
4053       the disclaimer to go over the modem before they start seeing the image.
4054       Finally,  keywords  should  be full words, not abbreviations.  Keywords
4055       and text are in the ISO 8859-1 (Latin-1) character set (a  superset  of
4056       regular  ASCII) and can not contain NUL characters, and should not con‐
4057       tain control or other unprintable characters.   To  make  the  comments
4058       widely  readable,  stick  with  basic ASCII, and avoid machine specific
4059       character set extensions like the IBM-PC character  set.   The  keyword
4060       must  be  present,  but  you  can leave off the text string on non-com‐
4061       pressed pairs.  Compressed pairs must have a text string, as  only  the
4062       text  string is compressed anyway, so the compression would be meaning‐
4063       less.
4064
4065       PNG supports modification time via the png_time structure.  Two conver‐
4066       sion  routines  are  provided, png_convert_from_time_t() for time_t and
4067       png_convert_from_struct_tm() for struct tm.  The  time_t  routine  uses
4068       gmtime().   You  don't  have to use either of these, but if you wish to
4069       fill in the png_time structure directly, you should provide the time in
4070       universal time (GMT) if possible instead of your local time.  Note that
4071       the year number is the full year (e.g. 1998, rather than 98  -  PNG  is
4072       year 2000 compliant!), and that months start with 1.
4073
4074       If  you  want  to  store  the  time of the original image creation, you
4075       should use a plain tEXt chunk with the "Creation Time"  keyword.   This
4076       is  necessary  because  the  "creation time" of a PNG image is somewhat
4077       vague, depending on whether you mean the PNG file, the time  the  image
4078       was created in a non-PNG format, a still photo from which the image was
4079       scanned, or possibly the subject matter itself.  In order to facilitate
4080       machine-readable dates, it is recommended that the "Creation Time" tEXt
4081       chunk use RFC 1123 format dates (e.g.  "22  May  1997  18:07:10  GMT"),
4082       although  this  isn't  a requirement.  Unlike the tIME chunk, the "Cre‐
4083       ation Time" tEXt chunk is not expected to be automatically  changed  by
4084       the  software.   To  facilitate  the  use of RFC 1123 dates, a function
4085       png_convert_to_rfc1123_buffer(buffer, png_timep) is provided to convert
4086       from  PNG time to an RFC 1123 format string.  The caller must provide a
4087       writeable buffer of at least 29 bytes.
4088
4089
4090   Writing unknown chunks
4091       You can use the png_set_unknown_chunks function  to  queue  up  private
4092       chunks  for writing.  You give it a chunk name, location, raw data, and
4093       a size.  You also must use png_set_keep_unknown_chunks() to ensure that
4094       libpng  will  handle them.  That's all there is to it.  The chunks will
4095       be  written   by   the   next   following   png_write_info_before_PLTE,
4096       png_write_info, or png_write_end function, depending upon the specified
4097       location.   Any  chunks  previously  read  into  the  info  structure's
4098       unknown-chunk  list  will also be written out in a sequence that satis‐
4099       fies the PNG specification's ordering rules.
4100
4101       Here is an example of writing two private chunks, prVt and miNE:
4102
4103           #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
4104           /* Set unknown chunk data */
4105           png_unknown_chunk unk_chunk[2];
4106           strcpy((char *) unk_chunk[0].name, "prVt";
4107           unk_chunk[0].data = (unsigned char *) "PRIVATE DATA";
4108           unk_chunk[0].size = strlen(unk_chunk[0].data)+1;
4109           unk_chunk[0].location = PNG_HAVE_IHDR;
4110           strcpy((char *) unk_chunk[1].name, "miNE";
4111           unk_chunk[1].data = (unsigned char *) "MY CHUNK DATA";
4112           unk_chunk[1].size = strlen(unk_chunk[0].data)+1;
4113           unk_chunk[1].location = PNG_AFTER_IDAT;
4114           png_set_unknown_chunks(write_ptr, write_info_ptr,
4115               unk_chunk, 2);
4116           /* Needed because miNE is not safe-to-copy */
4117           png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS,
4118              (png_bytep) "miNE", 1);
4119           # if PNG_LIBPNG_VER < 10600
4120             /* Deal with unknown chunk location bug in 1.5.x and earlier */
4121             png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
4122             png_set_unknown_chunk_location(png, info, 1, PNG_AFTER_IDAT);
4123           # endif
4124           # if PNG_LIBPNG_VER < 10500
4125             /* PNG_AFTER_IDAT  writes  two  copies  of  the  chunk  prior  to
4126       libpng-1.5.0,
4127              *  one before IDAT and another after IDAT, so don't use it; only
4128       use
4129              * PNG_HAVE_IHDR location.  This call resets the location  previ‐
4130       ously
4131              *  set  by  assignment  and png_set_unknown_chunk_location() for
4132       chunk 1.
4133              */
4134             png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR);
4135           # endif
4136           #endif
4137
4138
4139   The high-level write interface
4140       At this point there are two ways to  proceed;  through  the  high-level
4141       write  interface,  or through a sequence of low-level write operations.
4142       You can use the high-level interface if your image data is  present  in
4143       the  info structure.  All defined output transformations are permitted,
4144       enabled by the following masks.
4145
4146           PNG_TRANSFORM_IDENTITY      No transformation
4147           PNG_TRANSFORM_PACKING       Pack 1, 2 and 4-bit samples
4148           PNG_TRANSFORM_PACKSWAP      Change order of packed
4149                                       pixels to LSB first
4150           PNG_TRANSFORM_INVERT_MONO   Invert monochrome images
4151           PNG_TRANSFORM_SHIFT         Normalize pixels to the
4152                                       sBIT depth
4153           PNG_TRANSFORM_BGR           Flip RGB to BGR, RGBA
4154                                       to BGRA
4155           PNG_TRANSFORM_SWAP_ALPHA    Flip RGBA to ARGB or GA
4156                                       to AG
4157           PNG_TRANSFORM_INVERT_ALPHA  Change alpha from opacity
4158                                       to transparency
4159           PNG_TRANSFORM_SWAP_ENDIAN   Byte-swap 16-bit samples
4160           PNG_TRANSFORM_STRIP_FILLER        Strip out filler
4161                                             bytes (deprecated).
4162           PNG_TRANSFORM_STRIP_FILLER_BEFORE Strip out leading
4163                                             filler bytes
4164           PNG_TRANSFORM_STRIP_FILLER_AFTER  Strip out trailing
4165                                             filler bytes
4166
4167       If you have valid image  data  in  the  info  structure  (you  can  use
4168       png_set_rows()  to  put  image  data  in the info structure), simply do
4169       this:
4170
4171           png_write_png(png_ptr, info_ptr, png_transforms, NULL)
4172
4173       where png_transforms is an integer containing the bitwise  OR  of  some
4174       set   of   transformation   flags.    This   call   is   equivalent  to
4175       png_write_info(), followed the set of transformations indicated by  the
4176       transform mask, then png_write_image(), and finally png_write_end().
4177
4178       (The  final  parameter  of this call is not yet used.  Someday it might
4179       point to transformation  parameters  required  by  some  future  output
4180       transform.)
4181
4182       You  must use png_transforms and not call any png_set_transform() func‐
4183       tions when you use png_write_png().
4184
4185
4186   The low-level write interface
4187       If you are going the low-level route instead,  you  are  now  ready  to
4188       write  all  the  file  information up to the actual image data.  You do
4189       this with a call to png_write_info().
4190
4191           png_write_info(png_ptr, info_ptr);
4192
4193       Note that there is  one  transformation  you  may  need  to  do  before
4194       png_write_info().   In  PNG files, the alpha channel in an image is the
4195       level of opacity.  If your data is supplied as a level of transparency,
4196       you  can  invert  the  alpha  channel before you write it, so that 0 is
4197       fully transparent and 255 (in 8-bit or paletted images)  or  65535  (in
4198       16-bit images) is fully opaque, with
4199
4200           png_set_invert_alpha(png_ptr);
4201
4202       This  must  appear  before  png_write_info()  instead of later with the
4203       other transformations because in the case of paletted images  the  tRNS
4204       chunk  data  has  to  be inverted before the tRNS chunk is written.  If
4205       your image is not a paletted image, the tRNS data (which in such  cases
4206       represents  a single color to be rendered as transparent) won't need to
4207       be changed, and you  can  safely  do  this  transformation  after  your
4208       png_write_info() call.
4209
4210       If you need to write a private chunk that you want to appear before the
4211       PLTE chunk when PLTE is present, you can write  the  PNG  info  in  two
4212       steps, and insert code to write your own chunk between them:
4213
4214           png_write_info_before_PLTE(png_ptr, info_ptr);
4215           png_set_unknown_chunks(png_ptr, info_ptr, ...);
4216           png_write_info(png_ptr, info_ptr);
4217
4218       After  you've  written the file information, you can set up the library
4219       to handle any special transformations of the image data.   The  various
4220       ways  to  transform  the  data will be described in the order that they
4221       should occur.  This is important, as some of  these  change  the  color
4222       type and/or bit depth of the data, and some others only work on certain
4223       color types and bit depths.  Even though each transformation checks  to
4224       see  if it has data that it can do something with, you should make sure
4225       to only enable a transformation if it will be valid for the data.   For
4226       example, don't swap red and blue on grayscale data.
4227
4228       PNG  files  store RGB pixels packed into 3 or 6 bytes.  This code tells
4229       the library to strip input data that has 4 or 8 bytes per pixel down to
4230       3  or  6  bytes  (or  strip 2 or 4-byte grayscale+filler data to 1 or 2
4231       bytes per pixel).
4232
4233           png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
4234
4235       where the 0 is unused, and the location is either PNG_FILLER_BEFORE  or
4236       PNG_FILLER_AFTER,  depending  upon whether the filler byte in the pixel
4237       is stored XRGB or RGBX.
4238
4239       PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small  as
4240       they can, resulting in, for example, 8 pixels per byte for 1 bit files.
4241       If the data is supplied at 1 pixel per byte, use this code, which  will
4242       correctly pack the pixels into a single byte:
4243
4244           png_set_packing(png_ptr);
4245
4246       PNG  files  reduce  possible bit depths to 1, 2, 4, 8, and 16.  If your
4247       data is of another bit depth, you can write an sBIT chunk into the file
4248       so that decoders can recover the original data if desired.
4249
4250           /* Set the true bit depth of the image data */
4251           if (color_type & PNG_COLOR_MASK_COLOR)
4252           {
4253              sig_bit.red = true_bit_depth;
4254              sig_bit.green = true_bit_depth;
4255              sig_bit.blue = true_bit_depth;
4256           }
4257
4258           else
4259           {
4260              sig_bit.gray = true_bit_depth;
4261           }
4262
4263           if (color_type & PNG_COLOR_MASK_ALPHA)
4264           {
4265              sig_bit.alpha = true_bit_depth;
4266           }
4267
4268           png_set_sBIT(png_ptr, info_ptr, &sig_bit);
4269
4270       If  the  data is stored in the row buffer in a bit depth other than one
4271       supported by PNG (e.g. 3 bit data in the range 0-7 for  a  4-bit  PNG),
4272       this  will scale the values to appear to be the correct bit depth as is
4273       required by PNG.
4274
4275           png_set_shift(png_ptr, &sig_bit);
4276
4277       PNG files store 16-bit pixels in network byte  order  (big-endian,  ie.
4278       most significant bits first).  This code would be used if they are sup‐
4279       plied the other way (little-endian, i.e. least significant bits  first,
4280       the way PCs store them):
4281
4282           if (bit_depth > 8)
4283              png_set_swap(png_ptr);
4284
4285       If  you  are using packed-pixel images (1, 2, or 4 bits/pixel), and you
4286       need to change the order the pixels are packed into bytes, you can use:
4287
4288           if (bit_depth < 8)
4289              png_set_packswap(png_ptr);
4290
4291       PNG files store 3 color pixels in red, green, blue  order.   This  code
4292       would be used if they are supplied as blue, green, red:
4293
4294           png_set_bgr(png_ptr);
4295
4296       PNG  files describe monochrome as black being zero and white being one.
4297       This code would be used if the pixels are supplied with  this  reversed
4298       (black being one and white being zero):
4299
4300           png_set_invert_mono(png_ptr);
4301
4302       Finally,  you can write your own transformation function if none of the
4303       existing ones meets your needs.  This is done  by  setting  a  callback
4304       with
4305
4306           png_set_write_user_transform_fn(png_ptr,
4307              write_transform_fn);
4308
4309       You must supply the function
4310
4311           void write_transform_fn(png_structp png_ptr, png_row_infop
4312              row_info, png_bytep data)
4313
4314       See  pngtest.c  for  a  working  example.  Your function will be called
4315       before any of the other transformations are  processed.   If  supported
4316       libpng  also  supplies  an  information routine that may be called from
4317       your callback:
4318
4319          png_get_current_row_number(png_ptr);
4320          png_get_current_pass_number(png_ptr);
4321
4322       This returns the current row passed to the transform.  With  interlaced
4323       images the value returned is the row in the input sub-image image.  Use
4324       PNG_ROW_FROM_PASS_ROW(row, pass) and  PNG_COL_FROM_PASS_COL(col,  pass)
4325       to  find  the  output  pixel  (x,y) given an interlaced sub-image pixel
4326       (row,col,pass).
4327
4328       The discussion of interlace handling above contains more information on
4329       how to use these values.
4330
4331       You can also set up a pointer to a user structure for use by your call‐
4332       back function.
4333
4334           png_set_user_transform_info(png_ptr, user_ptr, 0, 0);
4335
4336       The user_channels  and  user_depth  parameters  of  this  function  are
4337       ignored when writing; you can set them to zero as shown.
4338
4339       You  can  retrieve  the  pointer  via  the function png_get_user_trans‐
4340       form_ptr().  For example:
4341
4342           voidp write_user_transform_ptr =
4343              png_get_user_transform_ptr(png_ptr);
4344
4345       It is possible to have libpng flush any pending  output,  either  manu‐
4346       ally,  or automatically after a certain number of lines have been writ‐
4347       ten.  To flush the output stream a single time call:
4348
4349           png_write_flush(png_ptr);
4350
4351       and to have libpng flush the output stream periodically after a certain
4352       number of scanlines have been written, call:
4353
4354           png_set_flush(png_ptr, nrows);
4355
4356       Note   that   the   distance   between  rows  is  from  the  last  time
4357       png_write_flush() was called, or the first row of the image if  it  has
4358       never  been  called.   So if you write 50 lines, and then png_set_flush
4359       25, it will flush the output on the next scanline, and every  25  lines
4360       thereafter,  unless  png_write_flush()  is  called before 25 more lines
4361       have been written.  If nrows is too small (less than about 10 lines for
4362       a  640 pixel wide RGB image) the image compression may decrease notice‐
4363       ably (although this may  be  acceptable  for  real-time  applications).
4364       Infrequent  flushing will only degrade the compression performance by a
4365       few percent over images that do not use flushing.
4366
4367
4368   Writing the image data
4369       That's it for the transformations.  Now you can write the  image  data.
4370       The  simplest  way to do this is in one function call.  If you have the
4371       whole image in memory, you can just call png_write_image()  and  libpng
4372       will write the image.  You will need to pass in an array of pointers to
4373       each row.  This function  automatically  handles  interlacing,  so  you
4374       don't  need  to call png_set_interlace_handling() or call this function
4375       multiple  times,  or  any  of   that   other   stuff   necessary   with
4376       png_write_rows().
4377
4378           png_write_image(png_ptr, row_pointers);
4379
4380       where row_pointers is:
4381
4382           png_byte *row_pointers[height];
4383
4384       You can point to void or char or whatever you use for pixels.
4385
4386       If  you  don't  want  to  write  the  whole  image at once, you can use
4387       png_write_rows() instead.  If the file is not interlaced, this is  sim‐
4388       ple:
4389
4390           png_write_rows(png_ptr, row_pointers,
4391              number_of_rows);
4392
4393       row_pointers is the same as in the png_write_image() call.
4394
4395       If  you are just writing one row at a time, you can do this with a sin‐
4396       gle row_pointer instead of an array of row_pointers:
4397
4398           png_bytep row_pointer = row;
4399
4400           png_write_row(png_ptr, row_pointer);
4401
4402       When the file is interlaced, things can get a good  deal  more  compli‐
4403       cated.   The  only  currently (as of the PNG Specification version 1.2,
4404       dated July 1999) defined  interlacing  scheme  for  PNG  files  is  the
4405       "Adam7"  interlace scheme, that breaks down an image into seven smaller
4406       images of varying size.  libpng will build these images for you, or you
4407       can  do them yourself.  If you want to build them yourself, see the PNG
4408       specification for details of which pixels to write when.
4409
4410       If you don't want libpng to handle the interlacing  details,  just  use
4411       png_set_interlace_handling() and call png_write_rows() the correct num‐
4412       ber of times to write all the sub-images  (png_set_interlace_handling()
4413       returns the number of sub-images.)
4414
4415       If  you want libpng to build the sub-images, call this before you start
4416       writing any rows:
4417
4418           number_of_passes = png_set_interlace_handling(png_ptr);
4419
4420       This will return the number  of  passes  needed.   Currently,  this  is
4421       seven, but may change if another interlace type is added.
4422
4423       Then write the complete image number_of_passes times.
4424
4425           png_write_rows(png_ptr, row_pointers, number_of_rows);
4426
4427       Think  carefully  before you write an interlaced image.  Typically code
4428       that reads such images reads all the image  data  into  memory,  uncom‐
4429       pressed,  before  doing  any processing.  Only code that can display an
4430       image on the fly can take advantage of the interlacing  and  even  then
4431       the  image  has  to  be exactly the correct size for the output device,
4432       because scaling an image requires adjacent pixels  and  these  are  not
4433       available until all the passes have been read.
4434
4435       If you do write an interlaced image you will hardly ever need to handle
4436       the interlacing yourself.  Call  png_set_interlace_handling()  and  use
4437       the approach described above.
4438
4439       The  only  time it is conceivable that you will really need to write an
4440       interlaced image pass-by-pass is when you have read one  pass  by  pass
4441       and  made some pixel-by-pixel transformation to it, as described in the
4442       read code above.  In this case use the PNG_PASS_ROWS and  PNG_PASS_COLS
4443       macros to determine the size of each sub-image in turn and simply write
4444       the rows you obtained from the read code.
4445
4446
4447   Finishing a sequential write
4448       After you are finished writing the image, you should finish writing the
4449       file.   If  you  are interested in writing comments or time, you should
4450       pass an appropriately filled png_info pointer.  If you are  not  inter‐
4451       ested, you can pass NULL.
4452
4453           png_write_end(png_ptr, info_ptr);
4454
4455       When you are done, you can free all memory used by libpng like this:
4456
4457           png_destroy_write_struct(&png_ptr, &info_ptr);
4458
4459       It  is  also  possible  to  individually free the info_ptr members that
4460       point to libpng-allocated storage with the following function:
4461
4462           png_free_data(png_ptr, info_ptr, mask, seq)
4463
4464           mask  - identifies data to be freed, a mask
4465                   containing the bitwise OR of one or
4466                   more of
4467                     PNG_FREE_PLTE, PNG_FREE_TRNS,
4468                     PNG_FREE_HIST, PNG_FREE_ICCP,
4469                     PNG_FREE_PCAL, PNG_FREE_ROWS,
4470                     PNG_FREE_SCAL, PNG_FREE_SPLT,
4471                     PNG_FREE_TEXT, PNG_FREE_UNKN,
4472                   or simply PNG_FREE_ALL
4473
4474           seq   - sequence number of item to be freed
4475                   (-1 for all items)
4476
4477       This function may be  safely  called  when  the  relevant  storage  has
4478       already  been freed, or has not yet been allocated, or was allocated by
4479       the user  and not by libpng,  and will in those cases do nothing.   The
4480       "seq"  parameter is ignored if only one item of the selected data type,
4481       such as PLTE, is allowed.  If "seq" is not -1, and multiple  items  are
4482       allowed for the data type identified in the mask, such as text or sPLT,
4483       only the n'th item in the structure is freed, where n is "seq".
4484
4485       If you allocated data such as a palette that you passed  in  to  libpng
4486       with  png_set_*,  you  must  not  free it until just before the call to
4487       png_destroy_write_struct().
4488
4489       The default behavior is only to free data that was allocated internally
4490       by libpng.  This can be changed, so that libpng will not free the data,
4491       or so that it will free data  that  was  allocated  by  the  user  with
4492       png_malloc()  or png_calloc() and passed in via a png_set_*() function,
4493       with
4494
4495           png_data_freer(png_ptr, info_ptr, freer, mask)
4496
4497           freer  - one of
4498                      PNG_DESTROY_WILL_FREE_DATA
4499                      PNG_SET_WILL_FREE_DATA
4500                      PNG_USER_WILL_FREE_DATA
4501
4502           mask   - which data elements are affected
4503                    same choices as in png_free_data()
4504
4505       For example, to transfer responsibility  for  some  data  from  a  read
4506       structure to a write structure, you could use
4507
4508           png_data_freer(read_ptr, read_info_ptr,
4509              PNG_USER_WILL_FREE_DATA,
4510              PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
4511
4512           png_data_freer(write_ptr, write_info_ptr,
4513              PNG_DESTROY_WILL_FREE_DATA,
4514              PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
4515
4516       thereby  briefly reassigning responsibility for freeing to the user but
4517       immediately afterwards reassigning it once more  to  the  write_destroy
4518       function.   Having done this, it would then be safe to destroy the read
4519       structure and continue to use the PLTE, tRNS,  and  hIST  data  in  the
4520       write structure.
4521
4522       This  function  only affects data that has already been allocated.  You
4523       can call this function before calling after the  png_set_*()  functions
4524       to  control whether the user or png_destroy_*() is supposed to free the
4525       data.  When the user assumes responsibility for libpng-allocated  data,
4526       the  application  must  use  png_free()  to  free it, and when the user
4527       transfers responsibility to libpng for data that  the  user  has  allo‐
4528       cated, the user must have used png_malloc() or png_calloc() to allocate
4529       it.
4530
4531       If you  allocated  text_ptr.text,  text_ptr.lang,  and  text_ptr.trans‐
4532       lated_keyword  separately,  do  not transfer responsibility for freeing
4533       text_ptr to libpng, because when libpng fills a png_text  structure  it
4534       combines  these  members  with the key member, and png_free_data() will
4535       free only text_ptr.key.  Similarly, if you transfer responsibility  for
4536       free'ing  text_ptr  from  libpng  to your application, your application
4537       must not separately free those members.  For a more compact example  of
4538       writing a PNG image, see the file example.c.
4539
4540

V. Simplified API

4542       The  simplified  API, which became available in libpng-1.6.0, hides the
4543       details of both libpng and the PNG file format itself.  It  allows  PNG
4544       files to be read into a very limited number of in-memory bitmap formats
4545       or to be written from the same formats.  If these formats do not accom‐
4546       modate  your needs then you can, and should, use the more sophisticated
4547       APIs above - these support a wide variety of in-memory  formats  and  a
4548       wide  variety of sophisticated transformations to those formats as well
4549       as a wide variety of APIs to manipulate ancilliary information.
4550
4551       To read a PNG file using the simplified API:
4552
4553         1) Declare a 'png_image' structure (see below) on the stack, set the
4554            version field to PNG_IMAGE_VERSION and  the  'opaque'  pointer  to
4555       NULL
4556            (this is REQUIRED, your program may crash if you don't do it.)
4557
4558         2) Call the appropriate png_image_begin_read... function.
4559
4560         3) Set the png_image 'format' member to the required sample format.
4561
4562         4) Allocate a buffer for the image and, if required, the color-map.
4563
4564         5) Call png_image_finish_read to read the image and, if required, the
4565            color-map into your buffers.
4566
4567       There  are  no  restrictions on the format of the PNG input itself; all
4568       valid color types, bit depths, and interlace  methods  are  acceptable,
4569       and  the  input  image is transformed as necessary to the requested in-
4570       memory format during the png_image_finish_read() step.  The only caveat
4571       is  that  if  you request a color-mapped image from a PNG that is full-
4572       color or makes complex use of an alpha channel  the  transformation  is
4573       extremely lossy and the result may look terrible.
4574
4575       To write a PNG file using the simplified API:
4576
4577         1) Declare a 'png_image' structure on the stack and memset()
4578            it to all zero.
4579
4580         2) Initialize the members of the structure that describe the
4581            image, setting the 'format' member to the format of the
4582            image samples.
4583
4584         3) Call the appropriate png_image_write... function with a
4585            pointer to the image and, if necessary, the color-map to write
4586            the PNG data.
4587
4588       png_image  is  a  structure  that  describes the in-memory format of an
4589       image when it is being read or defines the in-memory format of an image
4590       that you need to write.  The "png_image" structure contains the follow‐
4591       ing members:
4592
4593          png_controlp opaque  Initialize to NULL, free with png_image_free
4594          png_uint_32  version Set to PNG_IMAGE_VERSION
4595          png_uint_32  width   Image width in pixels (columns)
4596          png_uint_32  height  Image height in pixels (rows)
4597          png_uint_32  format  Image format as defined below
4598          png_uint_32  flags   A bit mask containing informational flags
4599          png_uint_32  colormap_entries; Number of entries in the color-map
4600          png_uint_32  warning_or_error;
4601          char         message[64];
4602
4603       In the event of an error or warning the "warning_or_error"  field  will
4604       be  set  to a non-zero value and the 'message' field will contain a ' '
4605       terminated string with the libpng error or warning  message.   If  both
4606       warnings and an error were encountered, only the error is recorded.  If
4607       there are multiple warnings, only the first one is recorded.
4608
4609       The upper 30 bits of the "warning_or_error" value are reserved; the low
4610       two bits contain a two bit code such that a value more than 1 indicates
4611       a failure in the API just called:
4612
4613          0 - no warning or error
4614          1 - warning
4615          2 - error
4616          3 - error preceded by warning
4617
4618       The pixels (samples) of the image have one to four channels whose  com‐
4619       ponents have original values in the range 0 to 1.0:
4620
4621         1: A single gray or luminance channel (G).
4622         2: A gray/luminance channel and an alpha channel (GA).
4623         3: Three red, green, blue color channels (RGB).
4624         4: Three color channels and an alpha channel (RGBA).
4625
4626       The channels are encoded in one of two ways:
4627
4628         a) As a small integer, value 0..255, contained in a single byte.  For
4629       the alpha channel the original value  is  simply  value/255.   For  the
4630       color  or luminance channels the value is encoded according to the sRGB
4631       specification and matches the 8-bit format expected by typical  display
4632       devices.
4633
4634       The  color/gray  channels  are not scaled (pre-multiplied) by the alpha
4635       channel and are suitable for passing to color management software.
4636
4637         b) As a value in the range 0..65535, contained in a  2-byte  integer,
4638       in  the  native  byte order of the platform on which the application is
4639       running.  All channels can be converted to the original value by divid‐
4640       ing  by  65535;  all  channels  are linear.  Color channels use the RGB
4641       encoding (RGB end-points) of the sRGB specification.  This encoding  is
4642       identified by the PNG_FORMAT_FLAG_LINEAR flag below.
4643
4644       When  the  simplified API needs to convert between sRGB and linear col‐
4645       orspaces, the actual sRGB transfer curve defined in the sRGB specifica‐
4646       tion  (see  the article at https://en.wikipedia.org/wiki/SRGB) is used,
4647       not the gamma=1/2.2 approximation used elsewhere in libpng.
4648
4649       When an alpha channel is present it is expected to denote pixel  cover‐
4650       age of the color or luminance channels and is returned as an associated
4651       alpha channel: the color/gray channels are scaled  (pre-multiplied)  by
4652       the alpha value.
4653
4654       The  samples are either contained directly in the image data, between 1
4655       and 8 bytes per pixel according to the  encoding,  or  are  held  in  a
4656       color-map  indexed by bytes in the image data.  In the case of a color-
4657       map the color-map entries are individual samples, encoded as above, and
4658       the  image  data  has  one byte per pixel to select the relevant sample
4659       from the color-map.
4660
4661       PNG_FORMAT_*
4662
4663       The #defines to be used in png_image::format.  Each #define  identifies
4664       a  particular  layout  of  channel  data and, if present, alpha values.
4665       There are separate defines for each of the two component encodings.
4666
4667       A format is built up using single bit flag  values.   All  combinations
4668       are valid.  Formats can be built up from the flag values or you can use
4669       one of the predefined values below.  When testing  formats  always  use
4670       the  FORMAT_FLAG  macros  to test for individual features - future ver‐
4671       sions of the library may add new flags.
4672
4673       When reading or writing color-mapped images the format should be set to
4674       the    format    of    the    entries    in    the    color-map    then
4675       png_image_{read,write}_colormap called to read or write  the  color-map
4676       and  set  the  format  correctly  for  the  image data.  Do not set the
4677       PNG_FORMAT_FLAG_COLORMAP bit directly!
4678
4679       NOTE: libpng can be built with particular features disabled. If you see
4680       compiler  errors  because  the definition of one of the following flags
4681       has been compiled out it is because libpng does not have  the  required
4682       support.   It  is  possible,  however,  for the libpng configuration to
4683       enable the format on just read or just write; in that case you may  see
4684       an  error  at run time.  You can guard against this by checking for the
4685       definition of the appropriate "_SUPPORTED" macro, one of:
4686
4687          PNG_SIMPLIFIED_{READ,WRITE}_{BGR,AFIRST}_SUPPORTED
4688
4689          PNG_FORMAT_FLAG_ALPHA    format with an alpha channel
4690          PNG_FORMAT_FLAG_COLOR    color format: otherwise grayscale
4691          PNG_FORMAT_FLAG_LINEAR   2-byte channels else 1-byte
4692          PNG_FORMAT_FLAG_COLORMAP image data is color-mapped
4693          PNG_FORMAT_FLAG_BGR      BGR colors, else order is RGB
4694          PNG_FORMAT_FLAG_AFIRST   alpha channel comes first
4695
4696       Supported formats are as follows.  Future versions of libpng  may  sup‐
4697       port  more  formats; for compatibility with older versions simply check
4698       if the format macro is defined using #ifdef.   These  defines  describe
4699       the in-memory layout of the components of the pixels of the image.
4700
4701       First the single byte (sRGB) formats:
4702
4703          PNG_FORMAT_GRAY
4704          PNG_FORMAT_GA
4705          PNG_FORMAT_AG
4706          PNG_FORMAT_RGB
4707          PNG_FORMAT_BGR
4708          PNG_FORMAT_RGBA
4709          PNG_FORMAT_ARGB
4710          PNG_FORMAT_BGRA
4711          PNG_FORMAT_ABGR
4712
4713       Then the linear 2-byte formats.  When naming these "Y" is used to indi‐
4714       cate a luminance (gray) channel.  The component order within the  pixel
4715       is  always  the  same - there is no provision for swapping the order of
4716       the components in the linear format.  The components are  16-bit  inte‐
4717       gers in the native byte order for your platform, and there is no provi‐
4718       sion for swapping the bytes to a different endian condition.
4719
4720          PNG_FORMAT_LINEAR_Y
4721          PNG_FORMAT_LINEAR_Y_ALPHA
4722          PNG_FORMAT_LINEAR_RGB
4723          PNG_FORMAT_LINEAR_RGB_ALPHA
4724
4725       With color-mapped formats the image data is one byte  for  each  pixel.
4726       The  byte  is  an index into the color-map which is formatted as above.
4727       To obtain a color-mapped format  it  is  sufficient  just  to  add  the
4728       PNG_FOMAT_FLAG_COLORMAP to one of the above definitions, or you can use
4729       one of the definitions below.
4730
4731          PNG_FORMAT_RGB_COLORMAP
4732          PNG_FORMAT_BGR_COLORMAP
4733          PNG_FORMAT_RGBA_COLORMAP
4734          PNG_FORMAT_ARGB_COLORMAP
4735          PNG_FORMAT_BGRA_COLORMAP
4736          PNG_FORMAT_ABGR_COLORMAP
4737
4738       PNG_IMAGE macros
4739
4740       These are convenience macros to derive  information  from  a  png_image
4741       structure.   The  PNG_IMAGE_SAMPLE_ macros return values appropriate to
4742       the actual image sample values - either the entries in the color-map or
4743       the  pixels  in  the  image.  The PNG_IMAGE_PIXEL_ macros return corre‐
4744       sponding values for the pixels and will  always  return  1  for  color-
4745       mapped formats.  The remaining macros return information about the rows
4746       in the image and the complete image.
4747
4748       NOTE: All the macros that take a png_image::format parameter  are  com‐
4749       pile  time  constants  if  the format parameter is, itself, a constant.
4750       Therefore these macros can be  used  in  array  declarations  and  case
4751       labels  where  required.   Similarly  the macros are also pre-processor
4752       constants (sizeof is not used) so they can be used in #if tests.
4753
4754         PNG_IMAGE_SAMPLE_CHANNELS(fmt)
4755           Returns the total number of channels in a given format: 1..4
4756
4757         PNG_IMAGE_SAMPLE_COMPONENT_SIZE(fmt)
4758           Returns the size in bytes of a  single  component  of  a  pixel  or
4759       color-map
4760           entry (as appropriate) in the image: 1 or 2.
4761
4762         PNG_IMAGE_SAMPLE_SIZE(fmt)
4763           This  is  the size of the sample data for one sample.  If the image
4764       is
4765           color-mapped it is the size of one color-map entry (and image  pix‐
4766       els are
4767           one byte in size), otherwise it is the size of one image pixel.
4768
4769         PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(fmt)
4770           The  maximum size of the color-map required by the format expressed
4771       in a
4772           count of components.  This can be used to compile-time allocate a
4773           color-map:
4774
4775           png_uint_16     colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(lin‐
4776       ear_fmt)];
4777
4778           png_byte colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(sRGB_fmt)];
4779
4780           Alternatively  use  the  PNG_IMAGE_COLORMAP_SIZE macro below to use
4781       the
4782           information from one of the png_image_begin_read_ APIs and  dynami‐
4783       cally
4784           allocate the required memory.
4785
4786         PNG_IMAGE_COLORMAP_SIZE(fmt)
4787          The  size  of the color-map required by the format; this is the size
4788       of the
4789          color-map buffer passed to the png_image_{read,write}_colormap APIs.
4790       It is
4791          a  fixed  number determined by the format so can easily be allocated
4792       on the
4793          stack if necessary.
4794
4795       Corresponding information about the pixels
4796
4797         PNG_IMAGE_PIXEL_CHANNELS(fmt)
4798          The number of separate channels (components) in a pixel; 1 for a
4799          color-mapped image.
4800
4801         PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)   The size,  in  bytes,  of  each
4802       component in a pixel; 1 for a color-mapped
4803          image.
4804
4805         PNG_IMAGE_PIXEL_SIZE(fmt)
4806          The size, in bytes, of a complete pixel; 1 for a color-mapped image.
4807
4808       Information about the whole row, or whole image
4809
4810         PNG_IMAGE_ROW_STRIDE(image)
4811          Returns the total number of components in a single row of the image;
4812       this
4813          is the minimum 'row stride', the minimum count of components between
4814       each
4815          row.   For  a color-mapped image this is the minimum number of bytes
4816       in a
4817          row.
4818
4819          If you need the stride measured in bytes, row_stride_bytes is
4820          PNG_IMAGE_ROW_STRIDE(image) * PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)
4821          plus any padding bytes that your application might need, for example
4822          to start the next row on a 4-byte boundary.
4823
4824         PNG_IMAGE_BUFFER_SIZE(image, row_stride)
4825          Return the size, in bytes, of an image buffer given a png_image  and
4826       a row
4827          stride - the number of components to leave space for in each row.
4828
4829         PNG_IMAGE_SIZE(image)
4830          Return  the  size,  in  bytes,  of  the image in memory given just a
4831       png_image;
4832          the row stride is the minimum stride required for the image.
4833
4834         PNG_IMAGE_COLORMAP_SIZE(image)
4835          Return the size, in bytes, of the color-map of this image.   If  the
4836       image
4837          format  is not a color-map format this will return a size sufficient
4838       for
4839          256 entries in the given format; check PNG_FORMAT_FLAG_COLORMAP if
4840          you don't want to allocate a color-map in this case.
4841
4842       PNG_IMAGE_FLAG_*
4843
4844       Flags containing additional information about the image are held in the
4845       'flags' field of png_image.
4846
4847         PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB == 0x01
4848           This indicates the the RGB values of the in-memory bitmap do not
4849           correspond to the red, green and blue end-points defined by sRGB.
4850
4851         PNG_IMAGE_FLAG_FAST == 0x02
4852          On  write  emphasise  speed over compression; the resultant PNG file
4853       will be
4854          larger but will be produced  significantly  faster,  particular  for
4855       large
4856          images.   Do  not  use this option for images which will be distrib‐
4857       uted, only
4858          used it when producing intermediate files that will be read back in
4859          repeatedly.  For a typical 24-bit image the option will  double  the
4860       read
4861          speed  at  the cost of increasing the image size by 25%, however for
4862       many
4863          more compressible images the PNG file can be 10  times  larger  with
4864       only a
4865          slight speed gain.
4866
4867         PNG_IMAGE_FLAG_16BIT_sRGB == 0x04
4868           On  read  if the image is a 16-bit per component image and there is
4869       no gAMA
4870           or sRGB chunk assume that the components are sRGB encoded.   Notice
4871       that
4872           images  output by the simplified API always have gamma information;
4873       setting
4874           this flag only affects the interpretation of 16-bit images from an
4875           external source.  It is recommended  that  the  application  expose
4876       this flag
4877           to  the user; the user can normally easily recognize the difference
4878       between
4879           linear and sRGB encoding.  This flag has no effect on write  -  the
4880       data
4881           passed to the write APIs must have the correct encoding (as defined
4882           above.)
4883
4884           If  the  flag  is  not set (the default) input 16-bit per component
4885       data is
4886           assumed to be linear.
4887
4888           NOTE: the flag can only  be  set  after  the  png_image_begin_read_
4889       call,
4890           because that call initializes the 'flags' field.
4891
4892       READ APIs
4893
4894          The  png_image passed to the read APIs must have been initialized by
4895       setting
4896          the png_controlp field 'opaque' to  NULL  (or,  better,  memset  the
4897       whole thing.)
4898
4899          int png_image_begin_read_from_file( png_imagep image,
4900            const char *file_name)
4901
4902            The named file is opened for read and the image header
4903            is filled in from the PNG header in the file.
4904
4905          int png_image_begin_read_from_stdio (png_imagep image,
4906            FILE* file)
4907
4908             The PNG header is read from the stdio FILE object.
4909
4910          int png_image_begin_read_from_memory(png_imagep image,
4911             png_const_voidp memory, png_size_t size)
4912
4913             The PNG header is read from the given memory buffer.
4914
4915          int png_image_finish_read(png_imagep image,
4916             png_colorp background, void *buffer,
4917             png_int_32 row_stride, void *colormap));
4918
4919             Finish reading the image into the supplied buffer and
4920             clean up the png_image structure.
4921
4922             row_stride is the step, in png_byte or png_uint_16 units
4923             as appropriate, between adjacent rows.  A positive stride
4924             indicates that the top-most row is first in the buffer -
4925             the normal top-down arrangement.  A negative stride
4926             indicates that the bottom-most row is first in the buffer.
4927
4928             background need only be supplied if an alpha channel must
4929             be removed from a png_byte format and the removal is to be
4930             done by compositing on a solid color; otherwise it may be
4931             NULL and any composition will be done directly onto the
4932             buffer.  The value is an sRGB color to use for the
4933             background, for grayscale output the green channel is used.
4934
4935             For linear output removing the alpha channel is always done
4936             by compositing on black.
4937
4938          void png_image_free(png_imagep image)
4939
4940             Free any data allocated by libpng in image->opaque,
4941             setting the pointer to NULL.  May be called at any time
4942             after the structure is initialized.
4943
4944       When  the  simplified API needs to convert between sRGB and linear col‐
4945       orspaces, the actual sRGB transfer curve defined in the sRGB specifica‐
4946       tion  (see  the article at https://en.wikipedia.org/wiki/SRGB) is used,
4947       not the gamma=1/2.2 approximation used elsewhere in libpng.
4948
4949       WRITE APIS
4950
4951       For write you must initialize a png_image  structure  to  describe  the
4952       image to be written:
4953
4954          version: must be set to PNG_IMAGE_VERSION
4955          opaque: must be initialized to NULL
4956          width: image width in pixels
4957          height: image height in rows
4958          format: the format of the data you wish to write
4959          flags: set to 0 unless one of the defined flags applies; set
4960             PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB for color format images
4961             where the RGB values do not correspond to the colors in sRGB.
4962          colormap_entries:  set  to the number of entries in the color-map (0
4963       to 256)
4964
4965          int png_image_write_to_file, (png_imagep image,
4966             const char *file, int convert_to_8bit, const void *buffer,
4967             png_int_32 row_stride, const void *colormap));
4968
4969             Write the image to the named file.
4970
4971          int png_image_write_to_memory (png_imagep image, void *memory,
4972             png_alloc_size_t * PNG_RESTRICT memory_bytes,
4973             int convert_to_8_bit, const void *buffer, ptrdiff_t row_stride,
4974             const void *colormap));
4975
4976             Write the image to memory.
4977
4978          int png_image_write_to_stdio(png_imagep image, FILE *file,
4979             int convert_to_8_bit, const void *buffer,
4980             png_int_32 row_stride, const void *colormap)
4981
4982             Write the image to the given (FILE*).
4983
4984       With all write APIs if image is in  one  of  the  linear  formats  with
4985       (png_uint_16)  data then setting convert_to_8_bit will cause the output
4986       to be a (png_byte) PNG gamma encoded according to the  sRGB  specifica‐
4987       tion, otherwise a 16-bit linear encoded PNG file is written.
4988
4989       With  all  APIs  row_stride  is handled as in the read APIs - it is the
4990       spacing from one row to the next in component sized units  (float)  and
4991       if  negative  indicates  a  bottom-up row layout in the buffer.  If you
4992       pass zero, libpng will calculate the row_stride for you from the  width
4993       and number of channels.
4994
4995       Note that the write API does not support interlacing, sub-8-bit pixels,
4996       indexed (paletted) images, or most ancillary chunks.
4997
4998

VI. Modifying/Customizing libpng

5000       There are two issues here.  The first is changing how libpng does stan‐
5001       dard  things  like memory allocation, input/output, and error handling.
5002       The second deals with more complicated things like adding  new  chunks,
5003       adding  new  transformations,  and generally changing how libpng works.
5004       Both of those are compile-time issues;  that  is,  they  are  generally
5005       determined  at the time the code is written, and there is rarely a need
5006       to provide the user with a means of changing them.
5007
5008       Memory allocation, input/output, and error handling
5009
5010       All of the memory  allocation,  input/output,  and  error  handling  in
5011       libpng goes through callbacks that are user-settable.  The default rou‐
5012       tines are in pngmem.c,  pngrio.c,  pngwio.c,  and  pngerror.c,  respec‐
5013       tively.  To change these functions, call the appropriate png_set_*_fn()
5014       function.
5015
5016       Memory allocation is done through the functions png_malloc(),  png_cal‐
5017       loc(),  and png_free().  The png_malloc() and png_free() functions cur‐
5018       rently just call  the  standard  C  functions  and  png_calloc()  calls
5019       png_malloc()  and  then clears the newly allocated memory to zero; note
5020       that png_calloc(png_ptr, size) is not the same  as  the  calloc(number,
5021       size) function provided by stdlib.h.  There is limited support for cer‐
5022       tain systems with segmented  memory  architectures  and  the  types  of
5023       pointers declared by png.h match this; you will have to use appropriate
5024       pointers in your application.  If you prefer to use a different  method
5025       of  allocating and freeing data, you can use png_create_read_struct_2()
5026       or  png_create_write_struct_2()  to  register  your  own  functions  as
5027       described  above.  These functions also provide a void pointer that can
5028       be retrieved via
5029
5030           mem_ptr=png_get_mem_ptr(png_ptr);
5031
5032       Your replacement memory functions must have prototypes as follows:
5033
5034           png_voidp malloc_fn(png_structp png_ptr,
5035              png_alloc_size_t size);
5036
5037           void free_fn(png_structp png_ptr, png_voidp ptr);
5038
5039       Your malloc_fn() must return NULL in case of failure.  The png_malloc()
5040       function  will normally call png_error() if it receives a NULL from the
5041       system memory allocator or from your replacement malloc_fn().
5042
5043       Your free_fn() will never be called with a  NULL  ptr,  since  libpng's
5044       png_free() checks for NULL before calling free_fn().
5045
5046       Input/Output  in  libpng  is  done  through png_read() and png_write(),
5047       which currently just call fread() and fwrite().  The FILE *  is  stored
5048       in  png_struct  and  is  initialized via png_init_io().  If you wish to
5049       change the method of I/O, the library supplies callbacks that  you  can
5050       set  through  the  function png_set_read_fn() and png_set_write_fn() at
5051       run time, instead of calling the png_init_io() function.   These  func‐
5052       tions  also  provide a void pointer that can be retrieved via the func‐
5053       tion png_get_io_ptr().  For example:
5054
5055           png_set_read_fn(png_structp read_ptr,
5056               voidp read_io_ptr, png_rw_ptr read_data_fn)
5057
5058           png_set_write_fn(png_structp write_ptr,
5059               voidp write_io_ptr, png_rw_ptr write_data_fn,
5060               png_flush_ptr output_flush_fn);
5061
5062           voidp read_io_ptr = png_get_io_ptr(read_ptr);
5063           voidp write_io_ptr = png_get_io_ptr(write_ptr);
5064
5065       The replacement I/O functions must have prototypes as follows:
5066
5067           void user_read_data(png_structp png_ptr,
5068               png_bytep data, png_size_t length);
5069
5070           void user_write_data(png_structp png_ptr,
5071               png_bytep data, png_size_t length);
5072
5073           void user_flush_data(png_structp png_ptr);
5074
5075       The user_read_data() function is responsible for detecting and handling
5076       end-of-data errors.
5077
5078       Supplying  NULL  for the read, write, or flush functions sets them back
5079       to using the default C stream functions, which  expect  the  io_ptr  to
5080       point  to  a standard *FILE structure.  It is probably a mistake to use
5081       NULL for one of write_data_fn and output_flush_fn but not both of them,
5082       unless you have built libpng with PNG_NO_WRITE_FLUSH defined.  It is an
5083       error to read from a write stream, and vice versa.
5084
5085       Error handling in libpng is done through png_error() and png_warning().
5086       Errors  handled through png_error() are fatal, meaning that png_error()
5087       should never return to its caller.   Currently,  this  is  handled  via
5088       setjmp()   and   longjmp()   (unless  you  have  compiled  libpng  with
5089       PNG_NO_SETJMP, in which case it is handled via  PNG_ABORT()),  but  you
5090       could  change this to do things like exit() if you should wish, as long
5091       as your function does not return.
5092
5093       On non-fatal errors, png_warning() is called to print  a  warning  mes‐
5094       sage,  and  then  control  returns  to  the  calling  code.  By default
5095       png_error() and png_warning() print a message on stderr  via  fprintf()
5096       unless  the library is compiled with PNG_NO_CONSOLE_IO defined (because
5097       you don't want the messages) or PNG_NO_STDIO defined (because fprintf()
5098       isn't  available).   If  you  wish  to change the behavior of the error
5099       functions, you will need to set up your own message  callbacks.   These
5100       functions are normally supplied at the time that the png_struct is cre‐
5101       ated.  It is also possible to redirect errors and warnings to your  own
5102       replacement  functions  after  png_create_*_struct() has been called by
5103       calling:
5104
5105           png_set_error_fn(png_structp png_ptr,
5106               png_voidp error_ptr, png_error_ptr error_fn,
5107               png_error_ptr warning_fn);
5108
5109       If NULL is supplied for either error_fn or warning_fn, then the  libpng
5110       default  function will be used, calling fprintf() and/or longjmp() if a
5111       problem is encountered.  The replacement error  functions  should  have
5112       parameters as follows:
5113
5114           void user_error_fn(png_structp png_ptr,
5115               png_const_charp error_msg);
5116
5117           void user_warning_fn(png_structp png_ptr,
5118               png_const_charp warning_msg);
5119
5120       Then,  within  your  user_error_fn or user_warning_fn, you can retrieve
5121       the error_ptr if you need it, by calling
5122
5123           png_voidp error_ptr = png_get_error_ptr(png_ptr);
5124
5125       The motivation behind using setjmp() and longjmp() is the C++ throw and
5126       catch  exception  handling methods.  This makes the code much easier to
5127       write, as there is no need to check every return code of every function
5128       call.   However, there are some uncertainties about the status of local
5129       variables after a longjmp, so the user may want  to  be  careful  about
5130       doing  anything after setjmp returns non-zero besides returning itself.
5131       Consult your compiler documentation for more details.  For an  alterna‐
5132       tive  approach,  you  may  wish  to  use  the  "cexcept"  facility (see
5133       https://cexcept.sourceforge.io/), which is  illustrated  in  pngvalid.c
5134       and in contrib/visupng.
5135
5136       Beginning  in  libpng-1.4.0,  the  png_set_benign_errors()  API  became
5137       available.  You can use this to handle certain errors (normally handled
5138       as errors) as warnings.
5139
5140           png_set_benign_errors (png_ptr, int allowed);
5141
5142           allowed: 0: treat png_benign_error() as an error.
5143                    1: treat png_benign_error() as a warning.
5144
5145       As  of libpng-1.6.0, the default condition is to treat benign errors as
5146       warnings while reading and as errors while writing.
5147
5148
5149   Custom chunks
5150       If you need to read or write custom chunks, you may need to get  deeper
5151       into  the  libpng code.  The library now has mechanisms for storing and
5152       writing chunks of unknown type; you can even declare callbacks for cus‐
5153       tom  chunks.   However, this may not be good enough if the library code
5154       itself needs to know about interactions between your chunk and existing
5155       `intrinsic' chunks.
5156
5157       If you need to write a new intrinsic chunk, first read the PNG specifi‐
5158       cation. Acquire a first level of understanding of how  it  works.   Pay
5159       particular  attention  to  the  sections that describe chunk names, and
5160       look at how other chunks were designed, so you can do things similarly.
5161       Second,  check  out  the sections of libpng that read and write chunks.
5162       Try to find a chunk that is similar to yours and use it as a  template.
5163       More  details can be found in the comments inside the code.  It is best
5164       to handle private or unknown chunks in a generic method,  via  callback
5165       functions,  instead  of  by  modifying libpng functions. This is illus‐
5166       trated in pngtest.c, which uses a callback function to handle a private
5167       "vpAg"  chunk  and  the  new  "sTER"  chunk,  which are both unknown to
5168       libpng.
5169
5170       If you wish to write your own transformation for the data, look through
5171       the  part of the code that does the transformations, and check out some
5172       of the simpler ones to get an idea of how they work.   Try  to  find  a
5173       similar  transformation  to the one you want to add and copy off of it.
5174       More details can be found in the comments inside the code itself.
5175
5176
5177   Configuring for gui/windowing platforms:
5178       You will need to write new error and warning functions that use the GUI
5179       interface,  as  described  previously, and set them to be the error and
5180       warning functions at the time that png_create_*_struct() is called,  in
5181       order to have them available during the structure initialization.  They
5182       can be changed later via png_set_error_fn().  On  some  compilers,  you
5183       may also have to change the memory allocators (png_malloc, etc.).
5184
5185
5186   Configuring zlib:
5187       There  are special functions to configure the compression.  Perhaps the
5188       most useful one changes the compression  level,  which  currently  uses
5189       input compression values in the range 0 - 9.  The library normally uses
5190       the default compression level (Z_DEFAULT_COMPRESSION = 6).  Tests  have
5191       shown  that  for  a large majority of images, compression values in the
5192       range 3-6 compress nearly as well as higher  levels,  and  do  so  much
5193       faster.   For  online  applications it may be desirable to have maximum
5194       speed (Z_BEST_SPEED = 1).  With versions of zlib after v0.99,  you  can
5195       also specify no compression (Z_NO_COMPRESSION = 0), but this would cre‐
5196       ate files larger than just storing the raw bitmap.  You can specify the
5197       compression level by calling:
5198
5199           #include zlib.h
5200           png_set_compression_level(png_ptr, level);
5201
5202       Another  useful  one is to reduce the memory level used by the library.
5203       The memory level defaults to 8, but it can be lowered if you are  short
5204       on  memory  (running DOS, for example, where you only have 640K).  Note
5205       that the memory level does have an effect on compression;  among  other
5206       things,  lower  levels  will  result in sections of incompressible data
5207       being emitted in smaller stored blocks, with a  correspondingly  larger
5208       relative overhead of up to 15% in the worst case.
5209
5210           #include zlib.h
5211           png_set_compression_mem_level(png_ptr, level);
5212
5213       The other functions are for configuring zlib.  They are not recommended
5214       for normal use and may result in writing  an  invalid  PNG  file.   See
5215       zlib.h for more information on what these mean.
5216
5217           #include zlib.h
5218           png_set_compression_strategy(png_ptr,
5219               strategy);
5220
5221           png_set_compression_window_bits(png_ptr,
5222               window_bits);
5223
5224           png_set_compression_method(png_ptr, method);
5225
5226       This controls the size of the IDAT chunks (default 8192):
5227
5228           png_set_compression_buffer_size(png_ptr, size);
5229
5230       As  of  libpng  version  1.5.4, additional APIs became available to set
5231       these separately for non-IDAT compressed chunks such as zTXt, iTXt, and
5232       iCCP:
5233
5234           #include zlib.h
5235           #if PNG_LIBPNG_VER >= 10504
5236           png_set_text_compression_level(png_ptr, level);
5237
5238           png_set_text_compression_mem_level(png_ptr, level);
5239
5240           png_set_text_compression_strategy(png_ptr,
5241               strategy);
5242
5243           png_set_text_compression_window_bits(png_ptr,
5244               window_bits);
5245
5246           png_set_text_compression_method(png_ptr, method);
5247           #endif
5248
5249
5250   Controlling row filtering
5251       If you want to control whether libpng uses filtering or not, which fil‐
5252       ters are used, and how it goes about picking row filters, you can  call
5253       one of these functions.  The selection and configuration of row filters
5254       can have a significant impact on the size  and  encoding  speed  and  a
5255       somewhat lesser impact on the decoding speed of an image.  Filtering is
5256       enabled by default for RGB  and  grayscale  images  (with  and  without
5257       alpha),  but not for paletted images nor for any images with bit depths
5258       less than 8 bits/pixel.
5259
5260       The 'method' parameter sets the main filtering method,  which  is  cur‐
5261       rently  only '0' in the PNG 1.2 specification.  The 'filters' parameter
5262       sets which filter(s), if any, should be used for each scanline.  Possi‐
5263       ble  values are PNG_ALL_FILTERS, PNG_NO_FILTERS, or PNG_FAST_FILTERS to
5264       turn filtering on and off, or to turn on just the fast-decoding  subset
5265       of filters, respectively.
5266
5267       Individual  filter  types are PNG_FILTER_NONE, PNG_FILTER_SUB, PNG_FIL‐
5268       TER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which  can  be  bitwise  ORed
5269       together with '|' to specify one or more filters to use.  These filters
5270       are described in more detail in the PNG specification.  If  you  intend
5271       to  change  the filter type during the course of writing the image, you
5272       should start with flags set for all of the filters you intend to use so
5273       that  libpng  can  initialize its internal structures appropriately for
5274       all of the filter types.  (Note that this  means  the  first  row  must
5275       always  be adaptively filtered, because libpng currently does not allo‐
5276       cate the filter buffers until png_write_row() is called for  the  first
5277       time.)
5278
5279           filters = PNG_NO_FILTERS;
5280           filters = PNG_ALL_FILTERS;
5281           filters = PNG_FAST_FILTERS;
5282
5283           or
5284
5285           filters = PNG_FILTER_NONE | PNG_FILTER_SUB |
5286                     PNG_FILTER_UP | PNG_FILTER_AVG |
5287                     PNG_FILTER_PAETH;
5288
5289           png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
5290              filters);
5291
5292                     The second parameter can also be
5293                     PNG_INTRAPIXEL_DIFFERENCING if you are
5294                     writing a PNG to be embedded in a MNG
5295                     datastream.  This parameter must be the
5296                     same as the value of filter_method used
5297                     in png_set_IHDR().
5298
5299
5300   Requesting debug printout
5301       The  macro definition PNG_DEBUG can be used to request debugging print‐
5302       out.  Set it to an integer value in the range 0 to 3.   Higher  numbers
5303       result in increasing amounts of debugging information.  The information
5304       is printed to the "stderr" file, unless another file name is  specified
5305       in the PNG_DEBUG_FILE macro definition.
5306
5307       When PNG_DEBUG > 0, the following functions (macros) become available:
5308
5309          png_debug(level, message)
5310          png_debug1(level, message, p1)
5311          png_debug2(level, message, p1, p2)
5312
5313       in  which  "level"  is compared to PNG_DEBUG to decide whether to print
5314       the message, "message" is the formatted string to be  printed,  and  p1
5315       and  p2  are parameters that are to be embedded in the string according
5316       to printf-style formatting directives.  For example,
5317
5318          png_debug1(2, "foo=%d", foo);
5319
5320       is expanded to
5321
5322          if (PNG_DEBUG > 2)
5323             fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
5324
5325       When PNG_DEBUG is defined but is zero, the macros aren't  defined,  but
5326       you can still use PNG_DEBUG to control your own debugging:
5327
5328          #ifdef PNG_DEBUG
5329              fprintf(stderr, ...
5330          #endif
5331
5332       When  PNG_DEBUG  = 1, the macros are defined, but only png_debug state‐
5333       ments having level = 0 will be printed.  There aren't any  such  state‐
5334       ments  in  this  version of libpng, but if you insert some they will be
5335       printed.
5336
5337

VII. MNG support

5339       The  MNG  specification  (available  at  http://www.libpng.org/pub/mng)
5340       allows  certain  extensions  to PNG for PNG images that are embedded in
5341       MNG datastreams.  Libpng can support  some  of  these  extensions.   To
5342       enable them, use the png_permit_mng_features() function:
5343
5344          feature_set = png_permit_mng_features(png_ptr, mask)
5345
5346          mask is a png_uint_32 containing the bitwise OR of the
5347               features you want to enable.  These include
5348               PNG_FLAG_MNG_EMPTY_PLTE
5349               PNG_FLAG_MNG_FILTER_64
5350               PNG_ALL_MNG_FEATURES
5351
5352          feature_set is a png_uint_32 that is the bitwise AND of
5353             your mask with the set of MNG features that is
5354             supported by the version of libpng that you are using.
5355
5356       It  is  an  error to use this function when reading or writing a stand‐
5357       alone PNG file with the PNG 8-byte signature.  The PNG datastream  must
5358       be  wrapped  in  a  MNG datastream.  As a minimum, it must have the MNG
5359       8-byte signature and the MHDR and MEND chunks.  Libpng does not provide
5360       support  for  these or any other MNG chunks; your application must pro‐
5361       vide its own support for them.  You may wish to consider  using  libmng
5362       (available at https://www.libmng.com/) instead.
5363
5364

VIII. Changes to Libpng from version 0.88

5366       It should be noted that versions of libpng later than 0.96 are not dis‐
5367       tributed by the original libpng author, Guy Schalnat,  nor  by  Andreas
5368       Dilger,  who had taken over from Guy during 1996 and 1997, and distrib‐
5369       uted versions 0.89 through 0.96, but rather by another  member  of  the
5370       original  PNG  Group, Glenn Randers-Pehrson.  Guy and Andreas are still
5371       alive and well, but they have moved on to other things.
5372
5373       The   old   libpng   functions    png_read_init(),    png_write_init(),
5374       png_info_init(),  png_read_destroy(), and png_write_destroy() have been
5375       moved to PNG_INTERNAL in version 0.95 to discourage their  use.   These
5376       functions will be removed from libpng version 1.4.0.
5377
5378       The preferred method of creating and initializing the libpng structures
5379       is via  the  png_create_read_struct(),  png_create_write_struct(),  and
5380       png_create_info_struct()  because  they  isolate the size of the struc‐
5381       tures from the application, allow  version  error  checking,  and  also
5382       allow  the use of custom error handling routines during the initializa‐
5383       tion, which the old functions do not.  The functions png_read_destroy()
5384       and  png_write_destroy()  do  not  actually free the memory that libpng
5385       allocated for these structs, but just reset  the  data  structures,  so
5386       they   can   be   used   instead   of   png_destroy_read_struct()   and
5387       png_destroy_write_struct() if you feel there is too much  system  over‐
5388       head allocating and freeing the png_struct for each image read.
5389
5390       Setting   the   error   callbacks   via   png_set_message_fn()   before
5391       png_read_init() as was suggested in libpng-0.88 is no longer  supported
5392       because this caused applications that do not use custom error functions
5393       to fail if the png_ptr was not initialized to zero.  It is still possi‐
5394       ble to set the error callbacks AFTER png_read_init(), or to change them
5395       with png_set_error_fn(), which is essentially the  same  function,  but
5396       with  a new name to force compilation errors with applications that try
5397       to use the old method.
5398
5399       Support for the  sCAL,  iCCP,  iTXt,  and  sPLT  chunks  was  added  at
5400       libpng-1.0.6; however, iTXt support was not enabled by default.
5401
5402       Starting  with  version  1.0.7,  you  can find out which version of the
5403       library you are using at run-time:
5404
5405          png_uint_32 libpng_vn = png_access_version_number();
5406
5407       The number libpng_vn is constructed from the major version, minor  ver‐
5408       sion  with  leading  zero, and release number with leading zero, (e.g.,
5409       libpng_vn for version 1.0.7 is 10007).
5410
5411       Note that this function does not take a png_ptr, so  you  can  call  it
5412       before you've created one.
5413
5414       You  can also check which version of png.h you used when compiling your
5415       application:
5416
5417          png_uint_32 application_vn = PNG_LIBPNG_VER;
5418
5419

IX. Changes to Libpng from version 1.0.x to 1.2.x

5421       Support for user memory management was enabled by default.   To  accom‐
5422       plish   this,   the   functions   png_create_read_struct_2(),  png_cre‐
5423       ate_write_struct_2(),  png_set_mem_fn(),  png_get_mem_ptr(),   png_mal‐
5424       loc_default(), and png_free_default() were added.
5425
5426       Support  for  the  iTXt chunk has been enabled by default as of version
5427       1.2.41.
5428
5429       Support for certain MNG features was enabled.
5430
5431       Support for numbered error messages was added.  However, we  never  got
5432       around   to  actually  numbering  the  error  messages.   The  function
5433       png_set_strip_error_numbers() was added (Note: the prototype  for  this
5434       function  was inadvertently removed from png.h in PNG_NO_ASSEMBLER_CODE
5435       builds of libpng-1.2.15.  It was restored in libpng-1.2.36).
5436
5437       The png_malloc_warn() function was added at libpng-1.2.3.  This  issues
5438       a  png_warning  and  returns  NULL instead of aborting when it fails to
5439       acquire the requested memory allocation.
5440
5441       Support for setting user limits on image width and height  was  enabled
5442       by       default.        The      functions      png_set_user_limits(),
5443       png_get_user_width_max(), and png_get_user_height_max() were  added  at
5444       libpng-1.2.6.
5445
5446       The png_set_add_alpha() function was added at libpng-1.2.7.
5447
5448       The    function    png_set_expand_gray_1_2_4_to_8()    was   added   at
5449       libpng-1.2.9.  Unlike png_set_gray_1_2_4_to_8(), the new function  does
5450       not expand the tRNS chunk to alpha. The png_set_gray_1_2_4_to_8() func‐
5451       tion is deprecated.
5452
5453       A number of macro definitions in support of runtime selection of assem‐
5454       bler  code  features  (especially Intel MMX code support) were added at
5455       libpng-1.2.0:
5456
5457           PNG_ASM_FLAG_MMX_SUPPORT_COMPILED
5458           PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU
5459           PNG_ASM_FLAG_MMX_READ_COMBINE_ROW
5460           PNG_ASM_FLAG_MMX_READ_INTERLACE
5461           PNG_ASM_FLAG_MMX_READ_FILTER_SUB
5462           PNG_ASM_FLAG_MMX_READ_FILTER_UP
5463           PNG_ASM_FLAG_MMX_READ_FILTER_AVG
5464           PNG_ASM_FLAG_MMX_READ_FILTER_PAETH
5465           PNG_ASM_FLAGS_INITIALIZED
5466           PNG_MMX_READ_FLAGS
5467           PNG_MMX_FLAGS
5468           PNG_MMX_WRITE_FLAGS
5469           PNG_MMX_FLAGS
5470
5471       We added the following functions in support  of  runtime  selection  of
5472       assembler code features:
5473
5474           png_get_mmx_flagmask()
5475           png_set_mmx_thresholds()
5476           png_get_asm_flags()
5477           png_get_mmx_bitdepth_threshold()
5478           png_get_mmx_rowbytes_threshold()
5479           png_set_asm_flags()
5480
5481       We  replaced all of these functions with simple stubs in libpng-1.2.20,
5482       when the Intel assembler code was removed due to a licensing issue.
5483
5484       These macros are deprecated:
5485
5486           PNG_READ_TRANSFORMS_NOT_SUPPORTED
5487           PNG_PROGRESSIVE_READ_NOT_SUPPORTED
5488           PNG_NO_SEQUENTIAL_READ_SUPPORTED
5489           PNG_WRITE_TRANSFORMS_NOT_SUPPORTED
5490           PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED
5491           PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED
5492
5493       They have been replaced, respectively, by:
5494
5495           PNG_NO_READ_TRANSFORMS
5496           PNG_NO_PROGRESSIVE_READ
5497           PNG_NO_SEQUENTIAL_READ
5498           PNG_NO_WRITE_TRANSFORMS
5499           PNG_NO_READ_ANCILLARY_CHUNKS
5500           PNG_NO_WRITE_ANCILLARY_CHUNKS
5501
5502       PNG_MAX_UINT was replaced with PNG_UINT_31_MAX.  It has been deprecated
5503       since libpng-1.0.16 and libpng-1.2.6.
5504
5505       The function
5506           png_check_sig(sig, num) was replaced with
5507           !png_sig_cmp(sig, 0, num) It has been deprecated since libpng-0.90.
5508
5509       The function
5510           png_set_gray_1_2_4_to_8()  which  also  expands  tRNS  to alpha was
5511       replaced with
5512           png_set_expand_gray_1_2_4_to_8() which does not. It has been depre‐
5513       cated since libpng-1.0.18 and 1.2.9.
5514
5515

X. Changes to Libpng from version 1.0.x/1.2.x to 1.4.x

5517       Private  libpng  prototypes and macro definitions were moved from png.h
5518       and pngconf.h into a new pngpriv.h header file.
5519
5520       Functions     png_set_benign_errors(),     png_benign_error(),      and
5521       png_chunk_benign_error() were added.
5522
5523       Support  for  setting the maximum amount of memory that the application
5524       will allocate for reading chunks was added, as a security measure.  The
5525       functions  png_set_chunk_cache_max() and png_get_chunk_cache_max() were
5526       added to the library.
5527
5528       We implemented support for I/O states by adding png_ptr member io_state
5529       and   functions   png_get_io_chunk_name()   and  png_get_io_state()  in
5530       pngget.c
5531
5532       We added PNG_TRANSFORM_GRAY_TO_RGB to the  available  high-level  input
5533       transforms.
5534
5535       Checking  for  and  reporting of errors in the IHDR chunk is more thor‐
5536       ough.
5537
5538       Support for global arrays was removed, to improve thread safety.
5539
5540       Some obsolete/deprecated macros and functions have been removed.
5541
5542       Typecasted NULL definitions such as
5543          #define png_voidp_NULL            (png_voidp)NULL  were  eliminated.
5544       If you used these in your application, just use NULL instead.
5545
5546       The  png_struct and info_struct members "trans" and "trans_values" were
5547       changed to "trans_alpha" and "trans_color", respectively.
5548
5549       The obsolete, unused pnggccrd.c and pngvcrd.c files and  related  make‐
5550       files were removed.
5551
5552       The PNG_1_0_X and PNG_1_2_X macros were eliminated.
5553
5554       The PNG_LEGACY_SUPPORTED macro was eliminated.
5555
5556       Many WIN32_WCE #ifdefs were removed.
5557
5558       The    functions   png_read_init(info_ptr),   png_write_init(info_ptr),
5559       png_info_init(info_ptr),  png_read_destroy(),  and  png_write_destroy()
5560       have been removed.  They have been deprecated since libpng-0.95.
5561
5562       The  png_permit_empty_plte()  was removed. It has been deprecated since
5563       libpng-1.0.9.  Use png_permit_mng_features() instead.
5564
5565       We  removed  the  obsolete   stub   functions   png_get_mmx_flagmask(),
5566       png_set_mmx_thresholds(),     png_get_asm_flags(),     png_get_mmx_bit‐
5567       depth_threshold(),                    png_get_mmx_rowbytes_threshold(),
5568       png_set_asm_flags(), and png_mmx_supported()
5569
5570       We   removed  the  obsolete  png_check_sig(),  png_memcpy_check(),  and
5571       png_memset_check() functions.  Instead  use  !png_sig_cmp(),  memcpy(),
5572       and memset(), respectively.
5573
5574       The  function png_set_gray_1_2_4_to_8() was removed. It has been depre‐
5575       cated  since  libpng-1.0.18  and  1.2.9,  when  it  was  replaced  with
5576       png_set_expand_gray_1_2_4_to_8()   because  the  former  function  also
5577       expanded any tRNS chunk to an alpha channel.
5578
5579       Macros for png_get_uint_16, png_get_uint_32,  and  png_get_int_32  were
5580       added  and  are used by default instead of the corresponding functions.
5581       Unfortunately, from libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro
5582       (but   not   the   function)  incorrectly  returned  a  value  of  type
5583       png_uint_32.
5584
5585       We changed the prototype for png_malloc() from
5586           png_malloc(png_structp png_ptr, png_uint_32 size) to
5587           png_malloc(png_structp png_ptr, png_alloc_size_t size)
5588
5589       This also applies to  the  prototype  for  the  user  replacement  mal‐
5590       loc_fn().
5591
5592       The  png_calloc()  function  was  added  and  is  used  in  place of of
5593       "png_malloc(); memset();" except in the case  in  png_read_png()  where
5594       the array consists of pointers; in this case a "for" loop is used after
5595       the png_malloc() to set the pointers to NULL, to give robust.  behavior
5596       in  case  the  application  runs  out  of  memory  part-way through the
5597       process.
5598
5599       We changed  the  prototypes  of  png_get_compression_buffer_size()  and
5600       png_set_compression_buffer_size()  to  work  with png_size_t instead of
5601       png_uint_32.
5602
5603       Support for numbered error messages was removed by  default,  since  we
5604       never got around to actually numbering the error messages. The function
5605       png_set_strip_error_numbers() was removed from the library by default.
5606
5607       The png_zalloc() and png_zfree() functions are no longer exported.  The
5608       png_zalloc()  function  no  longer  zeroes out the memory that it allo‐
5609       cates.  Applications that called png_zalloc(png_ptr, number, size)  can
5610       call  png_calloc(png_ptr, number*size) instead, and can call png_free()
5611       instead of png_zfree().
5612
5613       Support for dithering was disabled by default in libpng-1.4.0,  because
5614       it  has  not  been well tested and doesn't actually "dither".  The code
5615       was not removed, however, and could be enabled by building libpng  with
5616       PNG_READ_DITHER_SUPPORTED  defined.   In libpng-1.4.2, this support was
5617       re-enabled, but the function was renamed png_set_quantize() to  reflect
5618       more  accurately  what  it  actually  does.   At  the  same  time,  the
5619       PNG_DITHER_[RED,GREEN_BLUE]_BITS macros were also renamed to  PNG_QUAN‐
5620       TIZE_[RED,GREEN,BLUE]_BITS,  and  PNG_READ_DITHER_SUPPORTED was renamed
5621       to PNG_READ_QUANTIZE_SUPPORTED.
5622
5623       We removed the trailing '.' from the warning and error messages.
5624
5625

XI. Changes to Libpng from version 1.4.x to 1.5.x

5627       From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but  not  the
5628       function) incorrectly returned a value of type png_uint_32.  The incor‐
5629       rect macro was removed from libpng-1.4.5.
5630
5631       Checking for invalid palette index on write was added at libpng 1.5.10.
5632       If  a  pixel  contains  an invalid (out-of-range) index libpng issues a
5633       benign error.  This is enabled by default because this condition is  an
5634       error  according to the PNG specification, Clause 11.3.2, but the error
5635       can be ignored in each png_ptr with
5636
5637          png_set_check_for_invalid_index(png_ptr, allowed);
5638
5639             allowed  - one of
5640                        0: disable benign error (accept the
5641                           invalid data without warning).
5642                        1: enable benign error (treat the
5643                           invalid data as an error or a
5644                           warning).
5645
5646       If the error is ignored, or if png_benign_error() treats it as a  warn‐
5647       ing,  any invalid pixels are decoded as opaque black by the decoder and
5648       written as-is by the encoder.
5649
5650       Retrieving the maximum palette index found was added at  libpng-1.5.15.
5651       This  statement  must  appear  after png_read_png() or png_read_image()
5652       while reading, and after  png_write_png()  or  png_write_image()  while
5653       writing.
5654
5655          int max_palette = png_get_palette_max(png_ptr, info_ptr);
5656
5657       This  will return the maximum palette index found in the image, or "-1"
5658       if the palette was not checked, or "0" if no palette was  found.   Note
5659       that  this  does  not  account  for any palette index used by ancillary
5660       chunks such as the bKGD chunk;  you  must  check  those  separately  to
5661       determine the maximum palette index actually used.
5662
5663       There  are  no substantial API changes between the non-deprecated parts
5664       of the 1.4.5 API and the 1.5.0 API; however, the  ability  to  directly
5665       access  members  of  the main libpng control structures, png_struct and
5666       png_info, deprecated in earlier versions of libpng, has been completely
5667       removed  from  libpng  1.5, and new private "pngstruct.h", "pnginfo.h",
5668       and "pngdebug.h" header files were created.
5669
5670       We no longer include zlib.h in png.h.  The include statement  has  been
5671       moved  to  pngstruct.h,  where  it  is  not accessible by applications.
5672       Applications that need access to information in zlib.h will need to add
5673       the  '#include "zlib.h"' directive.  It does not matter whether this is
5674       placed prior to or after the '"#include png.h"' directive.
5675
5676       The png_sprintf(), png_strcpy(), and png_strncpy() macros are no longer
5677       used and were removed.
5678
5679       We moved the png_strlen(), png_memcpy(), png_memset(), and png_memcmp()
5680       macros into a private header file (pngpriv.h) that is not accessible to
5681       applications.
5682
5683       In  png_get_iCCP,  the type of "profile" was changed from png_charpp to
5684       png_bytepp, and in png_set_iCCP, from png_charp to png_const_bytep.
5685
5686       There are changes of form in png.h, including new and changed macros to
5687       declare  parts  of the API.  Some API functions with arguments that are
5688       pointers to data not modified within the function have  been  corrected
5689       to declare these arguments with PNG_CONST.
5690
5691       Much  of  the internal use of C macros to control the library build has
5692       also changed and some of this is visible in the exported header  files,
5693       in  particular the use of macros to control data and API elements visi‐
5694       ble during application compilation may require significant revision  to
5695       application  code.   (It  is  extremely  rare  for an application to do
5696       this.)
5697
5698       Any program that compiled against libpng 1.4 and did not use deprecated
5699       features  or access internal library structures should compile and work
5700       against libpng  1.5,  except  for  the  change  in  the  prototype  for
5701       png_get_iCCP() and png_set_iCCP() API functions mentioned above.
5702
5703       libpng  1.5.0  adds PNG_ PASS macros to help in the reading and writing
5704       of interlaced images.  The macros return the number of rows and columns
5705       in  each  pass and information that can be used to de-interlace and (if
5706       absolutely necessary) interlace an image.
5707
5708       libpng 1.5.0 adds an API png_longjmp(png_ptr, value).  This  API  calls
5709       the  application-provided png_longjmp_ptr on the internal, but applica‐
5710       tion initialized, longjmp buffer.  It is provided as a  convenience  to
5711       avoid  the  need to use the png_jmpbuf macro, which had the unnecessary
5712       side effect of resetting the internal png_longjmp_ptr value.
5713
5714       libpng 1.5.0 includes a complete fixed point API.  By default  this  is
5715       present  along  with  the corresponding floating point API.  In general
5716       the fixed point API is faster and smaller than the floating  point  one
5717       because the PNG file format used fixed point, not floating point.  This
5718       applies even if the library uses floating point  in  internal  calcula‐
5719       tions.  A new macro, PNG_FLOATING_ARITHMETIC_SUPPORTED, reveals whether
5720       the library uses floating point arithmetic (the default) or fixed point
5721       arithmetic  internally  for  performance  critical calculations such as
5722       gamma correction.  In some cases, the gamma  calculations  may  produce
5723       slightly   different   results.    This  has  changed  the  results  in
5724       png_rgb_to_gray and in alpha composition (png_set_background for  exam‐
5725       ple). This applies even if the original image was already linear (gamma
5726       == 1.0) and, therefore, it is not necessary  to  linearize  the  image.
5727       This  is  because  libpng  has *not* been changed to optimize that case
5728       correctly, yet.
5729
5730       Fixed point support for the sCAL chunk comes with an important  caveat;
5731       the sCAL specification uses a decimal encoding of floating point values
5732       and the accuracy of PNG fixed point values is insufficient  for  repre‐
5733       sentation  of these values. Consequently a "string" API (png_get_sCAL_s
5734       and png_set_sCAL_s) is the only reliable way of reading arbitrary  sCAL
5735       chunks  in  the  absence  of  either the floating point API or internal
5736       floating point calculations.  Starting with libpng-1.5.0, both of these
5737       functions  are  present  when  PNG_sCAL_SUPPORTED is defined.  Prior to
5738       libpng-1.5.0, their presence also  depended  upon  PNG_FIXED_POINT_SUP‐
5739       PORTED   being   defined  and  PNG_FLOATING_POINT_SUPPORTED  not  being
5740       defined.
5741
5742       Applications no longer need to include the optional distribution header
5743       file  pngusr.h  or  define  the corresponding macros during application
5744       build in order to see the correct variant  of  the  libpng  API.   From
5745       1.5.0  application  code  can  check  for  the corresponding _SUPPORTED
5746       macro:
5747
5748       #ifdef PNG_INCH_CONVERSIONS_SUPPORTED
5749          /* code that uses the inch conversion APIs. */ #endif
5750
5751       This macro will only be defined if the inch conversion  functions  have
5752       been  compiled into libpng.  The full set of macros, and whether or not
5753       support has been compiled in, are available in the header file  pnglib‐
5754       conf.h.  This header file is specific to the libpng build.  Notice that
5755       prior to 1.5.0 the _SUPPORTED macros would always have the default def‐
5756       inition  unless  reset  by pngusr.h or by explicit settings on the com‐
5757       piler command line.  These settings may produce  compiler  warnings  or
5758       errors in 1.5.0 because of macro redefinition.
5759
5760       Applications  can now choose whether to use these macros or to call the
5761       corresponding   function    by    defining    PNG_USE_READ_MACROS    or
5762       PNG_NO_USE_READ_MACROS  before  including  png.h.   Notice that this is
5763       only supported from 1.5.0;  defining  PNG_NO_USE_READ_MACROS  prior  to
5764       1.5.0 will lead to a link failure.
5765
5766       Prior to libpng-1.5.4, the zlib compressor used the same set of parame‐
5767       ters when compressing the IDAT data and textual data such as  zTXt  and
5768       iCCP.   In  libpng-1.5.4 we reinitialized the zlib stream for each type
5769       of data.  We added five  png_set_text_*()  functions  for  setting  the
5770       parameters to use with textual data.
5771
5772       Prior  to  libpng-1.5.4,  the PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
5773       option was off by default, and slightly  inaccurate  scaling  occurred.
5774       This  option can no longer be turned off, and the choice of accurate or
5775       inaccurate 16-to-8 scaling is by using the new  png_set_scale_16_to_8()
5776       API  for  accurate  scaling  or the old png_set_strip_16_to_8() API for
5777       simple   chopping.    In   libpng-1.5.4,   the   PNG_READ_16_TO_8_ACCU‐
5778       RATE_SCALE_SUPPORTED macro became PNG_READ_SCALE_16_TO_8_SUPPORTED, and
5779       the PNG_READ_16_TO_8 macro became PNG_READ_STRIP_16_TO_8_SUPPORTED,  to
5780       enable the two png_set_*_16_to_8() functions separately.
5781
5782       Prior to libpng-1.5.4, the png_set_user_limits() function could only be
5783       used  to  reduce  the  width  and  height  limits  from  the  value  of
5784       PNG_USER_WIDTH_MAX and PNG_USER_HEIGHT_MAX, although this document said
5785       that it could be used to override them.  Now this function will  reduce
5786       or increase the limits.
5787
5788       Starting  in libpng-1.5.22, default user limits were established. These
5789       can  be  overridden  by  application  calls  to  png_set_user_limits(),
5790       png_set_user_chunk_cache_max(),  and/or png_set_user_malloc_max().  The
5791       limits are now
5792                                    max possible  default
5793          png_user_width_max        0x7fffffff    1,000,000
5794          png_user_height_max       0x7fffffff    1,000,000
5795          png_user_chunk_cache_max  0 (unlimited) 1000
5796          png_user_chunk_malloc_max 0 (unlimited) 8,000,000
5797
5798       The png_set_option() function (and the  "options"  member  of  the  png
5799       struct) was added to libpng-1.5.15, with option PNG_ARM_NEON.
5800
5801       The  library now supports a complete fixed point implementation and can
5802       thus be used on systems that have no floating  point  support  or  very
5803       limited  or  slow  support.   Previously gamma correction, an essential
5804       part of complete PNG support, required reasonably fast floating point.
5805
5806       As part of this the choice of internal  implementation  has  been  made
5807       independent  of  the choice of fixed versus floating point APIs and all
5808       the missing fixed point APIs have been implemented.
5809
5810       The exact mechanism used to control attributes  of  API  functions  has
5811       changed, as described in the INSTALL file.
5812
5813       A new test program, pngvalid, is provided in addition to pngtest.  png‐
5814       valid validates the arithmetic accuracy of the gamma correction  calcu‐
5815       lations  and  includes  a  number of validations of the file format.  A
5816       subset of the full range of tests is run when "make check" is done  (in
5817       the  'configure'  build.)   pngvalid also allows total allocated memory
5818       usage to be evaluated and performs additional memory overwrite  valida‐
5819       tion.
5820
5821       Many changes to individual feature macros have been made. The following
5822       are the changes most likely to be noticed by library builders who  con‐
5823       figure libpng:
5824
5825       1) All feature macros now have consistent naming:
5826
5827       #define  PNG_NO_feature  turns the feature off #define PNG_feature_SUP‐
5828       PORTED turns the feature on
5829
5830       pnglibconf.h contains one line for each feature macro which is either:
5831
5832       #define PNG_feature_SUPPORTED
5833
5834       if the feature is supported or:
5835
5836       /*#undef PNG_feature_SUPPORTED*/
5837
5838       if it is not.  Library code consistently  checks  for  the  'SUPPORTED'
5839       macro.   It does not, and libpng applications should not, check for the
5840       'NO' macro which will not normally be defined even if  the  feature  is
5841       not supported.  The 'NO' macros are only used internally for setting or
5842       not setting the corresponding 'SUPPORTED' macros.
5843
5844       Compatibility with the old names is provided as follows:
5845
5846       PNG_INCH_CONVERSIONS turns on PNG_INCH_CONVERSIONS_SUPPORTED
5847
5848       And the following definitions disable the corresponding feature:
5849
5850       PNG_SETJMP_NOT_SUPPORTED disables  SETJMP  PNG_READ_TRANSFORMS_NOT_SUP‐
5851       PORTED  disables  READ_TRANSFORMS PNG_NO_READ_COMPOSITED_NODIV disables
5852       READ_COMPOSITE_NODIV    PNG_WRITE_TRANSFORMS_NOT_SUPPORTED     disables
5853       WRITE_TRANSFORMS    PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED    disables
5854       READ_ANCILLARY_CHUNKS PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED disables
5855       WRITE_ANCILLARY_CHUNKS
5856
5857       Library builders should remove use of the above, inconsistent, names.
5858
5859       2)  Warning  and error message formatting was previously conditional on
5860       the STDIO feature. The library has been changed to use  the  CONSOLE_IO
5861       feature  instead. This means that if CONSOLE_IO is disabled the library
5862       no longer  uses  the  printf(3)  functions,  even  though  the  default
5863       read/write implementations use (FILE) style stdio.h functions.
5864
5865       3) Three feature macros now control the fixed/floating point decisions:
5866
5867       PNG_FLOATING_POINT_SUPPORTED enables the floating point APIs
5868
5869       PNG_FIXED_POINT_SUPPORTED  enables  the  fixed  point APIs; however, in
5870       practice these are normally required internally anyway (because the PNG
5871       file format is fixed point), therefore in most cases PNG_NO_FIXED_POINT
5872       merely stops the function from being exported.
5873
5874       PNG_FLOATING_ARITHMETIC_SUPPORTED chooses between the internal floating
5875       point implementation or the fixed point one.  Typically the fixed point
5876       implementation is larger and slower than the floating point implementa‐
5877       tion  on  a  system  that  supports  floating point; however, it may be
5878       faster on a system which lacks floating point  hardware  and  therefore
5879       uses a software emulation.
5880
5881       4)  Added  PNG_{READ,WRITE}_INT_FUNCTIONS_SUPPORTED.   This  allows the
5882       functions to read and  write  ints  to  be  disabled  independently  of
5883       PNG_USE_READ_MACROS, which allows libpng to be built with the functions
5884       even though the default is to use the macros - this allows applications
5885       to  choose  at  app  buildtime whether or not to use macros (previously
5886       impossible because the functions weren't in the default build.)
5887
5888

XII. Changes to Libpng from version 1.5.x to 1.6.x

5890       A "simplified API" has been added (see documentation  in  png.h  and  a
5891       simple example in contrib/examples/pngtopng.c).  The new publicly visi‐
5892       ble API includes the following:
5893
5894          macros:
5895            PNG_FORMAT_*
5896            PNG_IMAGE_*
5897          structures:
5898            png_control
5899            png_image
5900          read functions
5901            png_image_begin_read_from_file()
5902            png_image_begin_read_from_stdio()
5903            png_image_begin_read_from_memory()
5904            png_image_finish_read()
5905            png_image_free()
5906          write functions
5907            png_image_write_to_file()
5908            png_image_write_to_memory()
5909            png_image_write_to_stdio()
5910
5911       Starting with libpng-1.6.0, you can  configure  libpng  to  prefix  all
5912       exported symbols, using the PNG_PREFIX macro.
5913
5914       We no longer include string.h in png.h.  The include statement has been
5915       moved to pngpriv.h, where it is not accessible by applications.  Appli‐
5916       cations  that  need  access  to  information  in  string.h  must add an
5917       '#include <string.h>' directive.  It does not matter  whether  this  is
5918       placed prior to or after the '#include "png.h"' directive.
5919
5920       The following API are now DEPRECATED:
5921          png_info_init_3()
5922          png_convert_to_rfc1123() which has been replaced
5923            with png_convert_to_rfc1123_buffer()
5924          png_malloc_default()
5925          png_free_default()
5926          png_reset_zstream()
5927
5928       The following have been removed:
5929          png_get_io_chunk_name(), which has been replaced
5930            with png_get_io_chunk_type().  The new
5931            function returns a 32-bit integer instead of
5932            a string.
5933          The png_sizeof(), png_strlen(), png_memcpy(), png_memcmp(), and
5934            png_memset() macros are no longer used in the libpng sources and
5935            have  been  removed.   These  had  already  been made invisible to
5936       applications
5937            (i.e.,  defined  in  the  private  pngpriv.h  header  file)  since
5938       libpng-1.5.0.
5939
5940       The signatures of many exported functions were changed, such that
5941          png_structp became png_structrp or png_const_structrp
5942          png_infop became png_inforp or png_const_inforp where "rp" indicates
5943       a "restricted pointer".
5944
5945       Dropped support for 16-bit platforms. The support for FAR/far types has
5946       been  eliminated  and  the  definition  of png_alloc_size_t is now con‐
5947       trolled by a flag so that 'small size_t' systems can select it if  nec‐
5948       essary.
5949
5950       Error  detection  in  some  chunks has improved; in particular the iCCP
5951       chunk reader now does pretty complete validation of the  basic  format.
5952       Some bad profiles that were previously accepted are now accepted with a
5953       warning or rejected, depending upon  the  png_set_benign_errors()  set‐
5954       ting,  in  particular  the  very old broken Microsoft/HP 3144-byte sRGB
5955       profile.  Starting with libpng-1.6.11, recognizing  and  checking  sRGB
5956       profiles can be avoided by means of
5957
5958           #if             defined(PNG_SKIP_sRGB_CHECK_PROFILE)             &&
5959       defined(PNG_SET_OPTION_SUPPORTED)
5960              png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE,
5961                  PNG_OPTION_ON);
5962           #endif
5963
5964       It's not a good idea to do this if you are using the "simplified  API",
5965       which needs to be able to recognize sRGB profiles conveyed via the iCCP
5966       chunk.
5967
5968       The PNG spec requirement that only grayscale  profiles  may  appear  in
5969       images  with color type 0 or 4 and that even if the image only contains
5970       gray pixels, only RGB profiles may appear in images with color type  2,
5971       3,  or  6,  is  now  enforced.   The sRGB chunk is allowed to appear in
5972       images with any color type and is interpreted by  libpng  to  convey  a
5973       one-tracer-curve  gray  profile  or a three-tracer-curve RGB profile as
5974       appropriate.
5975
5976       Libpng 1.5.x erroneously used /MD for Debug DLL builds; if you used the
5977       debug  builds  in your app and you changed your app to use /MD you will
5978       need to change it back to /MDd for libpng 1.6.x.
5979
5980       Prior to libpng-1.6.0 a warning would be issued if the iTXt chunk  con‐
5981       tained an empty language field or an empty translated keyword.  Both of
5982       these are allowed by the PNG specification, so these  warnings  are  no
5983       longer issued.
5984
5985       The  library  now  issues an error if the application attempts to set a
5986       transform after it calls png_read_update_info() or if  it  attempts  to
5987       call  both png_read_update_info() and png_start_read_image() or to call
5988       either of them more than once.
5989
5990       The default condition for benign_errors is now to treat  benign  errors
5991       as warnings while reading and as errors while writing.
5992
5993       The  library now issues a warning if both background processing and RGB
5994       to gray are used when gamma correction happens. As with  previous  ver‐
5995       sions of the library the results are numerically very incorrect in this
5996       case.
5997
5998       There are some minor arithmetic changes  in  some  transforms  such  as
5999       png_set_background(),  that  might  be  detected  by certain regression
6000       tests.
6001
6002       Unknown chunk handling has been improved internally,  without  any  API
6003       change.  This adds more correct option control of the unknown handling,
6004       corrects a pre-existing bug  where  the  per-chunk  'keep'  setting  is
6005       ignored,  and  makes  it possible to skip IDAT chunks in the sequential
6006       reader.
6007
6008       The  machine-generated  configure  files  are  no  longer  included  in
6009       branches libpng16 and later of the GIT repository.  They continue to be
6010       included in the tarball releases, however.
6011
6012       Libpng-1.6.0 through 1.6.2 used the CMF bytes at the beginning  of  the
6013       IDAT  stream  to set the size of the sliding window for reading instead
6014       of using the default 32-kbyte sliding window size.  It  was  discovered
6015       that  there  are  hundreds of PNG files in the wild that have incorrect
6016       CMF bytes that caused zlib to issue the "invalid distance too far back"
6017       error  and reject the file.  Libpng-1.6.3 and later calculate their own
6018       safe CMF from the image dimensions, provide a  way  to  revert  to  the
6019       libpng-1.5.x  behavior  (ignoring  the  CMF  bytes and using a 32-kbyte
6020       sliding window), by using
6021
6022           png_set_option(png_ptr, PNG_MAXIMUM_INFLATE_WINDOW,
6023               PNG_OPTION_ON);
6024
6025       and provide a tool (contrib/tools/pngfix)  for  rewriting  a  PNG  file
6026       while optimizing the CMF bytes in its IDAT chunk correctly.
6027
6028       Libpng-1.6.0  and  libpng-1.6.1 wrote uncompressed iTXt chunks with the
6029       wrong length, which resulted in PNG files that cannot  be  read  beyond
6030       the  bad  iTXt chunk.  This error was fixed in libpng-1.6.3, and a tool
6031       (called contrib/tools/png-fix-itxt) has been added to the  libpng  dis‐
6032       tribution.
6033
6034       Starting  with  libpng-1.6.17, the PNG_SAFE_LIMITS macro was eliminated
6035       and safe limits are used by default (users who need larger  limits  can
6036       still override them at compile time or run time, as described above).
6037
6038       The new limits are
6039                                       default   spec limit
6040          png_user_width_max         1,000,000  2,147,483,647
6041          png_user_height_max        1,000,000  2,147,483,647
6042          png_user_chunk_cache_max         128  unlimited
6043          png_user_chunk_malloc_max  8,000,000  unlimited
6044
6045       Starting with libpng-1.6.18, a PNG_RELEASE_BUILD macro was added, which
6046       allows library builders to control compilation for an installed  system
6047       (a  release  build).  It can be set for testing debug or beta builds to
6048       ensure that they will compile when the build type is switched to RC  or
6049       STABLE.  In essence this overrides the PNG_LIBPNG_BUILD_BASE_TYPE defi‐
6050       nition which is not directly user controllable.
6051
6052       Starting with libpng-1.6.19, attempting  to  set  an  over-length  PLTE
6053       chunk is an error. Previously this requirement of the PNG specification
6054       was not enforced, and the palette was always limited to 256 entries. An
6055       over-length PLTE chunk found in an input PNG is silently truncated.
6056
6057       Starting  with  libpng-1.6.31, the eXIf chunk is supported. Libpng does
6058       not attempt to decode the Exif profile; it simply returns a byte  array
6059       containing the profile to the calling application which must do its own
6060       decoding.
6061
6062

XIII. Detecting libpng

6064       The png_get_io_ptr() function has been present since  libpng-0.88,  has
6065       never changed, and is unaffected by conditional compilation macros.  It
6066       is the best choice for use in configure scripts for detecting the pres‐
6067       ence  of  any libpng version since 0.88.  In an autoconf "configure.in"
6068       you could use
6069
6070           AC_CHECK_LIB(png, png_get_io_ptr, ...
6071
6072

XV. Source code repository

6074       Since about February 2009, version 1.2.34, libpng has been under  "git"
6075       source  control.   The  git  repository  was  built  from  old  libpng-
6076       x.y.z.tar.gz files going back to version 0.70.  You can access the  git
6077       repository (read only) at
6078
6079           https://github.com/glennrp/libpng or
6080           https://git.code.sf.net/p/libpng/code.git
6081
6082       or you can browse it with a web browser at
6083
6084           https://github.com/glennrp/libpng or
6085           https://sourceforge.net/p/libpng/code/ci/libpng16/tree/
6086
6087       Patches  can be sent to glennrp at users.sourceforge.net or to png-mng-
6088       implement at lists.sourceforge.net or you can upload them to the libpng
6089       bug tracker at
6090
6091           https://libpng.sourceforge.io/
6092
6093       or as a "pull request" to
6094
6095           https://github.com/glennrp/libpng/pulls
6096
6097       We  also  accept  patches  built from the tar or zip distributions, and
6098       simple verbal discriptions of bug fixes, reported either to the Source‐
6099       Forge  bug  tracker,  to  the png-mng-implement at lists.sf.net mailing
6100       list, as github issues, or directly to glennrp.
6101
6102

XV. Coding style

6104       Our  coding   style   is   similar   to   the   "Allman"   style   (See
6105       https://en.wikipedia.org/wiki/Indent_style#Allman_style),   with  curly
6106       braces on separate lines:
6107
6108           if (condition)
6109           {
6110              action;
6111           }
6112
6113           else if (another condition)
6114           {
6115              another action;
6116           }
6117
6118       The braces can be omitted from simple one-line actions:
6119
6120           if (condition)
6121              return (0);
6122
6123       We use 3-space indentation, except for continued statements  which  are
6124       usually  indented the same as the first line of the statement plus four
6125       more spaces.
6126
6127       For macro definitions we use 2-space indentation,  always  leaving  the
6128       "#" in the first column.
6129
6130           #ifndef PNG_NO_FEATURE
6131           #  ifndef PNG_FEATURE_SUPPORTED
6132           #    define PNG_FEATURE_SUPPORTED
6133           #  endif
6134           #endif
6135
6136       Comments  appear  with  the leading "/*" at the same indentation as the
6137       statement that follows the comment:
6138
6139           /* Single-line comment */
6140           statement;
6141
6142           /* This is a multiple-line
6143            * comment.
6144            */
6145           statement;
6146
6147       Very short comments can be placed after the end  of  the  statement  to
6148       which they pertain:
6149
6150           statement;    /* comment */
6151
6152       We  don't use C++ style ("//") comments. We have, however, used them in
6153       the past in some now-abandoned MMX assembler code.
6154
6155       Functions and their curly braces are not indented, and  exported  func‐
6156       tions are marked with PNGAPI:
6157
6158        /* This is a public function that is visible to
6159         * application programmers. It does thus-and-so.
6160         */
6161        void PNGAPI
6162        png_exported_function(png_ptr, png_info, foo)
6163        {
6164           body;
6165        }
6166
6167       The  return type and decorations are placed on a separate line ahead of
6168       the function name, as illustrated above.
6169
6170       The prototypes for all exported functions appear in  png.h,  above  the
6171       comment that says
6172
6173           /* Maintainer: Put new public prototypes here ... */
6174
6175       We mark all non-exported functions with "/* PRIVATE */"":
6176
6177        void /* PRIVATE */
6178        png_non_exported_function(png_ptr, png_info, foo)
6179        {
6180           body;
6181        }
6182
6183       The prototypes for non-exported functions (except for those in pngtest)
6184       appear in pngpriv.h above the comment that says
6185
6186         /* Maintainer: Put new private prototypes here ^ */
6187
6188       To avoid polluting the global namespace,  the  names  of  all  exported
6189       functions  and  variables begin with "png_", and all publicly visible C
6190       preprocessor macros begin with "PNG".   We  request  that  applications
6191       that  use  libpng  *not*  begin any of their own symbols with either of
6192       these strings.
6193
6194       We put a space after the "sizeof" operator and  we  omit  the  optional
6195       parentheses around its argument when the argument is an expression, not
6196       a type name, and we always enclose the sizeof operator, with its  argu‐
6197       ment, in parentheses:
6198
6199         (sizeof (png_uint_32))
6200         (sizeof array)
6201
6202       Prior  to  libpng-1.6.0  we  used  a "png_sizeof()" macro, formatted as
6203       though it were a function.
6204
6205       Control keywords if, for, while, and switch are always  followed  by  a
6206       space  to  distinguish them from function calls, which have no trailing
6207       space.
6208
6209       We put a space after each comma  and  after  each  semicolon  in  "for"
6210       statements,  and  we put spaces before and after each C binary operator
6211       and after "for" or "while", and before  "?".   We  don't  put  a  space
6212       between  a  typecast  and  the expression being cast, nor do we put one
6213       between a function name and the left parenthesis that follows it:
6214
6215           for (i = 2; i > 0; --i)
6216              y[i] = a(x) + (int)b;
6217
6218       We prefer #ifdef and #ifndef to #if defined() and #if  !defined()  when
6219       there  is  only one macro being tested.  We always use parentheses with
6220       "defined".
6221
6222       We express integer constants that are used as bit masks in hex  format,
6223       with an even number of lower-case hex digits, and to make them unsigned
6224       (e.g., 0x00U, 0xffU, 0x0100U) and long if they are greater than  0x7fff
6225       (e.g., 0xffffUL).
6226
6227       We prefer to use underscores rather than camelCase in names, except for
6228       a few type names that we inherit from zlib.h.
6229
6230       We prefer "if (something != 0)" and "if  (something  ==  0)"  over  "if
6231       (something)"  and  if "(!something)", respectively, and for pointers we
6232       prefer "if (some_pointer != NULL)" or "if (some_pointer == NULL)".
6233
6234       We do not use the TAB character for indentation in the C sources.
6235
6236       Lines do not exceed 80 characters.
6237
6238       Other rules can be inferred by inspecting the libpng source.
6239
6240

XVI. Y2K Compliance in libpng

6242       Since the PNG Development group is an ad-hoc body,  we  can't  make  an
6243       official declaration.
6244
6245       This  is  your  unofficial  assurance that libpng from version 0.71 and
6246       upward through 1.6.34 are Y2K compliant.  It is my belief that  earlier
6247       versions were also Y2K compliant.
6248
6249       Libpng only has two year fields.  One is a 2-byte unsigned integer that
6250       will hold years up to 65535.  The other, which is deprecated, holds the
6251       date in text format, and will hold years up to 9999.
6252
6253       The integer is
6254           "png_uint_16 year" in png_time_struct.
6255
6256       The string is
6257           "char  time_buffer[29]"  in  png_struct.  This is no longer used in
6258       libpng-1.6.x and will be removed from libpng-1.7.0.
6259
6260       There are seven time-related functions:
6261
6262           png_convert_to_rfc_1123_buffer() in png.c
6263             (formerly png_convert_to_rfc_1152() in error, and
6264             also formerly png_convert_to_rfc_1123())
6265           png_convert_from_struct_tm() in pngwrite.c, called
6266             in pngwrite.c
6267           png_convert_from_time_t() in pngwrite.c
6268           png_get_tIME() in pngget.c
6269           png_handle_tIME() in pngrutil.c, called in pngread.c
6270           png_set_tIME() in pngset.c
6271           png_write_tIME() in pngwutil.c, called in pngwrite.c
6272
6273       All appear to handle dates properly in a Y2K environment.  The png_con‐
6274       vert_from_time_t() function calls gmtime() to convert from system clock
6275       time, which returns (year - 1900), which we  properly  convert  to  the
6276       full  4-digit  year.   There  is  a possibility that applications using
6277       libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
6278       function,  or  that  they  are  incorrectly passing only a 2-digit year
6279       instead of "year - 1900" into  the  png_convert_from_struct_tm()  func‐
6280       tion,  but this is not under our control.  The libpng documentation has
6281       always stated that it works with 4-digit years, and the APIs have  been
6282       documented as such.
6283
6284       The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
6285       integer to hold the year, and can hold years as large as 65535.
6286
6287       zlib, upon which libpng depends, is also Y2K compliant.  It contains no
6288       date-related code.
6289
6290
6291          Glenn Randers-Pehrson
6292          libpng maintainer
6293          PNG Development Group
6294
6295

NOTE

6297       Note about libpng version numbers:
6298
6299       Due to various miscommunications, unforeseen code incompatibilities and
6300       occasional factors outside the authors' control, version  numbering  on
6301       the  library  has  not always been consistent and straightforward.  The
6302       following table summarizes matters since version 0.89c, which  was  the
6303       first widely used release:
6304
6305        source             png.h  png.h  shared-lib
6306        version            string   int  version
6307        -------            ------  ----- ----------
6308        0.89c "1.0 beta 3"     0.89      89  1.0.89
6309        0.90  "1.0 beta 4"     0.90      90  0.90  [should have been 2.0.90]
6310        0.95  "1.0 beta 5"     0.95      95  0.95  [should have been 2.0.95]
6311        0.96  "1.0 beta 6"     0.96      96  0.96  [should have been 2.0.96]
6312        0.97b "1.00.97 beta 7" 1.00.97   97  1.0.1 [should have been 2.0.97]
6313        0.97c                  0.97      97  2.0.97
6314        0.98                   0.98      98  2.0.98
6315        0.99                   0.99      98  2.0.99
6316        0.99a-m                0.99      99  2.0.99
6317        1.00                   1.00     100  2.1.0 [100 should be 10000]
6318        1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]
6319        1.0.1       png.h string is   10001  2.1.0
6320        1.0.1a-e    identical to the  10002  from here on, the shared library
6321        1.0.2       source version)   10002  is 2.V where V is the source code
6322        1.0.2a-b                      10003  version, except as noted.
6323        1.0.3                         10003
6324        1.0.3a-d                      10004
6325        1.0.4                         10004
6326        1.0.4a-f                      10005
6327        1.0.5 (+ 2 patches)           10005
6328        1.0.5a-d                      10006
6329        1.0.5e-r                      10100 (not source compatible)
6330        1.0.5s-v                      10006 (not binary compatible)
6331        1.0.6 (+ 3 patches)           10006 (still binary incompatible)
6332        1.0.6d-f                      10007 (still binary incompatible)
6333        1.0.6g                        10007
6334        1.0.6h                        10007  10.6h (testing xy.z so-numbering)
6335        1.0.6i                        10007  10.6i
6336        1.0.6j                          10007    2.1.0.6j  (incompatible  with
6337       1.0.0)
6338        1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compati‐
6339       ble)
6340        1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compati‐
6341       ble)
6342        1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)
6343        1.0.7                    1    10007  (still compatible)
6344        ...
6345        1.0.19                  10    10019  10.so.0.19[.0]
6346        ...
6347        1.2.59                  13    10259  12.so.0.59[.0]
6348        ...
6349        1.5.30                  15    10530  15.so.15.30[.0]
6350        ...
6351        1.6.34                  16    10634  16.so.16.34[.0]
6352
6353       Henceforth the source version will match the shared-library  minor  and
6354       patch numbers; the shared-library major version number will be used for
6355       changes  in  backward  compatibility,   as   it   is   intended.    The
6356       PNG_PNGLIB_VER  macro, which is not used within libpng but is available
6357       for applications, is an unsigned integer of the form xyyzz  correspond‐
6358       ing  to the source version x.y.z (leading zeros in y and z).  Beta ver‐
6359       sions were given the previous public  release  number  plus  a  letter,
6360       until  version 1.0.6j; from then on they were given the upcoming public
6361       release number plus "betaNN" or "rcNN".
6362
6363

SEE ALSO

6365       libpngpf(3), png(5)
6366
6367       libpng:
6368
6369              https://libpng.sourceforge.io/  (follow  the  [DOWNLOAD]   link)
6370              http://www.libpng.org/pub/png
6371
6372
6373       zlib:
6374
6375              (generally) at the same location as libpng or at
6376              https://zlib.net/
6377
6378
6379       PNGspecification:RFC2083
6380
6381              (generally) at the same location as libpng or at
6382              https://www.ietf.org/rfc/rfc2083.txt
6383              or (as a W3C Recommendation) at
6384              https://www.w3.org/TR/REC-png.html
6385
6386
6387       In the case of any inconsistency between the PNG specification and this
6388       library, the specification takes precedence.
6389
6390

AUTHORS

6392       This man page: Glenn Randers-Pehrson <glennrp at users.sourceforge.net>
6393
6394       The contributing authors would like to thank all those who helped  with
6395       testing,  bug  fixes,  and  patience.  This wouldn't have been possible
6396       without all of you.
6397
6398       Thanks to Frank J. T. Wojcik for helping with the documentation.
6399
6400       Libpng version 1.6.34 - September 29, 2017: Initially created  in  1995
6401       by  Guy  Eric Schalnat, then of Group 42, Inc.  Currently maintained by
6402       Glenn Randers-Pehrson (glennrp at users.sourceforge.net).
6403
6404       Supported by the PNG development group
6405       png-mng-implement at lists.sf.net (subscription  required;  visit  png-
6406       mng-implement  at  lists.sourceforge.net  (subscription required; visit
6407       https://lists.sourceforge.net/lists/listinfo/png-mng-implement to  sub‐
6408       scribe).
6409
6410

NOTICES:

6412       This  copy  of the libpng notices is provided for your convenience.  In
6413       case of any discrepancy between this copy and the notices in  the  file
6414       png.h  that  is  included  in the libpng distribution, the latter shall
6415       prevail.
6416
6417       COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
6418
6419       If you modify libpng you may insert additional notices immediately fol‐
6420       lowing this sentence.
6421
6422       This code is released under the libpng license.
6423
6424       libpng  versions 1.0.7, July 1, 2000 through 1.6.34, September 29, 2017
6425       are Copyright (c) 2000-2002, 2004, 2006-2017 Glenn Randers-Pehrson, are
6426       derived  from  libpng-1.0.6,  and are distributed according to the same
6427       disclaimer and license as libpng-1.0.6 with the  following  individuals
6428       added to the list of Contributing Authors:
6429
6430          Simon-Pierre Cadieux
6431          Eric S. Raymond
6432          Mans Rullgard
6433          Cosmin Truta
6434          Gilles Vollant
6435          James Yu
6436          Mandar Sahastrabuddhe
6437          Google Inc.
6438          Vadim Barkov
6439
6440       and with the following additions to the disclaimer:
6441
6442          There is no warranty against interference with your enjoyment of the
6443          library or against infringement.  There is no warranty that our
6444          efforts or the library will fulfill any of your particular purposes
6445          or needs.  This library is provided with all faults, and the entire
6446          risk  of  satisfactory quality, performance, accuracy, and effort is
6447       with
6448          the user.
6449
6450       Some files in the  "contrib"  directory  and  some  configure-generated
6451       files  that are distributed with libpng have other copyright owners and
6452       are released under other open source licenses.
6453
6454       libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000,  are
6455       Copyright   (c)  1998-2000  Glenn  Randers-Pehrson,  are  derived  from
6456       libpng-0.96, and are distributed according to the same  disclaimer  and
6457       license  as  libpng-0.96,  with  the following individuals added to the
6458       list of Contributing Authors:
6459
6460          Tom Lane
6461          Glenn Randers-Pehrson
6462          Willem van Schaik
6463
6464       libpng versions 0.89, June 1996, through 0.96, May 1997, are  Copyright
6465       (c)  1996-1997  Andreas  Dilger,  are derived from libpng-0.88, and are
6466       distributed  according  to  the  same   disclaimer   and   license   as
6467       libpng-0.88,  with  the following individuals added to the list of Con‐
6468       tributing Authors:
6469
6470          John Bowler
6471          Kevin Bracey
6472          Sam Bushell
6473          Magnus Holmgren
6474          Greg Roelofs
6475          Tom Tanner
6476
6477       Some files in the "scripts" directory have other copyright  owners  but
6478       are released under this license.
6479
6480       libpng  versions  0.5,  May 1995, through 0.88, January 1996, are Copy‐
6481       right (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
6482
6483       For the purposes of this copyright and license, "Contributing  Authors"
6484       is defined as the following set of individuals:
6485
6486          Andreas Dilger
6487          Dave Martindale
6488          Guy Eric Schalnat
6489          Paul Schmidt
6490          Tim Wegner
6491
6492       The  PNG  Reference  Library  is  supplied  "AS  IS".  The Contributing
6493       Authors and Group  42,  Inc.  disclaim  all  warranties,  expressed  or
6494       implied, including, without limitation, the warranties of merchantabil‐
6495       ity and of fitness for any purpose.  The Contributing Authors and Group
6496       42,  Inc.   assume  no liability for direct, indirect, incidental, spe‐
6497       cial, exemplary, or consequential damages, which may  result  from  the
6498       use of the PNG Reference Library, even if advised of the possibility of
6499       such damage.
6500
6501       Permission is hereby granted to use, copy, modify, and distribute  this
6502       source  code, or portions hereof, for any purpose, without fee, subject
6503       to the following restrictions:
6504
6505         1. The origin of this source code must not be misrepresented.
6506
6507         2. Altered versions must be plainly marked as such and must not
6508            be misrepresented as being the original source.
6509
6510         3. This Copyright notice may not be removed or altered from any
6511            source or altered source distribution.
6512
6513       The Contributing Authors and Group 42, Inc. specifically permit,  with‐
6514       out  fee,  and  encourage the use of this source code as a component to
6515       supporting the PNG file format in commercial products.  If you use this
6516       source  code  in a product, acknowledgment is not required but would be
6517       appreciated.
6518
6519       END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
6520
6521       TRADEMARK:
6522
6523       The name "libpng" has not been registered by the Copyright owner  as  a
6524       trademark  in  any jurisdiction.  However, because libpng has been dis‐
6525       tributed and maintained world-wide, continually since 1995,  the  Copy‐
6526       right  owner  claims "common-law trademark protection" in any jurisdic‐
6527       tion where common-law trademark is recognized.
6528
6529       OSI CERTIFICATION:
6530
6531       Libpng is OSI Certified  Open  Source  Software.   OSI  Certified  Open
6532       Source  is  a certification mark of the Open Source Initiative. OSI has
6533       not addressed the additional disclaimers inserted at version 1.0.7.
6534
6535       EXPORT CONTROL:
6536
6537       The Copyright owner believes that  the  Export  Control  Classification
6538       Number  (ECCN)  for  libpng is EAR99, which means not subject to export
6539       controls or International Traffic in Arms Regulations (ITAR) because it
6540       is  open source, publicly available software, that does not contain any
6541       encryption software.  See the EAR, paragraphs 734.3(b)(3) and 734.7(b).
6542
6543       A "png_get_copyright" function is  available,  for  convenient  use  in
6544       "about" boxes and the like:
6545
6546          printf("%s", png_get_copyright(NULL));
6547
6548       Also,  the PNG logo (in PNG format, of course) is supplied in the files
6549       "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
6550
6551       Glenn Randers-Pehrson glennrp at  users.sourceforge.net  September  29,
6552       2017
6553
6554
6555
6556
6557
6558                              September 29, 2017                     LIBPNG(3)
Impressum