Initial revision
[rrdtool.git] / libraries / libpng-1.0.9 / libpng.txt
1 libpng.txt - A description on how to use and modify libpng
2
3  libpng version 1.0.9 - January 31, 2001
4  Updated and distributed by Glenn Randers-Pehrson
5  <randeg@alum.rpi.edu>
6  Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson
7  For conditions of distribution and use, see copyright
8  notice in png.h.
9
10  based on:
11
12  libpng 1.0 beta 6  version 0.96 May 28, 1997
13  Updated and distributed by Andreas Dilger
14  Copyright (c) 1996, 1997 Andreas Dilger
15
16  libpng 1.0 beta 2 - version 0.88  January 26, 1996
17  For conditions of distribution and use, see copyright
18  notice in png.h. Copyright (c) 1995, 1996 Guy Eric
19  Schalnat, Group 42, Inc.
20
21  Updated/rewritten per request in the libpng FAQ
22  Copyright (c) 1995, 1996 Frank J. T. Wojcik
23  December 18, 1995 & January 20, 1996
24
25 I. Introduction
26
27 This file describes how to use and modify the PNG reference library
28 (known as libpng) for your own use.  There are five sections to this
29 file: introduction, structures, reading, writing, and modification and
30 configuration notes for various special platforms.  In addition to this
31 file, example.c is a good starting point for using the library, as
32 it is heavily commented and should include everything most people
33 will need.  We assume that libpng is already installed; see the
34 INSTALL file for instructions on how to install libpng.
35
36 Libpng was written as a companion to the PNG specification, as a way
37 of reducing the amount of time and effort it takes to support the PNG
38 file format in application programs.
39
40 The PNG-1.2 specification is available at <http://www.libpng.org/pub/png>
41 and at <ftp://ftp.uu.net/graphics/png/documents/>.
42
43 The PNG-1.0 specification is available
44 as RFC 2083 <ftp://ftp.uu.net/graphics/png/documents/> and as a
45 W3C Recommendation <http://www.w3.org/TR/REC.png.html>. Some
46 additional chunks are described in the special-purpose public chunks
47 documents at <ftp://ftp.uu.net/graphics/png/documents/>.
48
49 Other information
50 about PNG, and the latest version of libpng, can be found at the PNG home
51 page, <http://www.libpng.org/pub/png/>
52 and at <ftp://ftp.uu.net/graphics/png/>.
53
54 Most users will not have to modify the library significantly; advanced
55 users may want to modify it more.  All attempts were made to make it as
56 complete as possible, while keeping the code easy to understand.
57 Currently, this library only supports C.  Support for other languages
58 is being considered.
59
60 Libpng has been designed to handle multiple sessions at one time,
61 to be easily modifiable, to be portable to the vast majority of
62 machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
63 to use.  The ultimate goal of libpng is to promote the acceptance of
64 the PNG file format in whatever way possible.  While there is still
65 work to be done (see the TODO file), libpng should cover the
66 majority of the needs of its users.
67
68 Libpng uses zlib for its compression and decompression of PNG files.
69 Further information about zlib, and the latest version of zlib, can
70 be found at the zlib home page, <http://www.info-zip.org/pub/infozip/zlib/>.
71 The zlib compression utility is a general purpose utility that is
72 useful for more than PNG files, and can be used without libpng.
73 See the documentation delivered with zlib for more details.
74 You can usually find the source files for the zlib utility wherever you
75 find the libpng source files.
76
77 Libpng is thread safe, provided the threads are using different
78 instances of the structures.  Each thread should have its own
79 png_struct and png_info instances, and thus its own image.
80 Libpng does not protect itself against two threads using the
81 same instance of a structure.
82
83
84 II. Structures
85
86 There are two main structures that are important to libpng, png_struct
87 and png_info.  The first, png_struct, is an internal structure that
88 will not, for the most part, be used by a user except as the first
89 variable passed to every libpng function call.
90
91 The png_info structure is designed to provide information about the
92 PNG file.  At one time, the fields of png_info were intended to be
93 directly accessible to the user.  However, this tended to cause problems
94 with applications using dynamically loaded libraries, and as a result
95 a set of interface functions for png_info (the png_get_*() and png_set_*()
96 functions) was developed.  The fields of png_info are still available for
97 older applications, but it is suggested that applications use the new
98 interfaces if at all possible.
99
100 Applications that do make direct access to the members of png_struct (except
101 for png_ptr->jmpbuf) must be recompiled whenever the library is updated,
102 and applications that make direct access to the members of png_info must
103 be recompiled if they were compiled or loaded with libpng version 1.0.6,
104 in which the members were in a different order.  In version 1.0.7, the
105 members of the png_info structure reverted to the old order, as they were
106 in versions 0.97c through 1.0.5.  Starting with version 2.0.0, both
107 structures are going to be hidden, and the contents of the structures will
108 only be accessible through the png_get/png_set functions.
109
110 The png.h header file is an invaluable reference for programming with libpng.
111 And while I'm on the topic, make sure you include the libpng header file:
112
113 #include <png.h>
114
115 III. Reading
116
117 We'll now walk you through the possible functions to call when reading
118 in a PNG file sequentially, briefly explaining the syntax and purpose
119 of each one.  See example.c and png.h for more detail.  While
120 progressive reading is covered in the next section, you will still
121 need some of the functions discussed in this section to read a PNG
122 file.
123
124 Setup
125
126 You will want to do the I/O initialization(*) before you get into libpng,
127 so if it doesn't work, you don't have much to undo.  Of course, you
128 will also want to insure that you are, in fact, dealing with a PNG
129 file.  Libpng provides a simple check to see if a file is a PNG file.
130 To use it, pass in the first 1 to 8 bytes of the file to the function
131 png_sig_cmp(), and it will return 0 if the bytes match the corresponding
132 bytes of the PNG signature, or nonzero otherwise.  Of course, the more bytes
133 you pass in, the greater the accuracy of the prediction.
134
135 If you are intending to keep the file pointer open for use in libpng,
136 you must ensure you don't read more than 8 bytes from the beginning
137 of the file, and you also have to make a call to png_set_sig_bytes_read()
138 with the number of bytes you read from the beginning.  Libpng will
139 then only check the bytes (if any) that your program didn't read.
140
141 (*): If you are not using the standard I/O functions, you will need
142 to replace them with custom functions.  See the discussion under
143 Customizing libpng.
144
145
146     FILE *fp = fopen(file_name, "rb");
147     if (!fp)
148     {
149         return (ERROR);
150     }
151     fread(header, 1, number, fp);
152     is_png = !png_sig_cmp(header, 0, number);
153     if (!is_png)
154     {
155         return (NOT_PNG);
156     }
157
158
159 Next, png_struct and png_info need to be allocated and initialized.  In
160 order to ensure that the size of these structures is correct even with a
161 dynamically linked libpng, there are functions to initialize and
162 allocate the structures.  We also pass the library version, optional
163 pointers to error handling functions, and a pointer to a data struct for
164 use by the error functions, if necessary (the pointer and functions can
165 be NULL if the default error handlers are to be used).  See the section
166 on Changes to Libpng below regarding the old initialization functions.
167 The structure allocation functions quietly return NULL if they fail to
168 create the structure, so your application should check for that.
169
170     png_structp png_ptr = png_create_read_struct
171        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
172         user_error_fn, user_warning_fn);
173     if (!png_ptr)
174         return (ERROR);
175
176     png_infop info_ptr = png_create_info_struct(png_ptr);
177     if (!info_ptr)
178     {
179         png_destroy_read_struct(&png_ptr,
180            (png_infopp)NULL, (png_infopp)NULL);
181         return (ERROR);
182     }
183
184     png_infop end_info = png_create_info_struct(png_ptr);
185     if (!end_info)
186     {
187         png_destroy_read_struct(&png_ptr, &info_ptr,
188           (png_infopp)NULL);
189         return (ERROR);
190     }
191
192 If you want to use your own memory allocation routines,
193 define PNG_USER_MEM_SUPPORTED and use
194 png_create_read_struct_2() instead of png_create_read_struct():
195
196     png_structp png_ptr = png_create_read_struct_2
197        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
198         user_error_fn, user_warning_fn, (png_voidp)
199         user_mem_ptr, user_malloc_fn, user_free_fn);
200
201 The error handling routines passed to png_create_read_struct()
202 and the memory alloc/free routines passed to png_create_struct_2()
203 are only necessary if you are not using the libpng supplied error
204 handling and memory alloc/free functions.
205
206 When libpng encounters an error, it expects to longjmp back
207 to your routine.  Therefore, you will need to call setjmp and pass
208 your png_jmpbuf(png_ptr).  If you read the file from different
209 routines, you will need to update the jmpbuf field every time you enter
210 a new routine that will call a png_*() function.
211
212 See your documentation of setjmp/longjmp for your compiler for more
213 information on setjmp/longjmp.  See the discussion on libpng error
214 handling in the Customizing Libpng section below for more information
215 on the libpng error handling.  If an error occurs, and libpng longjmp's
216 back to your setjmp, you will want to call png_destroy_read_struct() to
217 free any memory.
218
219     if (setjmp(png_jmpbuf(png_ptr)))
220     {
221         png_destroy_read_struct(&png_ptr, &info_ptr,
222            &end_info);
223         fclose(fp);
224         return (ERROR);
225     }
226
227 If you would rather avoid the complexity of setjmp/longjmp issues,
228 you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case
229 errors will result in a call to PNG_ABORT() which defaults to abort().
230
231 Now you need to set up the input code.  The default for libpng is to
232 use the C function fread().  If you use this, you will need to pass a
233 valid FILE * in the function png_init_io().  Be sure that the file is
234 opened in binary mode.  If you wish to handle reading data in another
235 way, you need not call the png_init_io() function, but you must then
236 implement the libpng I/O methods discussed in the Customizing Libpng
237 section below.
238
239     png_init_io(png_ptr, fp);
240
241 If you had previously opened the file and read any of the signature from
242 the beginning in order to see if this was a PNG file, you need to let
243 libpng know that there are some bytes missing from the start of the file.
244
245     png_set_sig_bytes(png_ptr, number);
246
247 Setting up callback code
248
249 You can set up a callback function to handle any unknown chunks in the
250 input stream. You must supply the function
251
252     read_chunk_callback(png_ptr ptr,
253          png_unknown_chunkp chunk);
254     {
255        /* The unknown chunk structure contains your
256           chunk data: */
257            png_byte name[5];
258            png_byte *data;
259            png_size_t size;
260        /* Note that libpng has already taken care of the
261           CRC handling */
262
263        /* put your code here.  Return one of the following: */
264
265        return (-n); /* chunk had an error */
266        return (0); /* did not recognize */
267        return (n); /* success */
268     }
269
270 (You can give your function another name that you like instead of
271 "read_chunk_callback")
272
273 To inform libpng about your function, use
274
275     png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr,
276         read_chunk_callback);
277
278 This names not only the callback function, but also a user pointer that
279 you can retrieve with
280
281     png_get_user_chunk_ptr(png_ptr);
282
283 At this point, you can set up a callback function that will be
284 called after each row has been read, which you can use to control
285 a progress meter or the like.  It's demonstrated in pngtest.c.
286 You must supply a function
287
288     void read_row_callback(png_ptr ptr, png_uint_32 row, int pass);
289     {
290       /* put your code here */
291     }
292
293 (You can give it another name that you like instead of "read_row_callback")
294
295 To inform libpng about your function, use
296
297     png_set_read_status_fn(png_ptr, read_row_callback);
298
299 Unknown-chunk handling
300
301 Now you get to set the way the library processes unknown chunks in the
302 input PNG stream. Both known and unknown chunks will be read.  Normal
303 behavior is that known chunks will be parsed into information in
304 various info_ptr members; unknown chunks will be discarded. To change
305 this, you can call:
306
307     png_set_keep_unknown_chunks(png_ptr, info_ptr, keep,
308         chunk_list, num_chunks);
309     keep       - 0: do not keep
310                  1: keep only if safe-to-copy
311                  2: keep even if unsafe-to-copy
312     chunk_list - list of chunks affected (a byte string,
313                  five bytes per chunk, NULL or '\0' if
314                  num_chunks is 0)
315     num_chunks - number of chunks affected; if 0, all
316                  unknown chunks are affected
317
318 Unknown chunks declared in this way will be saved as raw data onto a
319 list of png_unknown_chunk structures.  If a chunk that is normally
320 known to libpng is named in the list, it will be handled as unknown,
321 according to the "keep" directive.  If a chunk is named in successive
322 instances of png_set_keep_unknown_chunks(), the final instance will
323 take precedence.
324
325 The high-level read interface
326
327 At this point there are two ways to proceed; through the high-level
328 read interface, or through a sequence of low-level read operations.
329 You can use the high-level interface if (a) you are willing to read
330 the entire image into memory, and (b) the input transformations
331 you want to do are limited to the following set:
332
333     PNG_TRANSFORM_IDENTITY      No transformation
334     PNG_TRANSFORM_STRIP_16      Strip 16-bit samples to 8 bits
335     PNG_TRANSFORM_STRIP_ALPHA   Discard the alpha channel
336     PNG_TRANSFORM_PACKING       Expand 1, 2 and 4-bit samples to bytes
337     PNG_TRANSFORM_PACKSWAP      Change order of packed pixels to LSB first
338     PNG_TRANSFORM_EXPAND        Perform set_expand()
339     PNG_TRANSFORM_INVERT_MONO   Invert monochrome images
340     PNG_TRANSFORM_SHIFT         Normalize pixels to the sBIT depth
341     PNG_TRANSFORM_BGR           Flip RGB to BGR, RGBA to BGRA
342     PNG_TRANSFORM_SWAP_ALPHA    Flip RGBA to ARGB or GA to AG
343     PNG_TRANSFORM_INVERT_ALPHA  Change alpha from opacity to transparency
344     PNG_TRANSFORM_SWAP_ENDIAN   Byte-swap 16-bit samples
345
346 (This excludes setting a background color, doing gamma transformation,
347 dithering, and setting filler.)  If this is the case, simply do this:
348
349     png_read_png(png_ptr, info_ptr, png_transforms, NULL)
350
351 where png_transforms is an integer containing the logical OR of
352 some set of transformation flags.  This call is equivalent to png_read_info(),
353 followed the set of transformations indicated by the transform mask,
354 then png_read_image(), and finally png_read_end().
355
356 (The final parameter of this call is not yet used.  Someday it might point
357 to transformation parameters required by some future input transform.)
358
359 After you have called png_read_png(), you can retrieve the image data
360 with
361
362    row_pointers = png_get_rows(png_ptr, info_ptr);
363
364 where row_pointers is an array of pointers to the pixel data for each row:
365
366    png_bytep row_pointers[height];
367
368 If you know your image size and pixel size ahead of time, you can allocate
369 row_pointers prior to calling png_read_png() with
370
371    row_pointers = png_malloc(png_ptr, height*sizeof(png_bytep));
372    for (int i=0; i<height, i++)
373       row_pointers[i]=png_malloc(png_ptr, width*pixel_size);
374    png_set_rows(png_ptr, info_ptr, &row_pointers);
375
376 Alternatively you could allocate your image in one big block and define
377 row_pointers[i] to point into the proper places in your block.
378
379 If you use png_set_rows(), the application is responsible for freeing
380 row_pointers (and row_pointers[i], if they were separately allocated).
381
382 If you don't allocate row_pointers ahead of time, png_read_png() will
383 do it, and it'll be free'ed when you call png_destroy_*().
384
385 The low-level read interface
386
387 If you are going the low-level route, you are now ready to read all
388 the file information up to the actual image data.  You do this with a
389 call to png_read_info().
390
391     png_read_info(png_ptr, info_ptr);
392
393 This will process all chunks up to but not including the image data.
394
395 Querying the info structure
396
397 Functions are used to get the information from the info_ptr once it
398 has been read.  Note that these fields may not be completely filled
399 in until png_read_end() has read the chunk data following the image.
400
401     png_get_IHDR(png_ptr, info_ptr, &width, &height,
402        &bit_depth, &color_type, &interlace_type,
403        &compression_type, &filter_method);
404
405     width          - holds the width of the image
406                      in pixels (up to 2^31).
407     height         - holds the height of the image
408                      in pixels (up to 2^31).
409     bit_depth      - holds the bit depth of one of the
410                      image channels.  (valid values are
411                      1, 2, 4, 8, 16 and depend also on
412                      the color_type.  See also
413                      significant bits (sBIT) below).
414     color_type     - describes which color/alpha channels
415                          are present.
416                      PNG_COLOR_TYPE_GRAY
417                         (bit depths 1, 2, 4, 8, 16)
418                      PNG_COLOR_TYPE_GRAY_ALPHA
419                         (bit depths 8, 16)
420                      PNG_COLOR_TYPE_PALETTE
421                         (bit depths 1, 2, 4, 8)
422                      PNG_COLOR_TYPE_RGB
423                         (bit_depths 8, 16)
424                      PNG_COLOR_TYPE_RGB_ALPHA
425                         (bit_depths 8, 16)
426
427                      PNG_COLOR_MASK_PALETTE
428                      PNG_COLOR_MASK_COLOR
429                      PNG_COLOR_MASK_ALPHA
430
431     filter_method  - (must be PNG_FILTER_TYPE_BASE
432                      for PNG 1.0, and can also be
433                      PNG_INTRAPIXEL_DIFFERENCING if
434                      the PNG datastream is embedded in
435                      a MNG-1.0 datastream)
436     compression_type - (must be PNG_COMPRESSION_TYPE_BASE
437                      for PNG 1.0)
438     interlace_type - (PNG_INTERLACE_NONE or
439                      PNG_INTERLACE_ADAM7)
440     Any or all of interlace_type, compression_type, of
441                      filter_method can be NULL if you are
442                      not interested in their values.
443
444     channels = png_get_channels(png_ptr, info_ptr);
445     channels       - number of channels of info for the
446                      color type (valid values are 1 (GRAY,
447                      PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
448                      4 (RGB_ALPHA or RGB + filler byte))
449     rowbytes = png_get_rowbytes(png_ptr, info_ptr);
450     rowbytes       - number of bytes needed to hold a row
451
452     signature = png_get_signature(png_ptr, info_ptr);
453     signature      - holds the signature read from the
454                      file (if any).  The data is kept in
455                      the same offset it would be if the
456                      whole signature were read (i.e. if an
457                      application had already read in 4
458                      bytes of signature before starting
459                      libpng, the remaining 4 bytes would
460                      be in signature[4] through signature[7]
461                      (see png_set_sig_bytes())).
462
463
464     width            = png_get_image_width(png_ptr,
465                          info_ptr);
466     height           = png_get_image_height(png_ptr,
467                          info_ptr);
468     bit_depth        = png_get_bit_depth(png_ptr,
469                          info_ptr);
470     color_type       = png_get_color_type(png_ptr,
471                          info_ptr);
472     filter_method    = png_get_filter_type(png_ptr,
473                          info_ptr);
474     compression_type = png_get_compression_type(png_ptr,
475                          info_ptr);
476     interlace_type   = png_get_interlace_type(png_ptr,
477                          info_ptr);
478
479
480 These are also important, but their validity depends on whether the chunk
481 has been read.  The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
482 png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
483 data has been read, or zero if it is missing.  The parameters to the
484 png_get_<chunk> are set directly if they are simple data types, or a pointer
485 into the info_ptr is returned for any complex types.
486
487     png_get_PLTE(png_ptr, info_ptr, &palette,
488                      &num_palette);
489     palette        - the palette for the file
490                      (array of png_color)
491     num_palette    - number of entries in the palette
492
493     png_get_gAMA(png_ptr, info_ptr, &gamma);
494     gamma          - the gamma the file is written
495                      at (PNG_INFO_gAMA)
496
497     png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
498     srgb_intent    - the rendering intent (PNG_INFO_sRGB)
499                      The presence of the sRGB chunk
500                      means that the pixel data is in the
501                      sRGB color space.  This chunk also
502                      implies specific values of gAMA and
503                      cHRM.
504
505     png_get_iCCP(png_ptr, info_ptr, &name, &compression_type,
506                       &profile, &proflen);
507     name            - The profile name.
508     compression     - The compression type; always PNG_COMPRESSION_TYPE_BASE
509                       for PNG 1.0.  You may give NULL to this argument
510                       to ignore it.
511     profile         - International Color Consortium color profile
512                       data. May contain NULs.
513     proflen         - length of profile data in bytes.
514
515     png_get_sBIT(png_ptr, info_ptr, &sig_bit);
516     sig_bit        - the number of significant bits for
517                      (PNG_INFO_sBIT) each of the gray,
518                      red, green, and blue channels,
519                      whichever are appropriate for the
520                      given color type (png_color_16)
521
522     png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
523                      &trans_values);
524     trans          - array of transparent entries for
525                      palette (PNG_INFO_tRNS)
526     trans_values   - graylevel or color sample values of
527                      the single transparent color for
528                      non-paletted images (PNG_INFO_tRNS)
529     num_trans      - number of transparent entries
530                      (PNG_INFO_tRNS)
531
532     png_get_hIST(png_ptr, info_ptr, &hist);
533                      (PNG_INFO_hIST)
534     hist           - histogram of palette (array of
535                      png_uint_16)
536
537     png_get_tIME(png_ptr, info_ptr, &mod_time);
538     mod_time       - time image was last modified
539                     (PNG_VALID_tIME)
540
541     png_get_bKGD(png_ptr, info_ptr, &background);
542     background     - background color (PNG_VALID_bKGD)
543                      valid 16-bit red, green and blue
544                      values, regardless of color_type
545
546     num_comments   = png_get_text(png_ptr, info_ptr,
547                      &text_ptr, &num_text);
548     num_comments   - number of comments
549     text_ptr       - array of png_text holding image
550                      comments
551     text_ptr[i].compression - type of compression used
552                  on "text" PNG_TEXT_COMPRESSION_NONE
553                            PNG_TEXT_COMPRESSION_zTXt
554                            PNG_ITXT_COMPRESSION_NONE
555                            PNG_ITXT_COMPRESSION_zTXt
556     text_ptr[i].key   - keyword for comment.  Must contain
557                          1-79 characters.
558     text_ptr[i].text  - text comments for current
559                          keyword.  Can be empty.
560     text_ptr[i].text_length - length of text string,
561                  after decompression, 0 for iTXt
562     text_ptr[i].itxt_length - length of itxt string,
563                  after decompression, 0 for tEXt/zTXt
564     text_ptr[i].lang  - language of comment (empty
565                          string for unknown).
566     text_ptr[i].translated_keyword  - keyword in UTF-8
567                          (empty string for unknown).
568     num_text       - number of comments (same as num_comments;
569                      you can put NULL here to avoid the duplication)
570     Note while png_set_text() will accept text, language, and
571     translated keywords that can be NULL pointers, the structure
572     returned by png_get_text will always contain regular
573     zero-terminated C strings.  They might be empty strings but
574     they will never be NULL pointers.
575
576     num_spalettes = png_get_sPLT(png_ptr, info_ptr, &palette_ptr);
577     palette_ptr    - array of palette structures holding
578                      contents of one or more sPLT chunks read.
579     num_spalettes  - number of sPLT chunks read.
580
581     png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
582                      &unit_type);
583     offset_x       - positive offset from the left edge
584                      of the screen
585     offset_y       - positive offset from the top edge
586                      of the screen
587     unit_type      - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
588
589     png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
590                      &unit_type);
591     res_x          - pixels/unit physical resolution in
592                      x direction
593     res_y          - pixels/unit physical resolution in
594                      x direction
595     unit_type      - PNG_RESOLUTION_UNKNOWN,
596                      PNG_RESOLUTION_METER
597
598     png_get_sCAL(png_ptr, info_ptr, &unit, &width, &height)
599     unit        - physical scale units (an integer)
600     width       - width of a pixel in physical scale units
601     height      - height of a pixel in physical scale units
602                  (width and height are doubles)
603
604     png_get_sCAL_s(png_ptr, info_ptr, &unit, &width, &height)
605     unit        - physical scale units (an integer)
606     width       - width of a pixel in physical scale units
607     height      - height of a pixel in physical scale units
608                  (width and height are strings like "2.54")
609
610     num_unknown_chunks = png_get_unknown_chunks(png_ptr, info_ptr,
611                             &unknowns)
612     unknowns          - array of png_unknown_chunk structures holding
613                         unknown chunks
614     unknowns[i].name  - name of unknown chunk
615     unknowns[i].data  - data of unknown chunk
616     unknowns[i].size  - size of unknown chunk's data
617     unknowns[i].location - position of chunk in file
618
619     The value of "i" corresponds to the order in which the chunks were read
620     from the PNG file or inserted with the png_set_unknown_chunks() function.
621
622 The data from the pHYs chunk can be retrieved in several convenient
623 forms:
624
625     res_x = png_get_x_pixels_per_meter(png_ptr,
626                   info_ptr)
627     res_y = png_get_y_pixels_per_meter(png_ptr,
628                   info_ptr)
629     res_x_and_y = png_get_pixels_per_meter(png_ptr,
630                   info_ptr)
631     res_x = png_get_x_pixels_per_inch(png_ptr,
632                   info_ptr)
633     res_y = png_get_y_pixels_per_inch(png_ptr,
634                   info_ptr)
635     res_x_and_y = png_get_pixels_per_inch(png_ptr,
636                   info_ptr)
637     aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
638                   info_ptr)
639
640    (Each of these returns 0 [signifying "unknown"] if
641        the data is not present or if res_x is 0;
642        res_x_and_y is 0 if res_x != res_y)
643
644 The data from the oFFs chunk can be retrieved in several convenient
645 forms:
646
647     x_offset = png_get_x_offset_microns(png_ptr, info_ptr);
648     y_offset = png_get_y_offset_microns(png_ptr, info_ptr);
649     x_offset = png_get_x_offset_inches(png_ptr, info_ptr);
650     y_offset = png_get_y_offset_inches(png_ptr, info_ptr);
651
652    (Each of these returns 0 [signifying "unknown" if both
653        x and y are 0] if the data is not present or if the chunk
654        is present but the unit is the pixel)
655
656 For more information, see the png_info definition in png.h and the
657 PNG specification for chunk contents.  Be careful with trusting
658 rowbytes, as some of the transformations could increase the space
659 needed to hold a row (expand, filler, gray_to_rgb, etc.).
660 See png_read_update_info(), below.
661
662 A quick word about text_ptr and num_text.  PNG stores comments in
663 keyword/text pairs, one pair per chunk, with no limit on the number
664 of text chunks, and a 2^31 byte limit on their size.  While there are
665 suggested keywords, there is no requirement to restrict the use to these
666 strings.  It is strongly suggested that keywords and text be sensible
667 to humans (that's the point), so don't use abbreviations.  Non-printing
668 symbols are not allowed.  See the PNG specification for more details.
669 There is also no requirement to have text after the keyword.
670
671 Keywords should be limited to 79 Latin-1 characters without leading or
672 trailing spaces, but non-consecutive spaces are allowed within the
673 keyword.  It is possible to have the same keyword any number of times.
674 The text_ptr is an array of png_text structures, each holding a
675 pointer to a language string, a pointer to a keyword and a pointer to
676 a text string.  The text string, language code, and translated
677 keyword may be empty or NULL pointers.  The keyword/text
678 pairs are put into the array in the order that they are received.
679 However, some or all of the text chunks may be after the image, so, to
680 make sure you have read all the text chunks, don't mess with these
681 until after you read the stuff after the image.  This will be
682 mentioned again below in the discussion that goes with png_read_end().
683
684 Input transformations
685
686 After you've read the header information, you can set up the library
687 to handle any special transformations of the image data.  The various
688 ways to transform the data will be described in the order that they
689 should occur.  This is important, as some of these change the color
690 type and/or bit depth of the data, and some others only work on
691 certain color types and bit depths.  Even though each transformation
692 checks to see if it has data that it can do something with, you should
693 make sure to only enable a transformation if it will be valid for the
694 data.  For example, don't swap red and blue on grayscale data.
695
696 The colors used for the background and transparency values should be
697 supplied in the same format/depth as the current image data.  They
698 are stored in the same format/depth as the image data in a bKGD or tRNS
699 chunk, so this is what libpng expects for this data.  The colors are
700 transformed to keep in sync with the image data when an application
701 calls the png_read_update_info() routine (see below).
702
703 Data will be decoded into the supplied row buffers packed into bytes
704 unless the library has been told to transform it into another format.
705 For example, 4 bit/pixel paletted or grayscale data will be returned
706 2 pixels/byte with the leftmost pixel in the high-order bits of the
707 byte, unless png_set_packing() is called.  8-bit RGB data will be stored
708 in RGB RGB RGB format unless png_set_filler() is called to insert filler
709 bytes, either before or after each RGB triplet.  16-bit RGB data will
710 be returned RRGGBB RRGGBB, with the most significant byte of the color
711 value first, unless png_set_strip_16() is called to transform it to
712 regular RGB RGB triplets, or png_set_filler() is called to insert
713 filler bytes, either before or after each RRGGBB triplet.  Similarly,
714 8-bit or 16-bit grayscale data can be modified with png_set_filler()
715 or png_set_strip_16().
716
717 The following code transforms grayscale images of less than 8 to 8 bits,
718 changes paletted images to RGB, and adds a full alpha channel if there is
719 transparency information in a tRNS chunk.  This is most useful on
720 grayscale images with bit depths of 2 or 4 or if there is a multiple-image
721 viewing application that wishes to treat all images in the same way.
722
723     if (color_type == PNG_COLOR_TYPE_PALETTE)
724         png_set_palette_to_rgb(png_ptr);
725
726     if (color_type == PNG_COLOR_TYPE_GRAY &&
727         bit_depth < 8) png_set_gray_1_2_4_to_8(png_ptr);
728
729     if (png_get_valid(png_ptr, info_ptr,
730         PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
731
732 These three functions are actually aliases for png_set_expand(), added
733 in libpng version 1.0.4, with the function names expanded to improve code
734 readability.  In some future version they may actually do different
735 things.
736
737 PNG can have files with 16 bits per channel.  If you only can handle
738 8 bits per channel, this will strip the pixels down to 8 bit.
739
740     if (bit_depth == 16)
741         png_set_strip_16(png_ptr);
742
743 If, for some reason, you don't need the alpha channel on an image,
744 and you want to remove it rather than combining it with the background
745 (but the image author certainly had in mind that you *would* combine
746 it with the background, so that's what you should probably do):
747
748     if (color_type & PNG_COLOR_MASK_ALPHA)
749         png_set_strip_alpha(png_ptr);
750
751 In PNG files, the alpha channel in an image
752 is the level of opacity.  If you need the alpha channel in an image to
753 be the level of transparency instead of opacity, you can invert the
754 alpha channel (or the tRNS chunk data) after it's read, so that 0 is
755 fully opaque and 255 (in 8-bit or paletted images) or 65535 (in 16-bit
756 images) is fully transparent, with
757
758     png_set_invert_alpha(png_ptr);
759
760 PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
761 they can, resulting in, for example, 8 pixels per byte for 1 bit
762 files.  This code expands to 1 pixel per byte without changing the
763 values of the pixels:
764
765     if (bit_depth < 8)
766         png_set_packing(png_ptr);
767
768 PNG files have possible bit depths of 1, 2, 4, 8, and 16.  All pixels
769 stored in a PNG image have been "scaled" or "shifted" up to the next
770 higher possible bit depth (e.g. from 5 bits/sample in the range [0,31] to
771 8 bits/sample in the range [0, 255]).  However, it is also possible to
772 convert the PNG pixel data back to the original bit depth of the image.
773 This call reduces the pixels back down to the original bit depth:
774
775     png_color_16p sig_bit;
776
777     if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
778         png_set_shift(png_ptr, sig_bit);
779
780 PNG files store 3-color pixels in red, green, blue order.  This code
781 changes the storage of the pixels to blue, green, red:
782
783     if (color_type == PNG_COLOR_TYPE_RGB ||
784         color_type == PNG_COLOR_TYPE_RGB_ALPHA)
785         png_set_bgr(png_ptr);
786
787 PNG files store RGB pixels packed into 3 bytes. This code expands them
788 into 4 bytes for windowing systems that need them in this format:
789
790     if (bit_depth == 8 && color_type ==
791         PNG_COLOR_TYPE_RGB) png_set_filler(png_ptr,
792         filler, PNG_FILLER_BEFORE);
793
794 where "filler" is the 8 or 16-bit number to fill with, and the location is
795 either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
796 you want the filler before the RGB or after.  This transformation
797 does not affect images that already have full alpha channels.
798
799 If you are reading an image with an alpha channel, and you need the
800 data as ARGB instead of the normal PNG format RGBA:
801
802     if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
803         png_set_swap_alpha(png_ptr);
804
805 For some uses, you may want a grayscale image to be represented as
806 RGB.  This code will do that conversion:
807
808     if (color_type == PNG_COLOR_TYPE_GRAY ||
809         color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
810           png_set_gray_to_rgb(png_ptr);
811
812 Conversely, you can convert an RGB or RGBA image to grayscale or grayscale
813 with alpha.
814
815     if (color_type == PNG_COLOR_TYPE_RGB ||
816         color_type == PNG_COLOR_TYPE_RGB_ALPHA)
817           png_set_rgb_to_gray_fixed(png_ptr, error_action,
818              int red_weight, int green_weight);
819
820     error_action = 1: silently do the conversion
821     error_action = 2: issue a warning if the original
822                       image has any pixel where
823                       red != green or red != blue
824     error_action = 3: issue an error and abort the
825                       conversion if the original
826                       image has any pixel where
827                       red != green or red != blue
828
829     red_weight:       weight of red component times 100000
830     green_weight:     weight of green component times 100000
831                       If either weight is negative, default
832                       weights (21268, 71514) are used.
833
834 If you have set error_action = 1 or 2, you can
835 later check whether the image really was gray, after processing
836 the image rows, with the png_get_rgb_to_gray_status(png_ptr) function.
837 It will return a png_byte that is zero if the image was gray or
838 1 if there were any non-gray pixels.  bKGD and sBIT data
839 will be silently converted to grayscale, using the green channel
840 data, regardless of the error_action setting.
841
842 With red_weight+green_weight<=100000,
843 the normalized graylevel is computed:
844
845     int rw = red_weight * 65536;
846     int gw = green_weight * 65536;
847     int bw = 65536 - (rw + gw);
848     gray = (rw*red + gw*green + bw*blue)/65536;
849
850 The default values approximate those recommended in the Charles
851 Poynton's Color FAQ, <http://www.inforamp.net/~poynton/>
852 Copyright (c) 1998-01-04 Charles Poynton poynton@inforamp.net
853
854     Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
855
856 Libpng approximates this with
857
858     Y = 0.21268 * R    + 0.7151 * G    + 0.07217 * B
859
860 which can be expressed with integers as
861
862     Y = (6969 * R + 23434 * G + 2365 * B)/32768
863
864 The calculation is done in a linear colorspace, if the image gamma
865 is known.
866
867 If you have a grayscale and you are using png_set_expand_depth() or
868 png_set_expand() to change to
869 a higher bit-depth, you must either supply the background color as a gray
870 value at the original file bit-depth (need_expand = 1) or else supply the
871 background color as an RGB triplet at the final, expanded bit depth
872 (need_expand = 0).  Similarly, if you are reading a paletted image, you
873 must either supply the background color as a palette index (need_expand = 1)
874 or as an RGB triplet that may or may not be in the palette (need_expand = 0).
875
876     png_color_16 my_background;
877     png_color_16p image_background;
878
879     if (png_get_bKGD(png_ptr, info_ptr, &image_background))
880         png_set_background(png_ptr, image_background,
881           PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
882     else
883         png_set_background(png_ptr, &my_background,
884           PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
885
886 The png_set_background() function tells libpng to composite images
887 with alpha or simple transparency against the supplied background
888 color.  If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
889 you may use this color, or supply another color more suitable for
890 the current display (e.g., the background color from a web page).  You
891 need to tell libpng whether the color is in the gamma space of the
892 display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
893 (PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
894 that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
895 know why anyone would use this, but it's here).
896
897 To properly display PNG images on any kind of system, the application needs
898 to know what the display gamma is.  Ideally, the user will know this, and
899 the application will allow them to set it.  One method of allowing the user
900 to set the display gamma separately for each system is to check for a
901 SCREEN_GAMMA or DISPLAY_GAMMA environment variable, which will hopefully be
902 correctly set.
903
904 Note that display_gamma is the overall gamma correction required to produce
905 pleasing results, which depends on the lighting conditions in the surrounding
906 environment.  In a dim or brightly lit room, no compensation other than
907 the physical gamma exponent of the monitor is needed, while in a dark room
908 a slightly smaller exponent is better.
909
910    double gamma, screen_gamma;
911
912    if (/* We have a user-defined screen
913        gamma value */)
914    {
915       screen_gamma = user_defined_screen_gamma;
916    }
917    /* One way that applications can share the same
918       screen gamma value */
919    else if ((gamma_str = getenv("SCREEN_GAMMA"))
920       != NULL)
921    {
922       screen_gamma = (double)atof(gamma_str);
923    }
924    /* If we don't have another value */
925    else
926    {
927       screen_gamma = 2.2; /* A good guess for a
928            PC monitor in a bright office or a dim room */
929       screen_gamma = 2.0; /* A good guess for a
930            PC monitor in a dark room */
931       screen_gamma = 1.7 or 1.0;  /* A good
932            guess for Mac systems */
933    }
934
935 The png_set_gamma() function handles gamma transformations of the data.
936 Pass both the file gamma and the current screen_gamma.  If the file does
937 not have a gamma value, you can pass one anyway if you have an idea what
938 it is (usually 0.45455 is a good guess for GIF images on PCs).  Note
939 that file gammas are inverted from screen gammas.  See the discussions
940 on gamma in the PNG specification for an excellent description of what
941 gamma is, and why all applications should support it.  It is strongly
942 recommended that PNG viewers support gamma correction.
943
944    if (png_get_gAMA(png_ptr, info_ptr, &gamma))
945       png_set_gamma(png_ptr, screen_gamma, gamma);
946    else
947       png_set_gamma(png_ptr, screen_gamma, 0.45455);
948
949 If you need to reduce an RGB file to a paletted file, or if a paletted
950 file has more entries then will fit on your screen, png_set_dither()
951 will do that.  Note that this is a simple match dither that merely
952 finds the closest color available.  This should work fairly well with
953 optimized palettes, and fairly badly with linear color cubes.  If you
954 pass a palette that is larger then maximum_colors, the file will
955 reduce the number of colors in the palette so it will fit into
956 maximum_colors.  If there is a histogram, it will use it to make
957 more intelligent choices when reducing the palette.  If there is no
958 histogram, it may not do as good a job.
959
960    if (color_type & PNG_COLOR_MASK_COLOR)
961    {
962       if (png_get_valid(png_ptr, info_ptr,
963          PNG_INFO_PLTE))
964       {
965          png_uint_16p histogram;
966
967          png_get_hIST(png_ptr, info_ptr,
968             &histogram);
969          png_set_dither(png_ptr, palette, num_palette,
970             max_screen_colors, histogram, 1);
971       }
972       else
973       {
974          png_color std_color_cube[MAX_SCREEN_COLORS] =
975             { ... colors ... };
976
977          png_set_dither(png_ptr, std_color_cube,
978             MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
979             NULL,0);
980       }
981    }
982
983 PNG files describe monochrome as black being zero and white being one.
984 The following code will reverse this (make black be one and white be
985 zero):
986
987    if (bit_depth == 1 && color_type == PNG_COLOR_GRAY)
988       png_set_invert_mono(png_ptr);
989
990 PNG files store 16 bit pixels in network byte order (big-endian,
991 ie. most significant bits first).  This code changes the storage to the
992 other way (little-endian, i.e. least significant bits first, the
993 way PCs store them):
994
995     if (bit_depth == 16)
996         png_set_swap(png_ptr);
997
998 If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
999 need to change the order the pixels are packed into bytes, you can use:
1000
1001     if (bit_depth < 8)
1002        png_set_packswap(png_ptr);
1003
1004 Finally, you can write your own transformation function if none of
1005 the existing ones meets your needs.  This is done by setting a callback
1006 with
1007
1008     png_set_read_user_transform_fn(png_ptr,
1009        read_transform_fn);
1010
1011 You must supply the function
1012
1013     void read_transform_fn(png_ptr ptr, row_info_ptr
1014        row_info, png_bytep data)
1015
1016 See pngtest.c for a working example.  Your function will be called
1017 after all of the other transformations have been processed.
1018
1019 You can also set up a pointer to a user structure for use by your
1020 callback function, and you can inform libpng that your transform
1021 function will change the number of channels or bit depth with the
1022 function
1023
1024     png_set_user_transform_info(png_ptr, user_ptr,
1025        user_depth, user_channels);
1026
1027 The user's application, not libpng, is responsible for allocating and
1028 freeing any memory required for the user structure.
1029
1030 You can retrieve the pointer via the function
1031 png_get_user_transform_ptr().  For example:
1032
1033     voidp read_user_transform_ptr =
1034        png_get_user_transform_ptr(png_ptr);
1035
1036 The last thing to handle is interlacing; this is covered in detail below,
1037 but you must call the function here if you want libpng to handle expansion
1038 of the interlaced image.
1039
1040     number_of_passes = png_set_interlace_handling(png_ptr);
1041
1042 After setting the transformations, libpng can update your png_info
1043 structure to reflect any transformations you've requested with this
1044 call.  This is most useful to update the info structure's rowbytes
1045 field so you can use it to allocate your image memory.  This function
1046 will also update your palette with the correct screen_gamma and
1047 background if these have been given with the calls above.
1048
1049     png_read_update_info(png_ptr, info_ptr);
1050
1051 After you call png_read_update_info(), you can allocate any
1052 memory you need to hold the image.  The row data is simply
1053 raw byte data for all forms of images.  As the actual allocation
1054 varies among applications, no example will be given.  If you
1055 are allocating one large chunk, you will need to build an
1056 array of pointers to each row, as it will be needed for some
1057 of the functions below.
1058
1059 Reading image data
1060
1061 After you've allocated memory, you can read the image data.
1062 The simplest way to do this is in one function call.  If you are
1063 allocating enough memory to hold the whole image, you can just
1064 call png_read_image() and libpng will read in all the image data
1065 and put it in the memory area supplied.  You will need to pass in
1066 an array of pointers to each row.
1067
1068 This function automatically handles interlacing, so you don't need
1069 to call png_set_interlace_handling() or call this function multiple
1070 times, or any of that other stuff necessary with png_read_rows().
1071
1072    png_read_image(png_ptr, row_pointers);
1073
1074 where row_pointers is:
1075
1076    png_bytep row_pointers[height];
1077
1078 You can point to void or char or whatever you use for pixels.
1079
1080 If you don't want to read in the whole image at once, you can
1081 use png_read_rows() instead.  If there is no interlacing (check
1082 interlace_type == PNG_INTERLACE_NONE), this is simple:
1083
1084     png_read_rows(png_ptr, row_pointers, NULL,
1085        number_of_rows);
1086
1087 where row_pointers is the same as in the png_read_image() call.
1088
1089 If you are doing this just one row at a time, you can do this with
1090 a single row_pointer instead of an array of row_pointers:
1091
1092     png_bytep row_pointer = row;
1093     png_read_row(png_ptr, row_pointer, NULL);
1094
1095 If the file is interlaced (interlace_type != 0 in the IHDR chunk), things
1096 get somewhat harder.  The only current (PNG Specification version 1.2)
1097 interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7)
1098 is a somewhat complicated 2D interlace scheme, known as Adam7, that
1099 breaks down an image into seven smaller images of varying size, based
1100 on an 8x8 grid.
1101
1102 libpng can fill out those images or it can give them to you "as is".
1103 If you want them filled out, there are two ways to do that.  The one
1104 mentioned in the PNG specification is to expand each pixel to cover
1105 those pixels that have not been read yet (the "rectangle" method).
1106 This results in a blocky image for the first pass, which gradually
1107 smooths out as more pixels are read.  The other method is the "sparkle"
1108 method, where pixels are drawn only in their final locations, with the
1109 rest of the image remaining whatever colors they were initialized to
1110 before the start of the read.  The first method usually looks better,
1111 but tends to be slower, as there are more pixels to put in the rows.
1112
1113 If you don't want libpng to handle the interlacing details, just call
1114 png_read_rows() seven times to read in all seven images.  Each of the
1115 images is a valid image by itself, or they can all be combined on an
1116 8x8 grid to form a single image (although if you intend to combine them
1117 you would be far better off using the libpng interlace handling).
1118
1119 The first pass will return an image 1/8 as wide as the entire image
1120 (every 8th column starting in column 0) and 1/8 as high as the original
1121 (every 8th row starting in row 0), the second will be 1/8 as wide
1122 (starting in column 4) and 1/8 as high (also starting in row 0).  The
1123 third pass will be 1/4 as wide (every 4th pixel starting in column 0) and
1124 1/8 as high (every 8th row starting in row 4), and the fourth pass will
1125 be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
1126 and every 4th row starting in row 0).  The fifth pass will return an
1127 image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
1128 while the sixth pass will be 1/2 as wide and 1/2 as high as the original
1129 (starting in column 1 and row 0).  The seventh and final pass will be as
1130 wide as the original, and 1/2 as high, containing all of the odd
1131 numbered scanlines.  Phew!
1132
1133 If you want libpng to expand the images, call this before calling
1134 png_start_read_image() or png_read_update_info():
1135
1136     if (interlace_type == PNG_INTERLACE_ADAM7)
1137         number_of_passes
1138            = png_set_interlace_handling(png_ptr);
1139
1140 This will return the number of passes needed.  Currently, this
1141 is seven, but may change if another interlace type is added.
1142 This function can be called even if the file is not interlaced,
1143 where it will return one pass.
1144
1145 If you are not going to display the image after each pass, but are
1146 going to wait until the entire image is read in, use the sparkle
1147 effect.  This effect is faster and the end result of either method
1148 is exactly the same.  If you are planning on displaying the image
1149 after each pass, the "rectangle" effect is generally considered the
1150 better looking one.
1151
1152 If you only want the "sparkle" effect, just call png_read_rows() as
1153 normal, with the third parameter NULL.  Make sure you make pass over
1154 the image number_of_passes times, and you don't change the data in the
1155 rows between calls.  You can change the locations of the data, just
1156 not the data.  Each pass only writes the pixels appropriate for that
1157 pass, and assumes the data from previous passes is still valid.
1158
1159     png_read_rows(png_ptr, row_pointers, NULL,
1160        number_of_rows);
1161
1162 If you only want the first effect (the rectangles), do the same as
1163 before except pass the row buffer in the third parameter, and leave
1164 the second parameter NULL.
1165
1166     png_read_rows(png_ptr, NULL, row_pointers,
1167        number_of_rows);
1168
1169 Finishing a sequential read
1170
1171 After you are finished reading the image through either the high- or
1172 low-level interfaces, you can finish reading the file.  If you are
1173 interested in comments or time, which may be stored either before or
1174 after the image data, you should pass the separate png_info struct if
1175 you want to keep the comments from before and after the image
1176 separate.  If you are not interested, you can pass NULL.
1177
1178    png_read_end(png_ptr, end_info);
1179
1180 When you are done, you can free all memory allocated by libpng like this:
1181
1182    png_destroy_read_struct(&png_ptr, &info_ptr,
1183        &end_info);
1184
1185 It is also possible to individually free the info_ptr members that
1186 point to libpng-allocated storage with the following function:
1187
1188     png_free_data(png_ptr, info_ptr, mask, n)
1189     mask - identifies data to be freed, a mask
1190            containing the logical OR of one or
1191            more of
1192              PNG_FREE_PLTE, PNG_FREE_TRNS,
1193              PNG_FREE_HIST, PNG_FREE_ICCP,
1194              PNG_FREE_PCAL, PNG_FREE_ROWS,
1195              PNG_FREE_SCAL, PNG_FREE_SPLT,
1196              PNG_FREE_TEXT, PNG_FREE_UNKN,
1197            or simply PNG_FREE_ALL
1198     n    - sequence number of item to be freed
1199            (-1 for all items)
1200
1201 This function may be safely called when the relevant storage has
1202 already been freed, or has not yet been allocated, or was allocated
1203 by the user and not by libpng,  and will in those
1204 cases do nothing.  The "n" parameter is ignored if only one item
1205 of the selected data type, such as PLTE, is allowed.  If "n" is not
1206 -1, and multiple items are allowed for the data type identified in
1207 the mask, such as text or sPLT, only the n'th item is freed.
1208
1209 The default behavior is only to free data that was allocated internally
1210 by libpng.  This can be changed, so that libpng will not free the data,
1211 or so that it will free data that was allocated by the user with png_malloc()
1212 or png_zalloc() and passed in via a png_set_*() function, with
1213
1214     png_data_freer(png_ptr, info_ptr, freer, mask)
1215     mask   - which data elements are affected
1216              same choices as in png_free_data()
1217     freer  - one of
1218                PNG_DESTROY_WILL_FREE_DATA
1219                PNG_SET_WILL_FREE_DATA
1220                PNG_USER_WILL_FREE_DATA
1221
1222 This function only affects data that has already been allocated.
1223 You can call this function after reading the PNG data but before calling
1224 any png_set_*() functions, to control whether the user or the png_set_*()
1225 function is responsible for freeing any existing data that might be present,
1226 and again after the png_set_*() functions to control whether the user
1227 or png_destroy_*() is supposed to free the data.  When the user assumes
1228 responsibility for libpng-allocated data, the application must use
1229 png_free() to free it, and when the user transfers responsibility to libpng
1230 for data that the user has allocated, the user must have used png_malloc()
1231 or png_zalloc() to allocate it (the png_zalloc() function is the same
1232 as png_malloc() except that it also zeroes the newly-allocated memory).
1233
1234 If you allocated your row_pointers in a single block, as suggested above in
1235 the description of the high level read interface, you must not transfer
1236 responsibility for freeing it to the png_set_rows or png_read_destroy function,
1237 because they would also try to free the individual row_pointers[i].
1238
1239 If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
1240 separately, do not transfer responsibility for freeing text_ptr to libpng,
1241 because when libpng fills a png_text structure it combines these members with
1242 the key member, and png_free_data() will free only text_ptr.key.  Similarly,
1243 if you transfer responsibility for free'ing text_ptr from libpng to your
1244 application, your application must not separately free those members.
1245
1246 The png_free_data() function will turn off the "valid" flag for anything
1247 it frees.  If you need to turn the flag off for a chunk that was freed by your
1248 application instead of by libpng, you can use
1249
1250     png_set_invalid(png_ptr, info_ptr, mask);
1251     mask - identifies the chunks to be made invalid,
1252            containing the logical OR of one or
1253            more of
1254              PNG_INFO_gAMA, PNG_INFO_sBIT,
1255              PNG_INFO_cHRM, PNG_INFO_PLTE,
1256              PNG_INFO_tRNS, PNG_INFO_bKGD,
1257              PNG_INFO_hIST, PNG_INFO_pHYs,
1258              PNG_INFO_oFFs, PNG_INFO_tIME,
1259              PNG_INFO_pCAL, PNG_INFO_sRGB,
1260              PNG_INFO_iCCP, PNG_INFO_sPLT,
1261              PNG_INFO_sCAL, PNG_INFO_IDAT
1262
1263 For a more compact example of reading a PNG image, see the file example.c.
1264
1265 Reading PNG files progressively
1266
1267 The progressive reader is slightly different then the non-progressive
1268 reader.  Instead of calling png_read_info(), png_read_rows(), and
1269 png_read_end(), you make one call to png_process_data(), which calls
1270 callbacks when it has the info, a row, or the end of the image.  You
1271 set up these callbacks with png_set_progressive_read_fn().  You don't
1272 have to worry about the input/output functions of libpng, as you are
1273 giving the library the data directly in png_process_data().  I will
1274 assume that you have read the section on reading PNG files above,
1275 so I will only highlight the differences (although I will show
1276 all of the code).
1277
1278 png_structp png_ptr;
1279 png_infop info_ptr;
1280
1281  /*  An example code fragment of how you would
1282      initialize the progressive reader in your
1283      application. */
1284  int
1285  initialize_png_reader()
1286  {
1287     png_ptr = png_create_read_struct
1288         (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1289          user_error_fn, user_warning_fn);
1290     if (!png_ptr)
1291         return (ERROR);
1292     info_ptr = png_create_info_struct(png_ptr);
1293     if (!info_ptr)
1294     {
1295         png_destroy_read_struct(&png_ptr, (png_infopp)NULL,
1296            (png_infopp)NULL);
1297         return (ERROR);
1298     }
1299
1300     if (setjmp(png_jmpbuf(png_ptr)))
1301     {
1302         png_destroy_read_struct(&png_ptr, &info_ptr,
1303            (png_infopp)NULL);
1304         return (ERROR);
1305     }
1306
1307     /* This one's new.  You can provide functions
1308        to be called when the header info is valid,
1309        when each row is completed, and when the image
1310        is finished.  If you aren't using all functions,
1311        you can specify NULL parameters.  Even when all
1312        three functions are NULL, you need to call
1313        png_set_progressive_read_fn().  You can use
1314        any struct as the user_ptr (cast to a void pointer
1315        for the function call), and retrieve the pointer
1316        from inside the callbacks using the function
1317
1318           png_get_progressive_ptr(png_ptr);
1319
1320        which will return a void pointer, which you have
1321        to cast appropriately.
1322      */
1323     png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
1324         info_callback, row_callback, end_callback);
1325
1326     return 0;
1327  }
1328
1329  /* A code fragment that you call as you receive blocks
1330    of data */
1331  int
1332  process_data(png_bytep buffer, png_uint_32 length)
1333  {
1334     if (setjmp(png_jmpbuf(png_ptr)))
1335     {
1336         png_destroy_read_struct(&png_ptr, &info_ptr,
1337            (png_infopp)NULL);
1338         return (ERROR);
1339     }
1340
1341     /* This one's new also.  Simply give it a chunk
1342        of data from the file stream (in order, of
1343        course).  On machines with segmented memory
1344        models machines, don't give it any more than
1345        64K.  The library seems to run fine with sizes
1346        of 4K. Although you can give it much less if
1347        necessary (I assume you can give it chunks of
1348        1 byte, I haven't tried less then 256 bytes
1349        yet).  When this function returns, you may
1350        want to display any rows that were generated
1351        in the row callback if you don't already do
1352        so there.
1353      */
1354     png_process_data(png_ptr, info_ptr, buffer, length);
1355     return 0;
1356  }
1357
1358  /* This function is called (as set by
1359     png_set_progressive_read_fn() above) when enough data
1360     has been supplied so all of the header has been
1361     read.
1362  */
1363  void
1364  info_callback(png_structp png_ptr, png_infop info)
1365  {
1366     /* Do any setup here, including setting any of
1367        the transformations mentioned in the Reading
1368        PNG files section.  For now, you _must_ call
1369        either png_start_read_image() or
1370        png_read_update_info() after all the
1371        transformations are set (even if you don't set
1372        any).  You may start getting rows before
1373        png_process_data() returns, so this is your
1374        last chance to prepare for that.
1375      */
1376  }
1377
1378  /* This function is called when each row of image
1379     data is complete */
1380  void
1381  row_callback(png_structp png_ptr, png_bytep new_row,
1382     png_uint_32 row_num, int pass)
1383  {
1384     /* If the image is interlaced, and you turned
1385        on the interlace handler, this function will
1386        be called for every row in every pass.  Some
1387        of these rows will not be changed from the
1388        previous pass.  When the row is not changed,
1389        the new_row variable will be NULL.  The rows
1390        and passes are called in order, so you don't
1391        really need the row_num and pass, but I'm
1392        supplying them because it may make your life
1393        easier.
1394
1395        For the non-NULL rows of interlaced images,
1396        you must call png_progressive_combine_row()
1397        passing in the row and the old row.  You can
1398        call this function for NULL rows (it will just
1399        return) and for non-interlaced images (it just
1400        does the memcpy for you) if it will make the
1401        code easier.  Thus, you can just do this for
1402        all cases:
1403      */
1404
1405         png_progressive_combine_row(png_ptr, old_row,
1406           new_row);
1407
1408     /* where old_row is what was displayed for
1409        previously for the row.  Note that the first
1410        pass (pass == 0, really) will completely cover
1411        the old row, so the rows do not have to be
1412        initialized.  After the first pass (and only
1413        for interlaced images), you will have to pass
1414        the current row, and the function will combine
1415        the old row and the new row.
1416     */
1417  }
1418
1419  void
1420  end_callback(png_structp png_ptr, png_infop info)
1421  {
1422     /* This function is called after the whole image
1423        has been read, including any chunks after the
1424        image (up to and including the IEND).  You
1425        will usually have the same info chunk as you
1426        had in the header, although some data may have
1427        been added to the comments and time fields.
1428
1429        Most people won't do much here, perhaps setting
1430        a flag that marks the image as finished.
1431      */
1432  }
1433
1434
1435
1436 IV. Writing
1437
1438 Much of this is very similar to reading.  However, everything of
1439 importance is repeated here, so you won't have to constantly look
1440 back up in the reading section to understand writing.
1441
1442 Setup
1443
1444 You will want to do the I/O initialization before you get into libpng,
1445 so if it doesn't work, you don't have anything to undo. If you are not
1446 using the standard I/O functions, you will need to replace them with
1447 custom writing functions.  See the discussion under Customizing libpng.
1448
1449     FILE *fp = fopen(file_name, "wb");
1450     if (!fp)
1451     {
1452        return (ERROR);
1453     }
1454
1455 Next, png_struct and png_info need to be allocated and initialized.
1456 As these can be both relatively large, you may not want to store these
1457 on the stack, unless you have stack space to spare.  Of course, you
1458 will want to check if they return NULL.  If you are also reading,
1459 you won't want to name your read structure and your write structure
1460 both "png_ptr"; you can call them anything you like, such as
1461 "read_ptr" and "write_ptr".  Look at pngtest.c, for example.
1462
1463     png_structp png_ptr = png_create_write_struct
1464        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1465         user_error_fn, user_warning_fn);
1466     if (!png_ptr)
1467        return (ERROR);
1468
1469     png_infop info_ptr = png_create_info_struct(png_ptr);
1470     if (!info_ptr)
1471     {
1472        png_destroy_write_struct(&png_ptr,
1473          (png_infopp)NULL);
1474        return (ERROR);
1475     }
1476
1477 If you want to use your own memory allocation routines,
1478 define PNG_USER_MEM_SUPPORTED and use
1479 png_create_write_struct_2() instead of png_create_write_struct():
1480
1481     png_structp png_ptr = png_create_write_struct_2
1482        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1483         user_error_fn, user_warning_fn, (png_voidp)
1484         user_mem_ptr, user_malloc_fn, user_free_fn);
1485
1486 After you have these structures, you will need to set up the
1487 error handling.  When libpng encounters an error, it expects to
1488 longjmp() back to your routine.  Therefore, you will need to call
1489 setjmp() and pass the png_jmpbuf(png_ptr).  If you
1490 write the file from different routines, you will need to update
1491 the png_jmpbuf(png_ptr) every time you enter a new routine that will
1492 call a png_*() function.  See your documentation of setjmp/longjmp
1493 for your compiler for more information on setjmp/longjmp.  See
1494 the discussion on libpng error handling in the Customizing Libpng
1495 section below for more information on the libpng error handling.
1496
1497     if (setjmp(png_jmpbuf(png_ptr)))
1498     {
1499        png_destroy_write_struct(&png_ptr, &info_ptr);
1500        fclose(fp);
1501        return (ERROR);
1502     }
1503     ...
1504     return;
1505
1506 If you would rather avoid the complexity of setjmp/longjmp issues,
1507 you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case
1508 errors will result in a call to PNG_ABORT() which defaults to abort().
1509
1510 Now you need to set up the output code.  The default for libpng is to
1511 use the C function fwrite().  If you use this, you will need to pass a
1512 valid FILE * in the function png_init_io().  Be sure that the file is
1513 opened in binary mode.  Again, if you wish to handle writing data in
1514 another way, see the discussion on libpng I/O handling in the Customizing
1515 Libpng section below.
1516
1517     png_init_io(png_ptr, fp);
1518
1519 Write callbacks
1520
1521 At this point, you can set up a callback function that will be
1522 called after each row has been written, which you can use to control
1523 a progress meter or the like.  It's demonstrated in pngtest.c.
1524 You must supply a function
1525
1526     void write_row_callback(png_ptr, png_uint_32 row, int pass);
1527     {
1528       /* put your code here */
1529     }
1530
1531 (You can give it another name that you like instead of "write_row_callback")
1532
1533 To inform libpng about your function, use
1534
1535     png_set_write_status_fn(png_ptr, write_row_callback);
1536
1537 You now have the option of modifying how the compression library will
1538 run.  The following functions are mainly for testing, but may be useful
1539 in some cases, like if you need to write PNG files extremely fast and
1540 are willing to give up some compression, or if you want to get the
1541 maximum possible compression at the expense of slower writing.  If you
1542 have no special needs in this area, let the library do what it wants by
1543 not calling this function at all, as it has been tuned to deliver a good
1544 speed/compression ratio. The second parameter to png_set_filter() is
1545 the filter method, for which the only valid values are 0 (as of the
1546 July 1999 PNG specification, version 1.2) or 64 (if you are writing
1547 a PNG datastream that is to be embedded in a MNG datastream).  The third
1548 parameter is a flag that indicates which filter type(s) are to be tested
1549 for each scanline.  See the PNG specification for details on the specific filter
1550 types.
1551
1552
1553     /* turn on or off filtering, and/or choose
1554        specific filters.  You can use either a single PNG_FILTER_VALUE_NAME
1555        or the logical OR of one or more PNG_FILTER_NAME masks. */
1556     png_set_filter(png_ptr, 0,
1557        PNG_FILTER_NONE  | PNG_FILTER_VALUE_NONE |
1558        PNG_FILTER_SUB   | PNG_FILTER_VALUE_SUB  |
1559        PNG_FILTER_UP    | PNG_FILTER_VALUE_UP   |
1560        PNG_FILTER_AVE   | PNG_FILTER_VALUE_AVE  |
1561        PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH|
1562        PNG_ALL_FILTERS);
1563
1564 If an application
1565 wants to start and stop using particular filters during compression,
1566 it should start out with all of the filters (to ensure that the previous
1567 row of pixels will be stored in case it's needed later), and then add
1568 and remove them after the start of compression.
1569
1570 If you are writing a PNG datastream that is to be embedded in a MNG
1571 datastream, the second parameter can be either 0 or 64.
1572
1573 The png_set_compression_*() functions interface to the zlib compression
1574 library, and should mostly be ignored unless you really know what you are
1575 doing.  The only generally useful call is png_set_compression_level()
1576 which changes how much time zlib spends on trying to compress the image
1577 data.  See the Compression Library (zlib.h and algorithm.txt, distributed
1578 with zlib) for details on the compression levels.
1579
1580     /* set the zlib compression level */
1581     png_set_compression_level(png_ptr,
1582         Z_BEST_COMPRESSION);
1583
1584     /* set other zlib parameters */
1585     png_set_compression_mem_level(png_ptr, 8);
1586     png_set_compression_strategy(png_ptr,
1587         Z_DEFAULT_STRATEGY);
1588     png_set_compression_window_bits(png_ptr, 15);
1589     png_set_compression_method(png_ptr, 8);
1590     png_set_compression_buffer_size(png_ptr, 8192)
1591
1592 extern PNG_EXPORT(void,png_set_zbuf_size)
1593
1594 Setting the contents of info for output
1595
1596 You now need to fill in the png_info structure with all the data you
1597 wish to write before the actual image.  Note that the only thing you
1598 are allowed to write after the image is the text chunks and the time
1599 chunk (as of PNG Specification 1.2, anyway).  See png_write_end() and
1600 the latest PNG specification for more information on that.  If you
1601 wish to write them before the image, fill them in now, and flag that
1602 data as being valid.  If you want to wait until after the data, don't
1603 fill them until png_write_end().  For all the fields in png_info and
1604 their data types, see png.h.  For explanations of what the fields
1605 contain, see the PNG specification.
1606
1607 Some of the more important parts of the png_info are:
1608
1609     png_set_IHDR(png_ptr, info_ptr, width, height,
1610        bit_depth, color_type, interlace_type,
1611        compression_type, filter_method)
1612     width          - holds the width of the image
1613                      in pixels (up to 2^31).
1614     height         - holds the height of the image
1615                      in pixels (up to 2^31).
1616     bit_depth      - holds the bit depth of one of the
1617                      image channels.
1618                      (valid values are 1, 2, 4, 8, 16
1619                      and depend also on the
1620                      color_type.  See also significant
1621                      bits (sBIT) below).
1622     color_type     - describes which color/alpha
1623                      channels are present.
1624                      PNG_COLOR_TYPE_GRAY
1625                         (bit depths 1, 2, 4, 8, 16)
1626                      PNG_COLOR_TYPE_GRAY_ALPHA
1627                         (bit depths 8, 16)
1628                      PNG_COLOR_TYPE_PALETTE
1629                         (bit depths 1, 2, 4, 8)
1630                      PNG_COLOR_TYPE_RGB
1631                         (bit_depths 8, 16)
1632                      PNG_COLOR_TYPE_RGB_ALPHA
1633                         (bit_depths 8, 16)
1634
1635                      PNG_COLOR_MASK_PALETTE
1636                      PNG_COLOR_MASK_COLOR
1637                      PNG_COLOR_MASK_ALPHA
1638
1639     interlace_type - PNG_INTERLACE_NONE or
1640                      PNG_INTERLACE_ADAM7
1641     compression_type - (must be
1642                      PNG_COMPRESSION_TYPE_DEFAULT)
1643     filter_method  - (must be PNG_FILTER_TYPE_DEFAULT
1644                      or, if you are writing a PNG to
1645                      be embedded in a MNG datastream,
1646                      can also be
1647                      PNG_INTRAPIXEL_DIFFERENCING)
1648
1649     png_set_PLTE(png_ptr, info_ptr, palette,
1650        num_palette);
1651     palette        - the palette for the file
1652                      (array of png_color)
1653     num_palette    - number of entries in the palette
1654
1655     png_set_gAMA(png_ptr, info_ptr, gamma);
1656     gamma          - the gamma the image was created
1657                      at (PNG_INFO_gAMA)
1658
1659     png_set_sRGB(png_ptr, info_ptr, srgb_intent);
1660     srgb_intent    - the rendering intent
1661                      (PNG_INFO_sRGB) The presence of
1662                      the sRGB chunk means that the pixel
1663                      data is in the sRGB color space.
1664                      This chunk also implies specific
1665                      values of gAMA and cHRM.  Rendering
1666                      intent is the CSS-1 property that
1667                      has been defined by the International
1668                      Color Consortium
1669                      (http://www.color.org).
1670                      It can be one of
1671                      PNG_sRGB_INTENT_SATURATION,
1672                      PNG_sRGB_INTENT_PERCEPTUAL,
1673                      PNG_sRGB_INTENT_ABSOLUTE, or
1674                      PNG_sRGB_INTENT_RELATIVE.
1675
1676
1677     png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
1678        srgb_intent);
1679     srgb_intent    - the rendering intent
1680                      (PNG_INFO_sRGB) The presence of the
1681                      sRGB chunk means that the pixel
1682                      data is in the sRGB color space.
1683                      This function also causes gAMA and
1684                      cHRM chunks with the specific values
1685                      that are consistent with sRGB to be
1686                      written.
1687
1688     png_set_iCCP(png_ptr, info_ptr, name, compression_type,
1689                       profile, proflen);
1690     name            - The profile name.
1691     compression     - The compression type; always PNG_COMPRESSION_TYPE_BASE
1692                       for PNG 1.0.  You may give NULL to this argument
1693                       to ignore it.
1694     profile         - International Color Consortium color profile
1695                       data. May contain NULs.
1696     proflen         - length of profile data in bytes.
1697
1698     png_set_sBIT(png_ptr, info_ptr, sig_bit);
1699     sig_bit        - the number of significant bits for
1700                      (PNG_INFO_sBIT) each of the gray, red,
1701                      green, and blue channels, whichever are
1702                      appropriate for the given color type
1703                      (png_color_16)
1704
1705     png_set_tRNS(png_ptr, info_ptr, trans, num_trans,
1706        trans_values);
1707     trans          - array of transparent entries for
1708                      palette (PNG_INFO_tRNS)
1709     trans_values   - graylevel or color sample values of
1710                      the single transparent color for
1711                      non-paletted images (PNG_INFO_tRNS)
1712     num_trans      - number of transparent entries
1713                      (PNG_INFO_tRNS)
1714
1715     png_set_hIST(png_ptr, info_ptr, hist);
1716                     (PNG_INFO_hIST)
1717     hist           - histogram of palette (array of
1718                      png_uint_16)
1719
1720     png_set_tIME(png_ptr, info_ptr, mod_time);
1721     mod_time       - time image was last modified
1722                      (PNG_VALID_tIME)
1723
1724     png_set_bKGD(png_ptr, info_ptr, background);
1725     background     - background color (PNG_VALID_bKGD)
1726
1727     png_set_text(png_ptr, info_ptr, text_ptr, num_text);
1728     text_ptr       - array of png_text holding image
1729                      comments
1730     text_ptr[i].compression - type of compression used
1731                  on "text" PNG_TEXT_COMPRESSION_NONE
1732                            PNG_TEXT_COMPRESSION_zTXt
1733                            PNG_ITXT_COMPRESSION_NONE
1734                            PNG_ITXT_COMPRESSION_zTXt
1735     text_ptr[i].key   - keyword for comment.  Must contain
1736                  1-79 characters.
1737     text_ptr[i].text  - text comments for current
1738                          keyword.  Can be NULL or empty.
1739     text_ptr[i].text_length - length of text string,
1740                  after decompression, 0 for iTXt
1741     text_ptr[i].itxt_length - length of itxt string,
1742                  after decompression, 0 for tEXt/zTXt
1743     text_ptr[i].lang  - language of comment (NULL or
1744                          empty for unknown).
1745     text_ptr[i].translated_keyword  - keyword in UTF-8 (NULL
1746                          or empty for unknown).
1747     num_text       - number of comments
1748
1749     png_set_sPLT(png_ptr, info_ptr, &palette_ptr, num_spalettes);
1750     palette_ptr    - array of png_sPLT_struct structures to be
1751                      added to the list of palettes in the info
1752                      structure.
1753     num_spalettes  - number of palette structures to be added.
1754
1755     png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
1756         unit_type);
1757     offset_x  - positive offset from the left
1758                      edge of the screen
1759     offset_y  - positive offset from the top
1760                      edge of the screen
1761     unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
1762
1763     png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
1764         unit_type);
1765     res_x       - pixels/unit physical resolution
1766                   in x direction
1767     res_y       - pixels/unit physical resolution
1768                   in y direction
1769     unit_type   - PNG_RESOLUTION_UNKNOWN,
1770                   PNG_RESOLUTION_METER
1771
1772     png_set_sCAL(png_ptr, info_ptr, unit, width, height)
1773     unit        - physical scale units (an integer)
1774     width       - width of a pixel in physical scale units
1775     height      - height of a pixel in physical scale units
1776                   (width and height are doubles)
1777
1778     png_set_sCAL_s(png_ptr, info_ptr, unit, width, height)
1779     unit        - physical scale units (an integer)
1780     width       - width of a pixel in physical scale units
1781     height      - height of a pixel in physical scale units
1782                  (width and height are strings like "2.54")
1783
1784     png_set_unknown_chunks(png_ptr, info_ptr, &unknowns, num_unknowns)
1785     unknowns          - array of png_unknown_chunk structures holding
1786                         unknown chunks
1787     unknowns[i].name  - name of unknown chunk
1788     unknowns[i].data  - data of unknown chunk
1789     unknowns[i].size  - size of unknown chunk's data
1790     unknowns[i].location - position to write chunk in file
1791                            0: do not write chunk
1792                            PNG_HAVE_IHDR: before PLTE
1793                            PNG_HAVE_PLTE: before IDAT
1794                            PNG_AFTER_IDAT: after IDAT
1795     The "location" member is set automatically according to
1796     what part of the output file has already been written.
1797     You can change its value after calling png_set_unknown_chunks()
1798     as demonstrated in pngtest.c.  Within each of the "locations",
1799     the chunks are sequenced according to their position in the
1800     structure (that is, the value of "i", which is the order in which
1801     the chunk was either read from the input file or defined with
1802     png_set_unknown_chunks).
1803
1804 A quick word about text and num_text.  text is an array of png_text
1805 structures.  num_text is the number of valid structures in the array.
1806 Each png_text structure holds a language code, a keyword, a text value,
1807 and a compression type.
1808
1809 The compression types have the same valid numbers as the compression
1810 types of the image data.  Currently, the only valid number is zero.
1811 However, you can store text either compressed or uncompressed, unlike
1812 images, which always have to be compressed.  So if you don't want the
1813 text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
1814 Because tEXt and zTXt chunks don't have a language field, if you
1815 specify PNG_TEXT_COMPRESSION_NONE or PNG_TEXT_COMPRESSION_zTXt
1816 any language code or translated keyword will not be written out.
1817
1818 Until text gets around 1000 bytes, it is not worth compressing it.
1819 After the text has been written out to the file, the compression type
1820 is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
1821 so that it isn't written out again at the end (in case you are calling
1822 png_write_end() with the same struct.
1823
1824 The keywords that are given in the PNG Specification are:
1825
1826     Title            Short (one line) title or
1827                      caption for image
1828     Author           Name of image's creator
1829     Description      Description of image (possibly long)
1830     Copyright        Copyright notice
1831     Creation Time    Time of original image creation
1832                      (usually RFC 1123 format, see below)
1833     Software         Software used to create the image
1834     Disclaimer       Legal disclaimer
1835     Warning          Warning of nature of content
1836     Source           Device used to create the image
1837     Comment          Miscellaneous comment; conversion
1838                      from other image format
1839
1840 The keyword-text pairs work like this.  Keywords should be short
1841 simple descriptions of what the comment is about.  Some typical
1842 keywords are found in the PNG specification, as is some recommendations
1843 on keywords.  You can repeat keywords in a file.  You can even write
1844 some text before the image and some after.  For example, you may want
1845 to put a description of the image before the image, but leave the
1846 disclaimer until after, so viewers working over modem connections
1847 don't have to wait for the disclaimer to go over the modem before
1848 they start seeing the image.  Finally, keywords should be full
1849 words, not abbreviations.  Keywords and text are in the ISO 8859-1
1850 (Latin-1) character set (a superset of regular ASCII) and can not
1851 contain NUL characters, and should not contain control or other
1852 unprintable characters.  To make the comments widely readable, stick
1853 with basic ASCII, and avoid machine specific character set extensions
1854 like the IBM-PC character set.  The keyword must be present, but
1855 you can leave off the text string on non-compressed pairs.
1856 Compressed pairs must have a text string, as only the text string
1857 is compressed anyway, so the compression would be meaningless.
1858
1859 PNG supports modification time via the png_time structure.  Two
1860 conversion routines are provided, png_convert_from_time_t() for
1861 time_t and png_convert_from_struct_tm() for struct tm.  The
1862 time_t routine uses gmtime().  You don't have to use either of
1863 these, but if you wish to fill in the png_time structure directly,
1864 you should provide the time in universal time (GMT) if possible
1865 instead of your local time.  Note that the year number is the full
1866 year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and
1867 that months start with 1.
1868
1869 If you want to store the time of the original image creation, you should
1870 use a plain tEXt chunk with the "Creation Time" keyword.  This is
1871 necessary because the "creation time" of a PNG image is somewhat vague,
1872 depending on whether you mean the PNG file, the time the image was
1873 created in a non-PNG format, a still photo from which the image was
1874 scanned, or possibly the subject matter itself.  In order to facilitate
1875 machine-readable dates, it is recommended that the "Creation Time"
1876 tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"),
1877 although this isn't a requirement.  Unlike the tIME chunk, the
1878 "Creation Time" tEXt chunk is not expected to be automatically changed
1879 by the software.  To facilitate the use of RFC 1123 dates, a function
1880 png_convert_to_rfc1123(png_timep) is provided to convert from PNG
1881 time to an RFC 1123 format string.
1882
1883 Writing unknown chunks
1884
1885 You can use the png_set_unknown_chunks function to queue up chunks
1886 for writing.  You give it a chunk name, raw data, and a size; that's
1887 all there is to it.  The chunks will be written by the next following
1888 png_write_info_before_PLTE, png_write_info, or png_write_end function.
1889 Any chunks previously read into the info structure's unknown-chunk
1890 list will also be written out in a sequence that satisfies the PNG
1891 specification's ordering rules.
1892
1893 The high-level write interface
1894
1895 At this point there are two ways to proceed; through the high-level
1896 write interface, or through a sequence of low-level write operations.
1897 You can use the high-level interface if your image data is present
1898 in the info structure.  All defined output
1899 transformations are permitted, enabled by the following masks.
1900
1901     PNG_TRANSFORM_IDENTITY      No transformation
1902     PNG_TRANSFORM_PACKING       Pack 1, 2 and 4-bit samples
1903     PNG_TRANSFORM_PACKSWAP      Change order of packed pixels to LSB first
1904     PNG_TRANSFORM_INVERT_MONO   Invert monochrome images
1905     PNG_TRANSFORM_SHIFT         Normalize pixels to the sBIT depth
1906     PNG_TRANSFORM_BGR           Flip RGB to BGR, RGBA to BGRA
1907     PNG_TRANSFORM_SWAP_ALPHA    Flip RGBA to ARGB or GA to AG
1908     PNG_TRANSFORM_INVERT_ALPHA  Change alpha from opacity to transparency
1909     PNG_TRANSFORM_SWAP_ENDIAN   Byte-swap 16-bit samples
1910     PNG_TRANSFORM_STRIP_FILLER  Strip out filler bytes.
1911
1912 If you have valid image data in the info structure (you can use
1913 png_set_rows() to put image data in the info structure), simply do this:
1914
1915     png_write_png(png_ptr, info_ptr, png_transforms, NULL)
1916
1917 where png_transforms is an integer containing the logical OR of some set of
1918 transformation flags.  This call is equivalent to png_write_info(),
1919 followed the set of transformations indicated by the transform mask,
1920 then png_write_image(), and finally png_write_end().
1921
1922 (The final parameter of this call is not yet used.  Someday it might point
1923 to transformation parameters required by some future output transform.)
1924
1925 The low-level write interface
1926
1927 If you are going the low-level route instead, you are now ready to
1928 write all the file information up to the actual image data.  You do
1929 this with a call to png_write_info().
1930
1931     png_write_info(png_ptr, info_ptr);
1932
1933 Note that there is one transformation you may need to do before
1934 png_write_info().  In PNG files, the alpha channel in an image is the
1935 level of opacity.  If your data is supplied as a level of
1936 transparency, you can invert the alpha channel before you write it, so
1937 that 0 is fully transparent and 255 (in 8-bit or paletted images) or
1938 65535 (in 16-bit images) is fully opaque, with
1939
1940     png_set_invert_alpha(png_ptr);
1941
1942 This must appear before png_write_info() instead of later with the
1943 other transformations because in the case of paletted images the tRNS
1944 chunk data has to be inverted before the tRNS chunk is written.  If
1945 your image is not a paletted image, the tRNS data (which in such cases
1946 represents a single color to be rendered as transparent) won't need to
1947 be changed, and you can safely do this transformation after your
1948 png_write_info() call.
1949
1950 If you need to write a private chunk that you want to appear before
1951 the PLTE chunk when PLTE is present, you can write the PNG info in
1952 two steps, and insert code to write your own chunk between them:
1953
1954     png_write_info_before_PLTE(png_ptr, info_ptr);
1955     png_set_unknown_chunks(png_ptr, info_ptr, ...);
1956     png_write_info(png_ptr, info_ptr);
1957
1958 After you've written the file information, you can set up the library
1959 to handle any special transformations of the image data.  The various
1960 ways to transform the data will be described in the order that they
1961 should occur.  This is important, as some of these change the color
1962 type and/or bit depth of the data, and some others only work on
1963 certain color types and bit depths.  Even though each transformation
1964 checks to see if it has data that it can do something with, you should
1965 make sure to only enable a transformation if it will be valid for the
1966 data.  For example, don't swap red and blue on grayscale data.
1967
1968 PNG files store RGB pixels packed into 3 or 6 bytes.  This code tells
1969 the library to strip input data that has 4 or 8 bytes per pixel down
1970 to 3 or 6 bytes (or strip 2 or 4-byte grayscale+filler data to 1 or 2
1971 bytes per pixel).
1972
1973     png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1974
1975 where the 0 is unused, and the location is either PNG_FILLER_BEFORE or
1976 PNG_FILLER_AFTER, depending upon whether the filler byte in the pixel
1977 is stored XRGB or RGBX.
1978
1979 PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
1980 they can, resulting in, for example, 8 pixels per byte for 1 bit files.
1981 If the data is supplied at 1 pixel per byte, use this code, which will
1982 correctly pack the pixels into a single byte:
1983
1984     png_set_packing(png_ptr);
1985
1986 PNG files reduce possible bit depths to 1, 2, 4, 8, and 16.  If your
1987 data is of another bit depth, you can write an sBIT chunk into the
1988 file so that decoders can recover the original data if desired.
1989
1990     /* Set the true bit depth of the image data */
1991     if (color_type & PNG_COLOR_MASK_COLOR)
1992     {
1993         sig_bit.red = true_bit_depth;
1994         sig_bit.green = true_bit_depth;
1995         sig_bit.blue = true_bit_depth;
1996     }
1997     else
1998     {
1999         sig_bit.gray = true_bit_depth;
2000     }
2001     if (color_type & PNG_COLOR_MASK_ALPHA)
2002     {
2003         sig_bit.alpha = true_bit_depth;
2004     }
2005
2006     png_set_sBIT(png_ptr, info_ptr, &sig_bit);
2007
2008 If the data is stored in the row buffer in a bit depth other than
2009 one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG),
2010 this will scale the values to appear to be the correct bit depth as
2011 is required by PNG.
2012
2013     png_set_shift(png_ptr, &sig_bit);
2014
2015 PNG files store 16 bit pixels in network byte order (big-endian,
2016 ie. most significant bits first).  This code would be used if they are
2017 supplied the other way (little-endian, i.e. least significant bits
2018 first, the way PCs store them):
2019
2020     if (bit_depth > 8)
2021        png_set_swap(png_ptr);
2022
2023 If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
2024 need to change the order the pixels are packed into bytes, you can use:
2025
2026     if (bit_depth < 8)
2027        png_set_packswap(png_ptr);
2028
2029 PNG files store 3 color pixels in red, green, blue order.  This code
2030 would be used if they are supplied as blue, green, red:
2031
2032     png_set_bgr(png_ptr);
2033
2034 PNG files describe monochrome as black being zero and white being
2035 one. This code would be used if the pixels are supplied with this reversed
2036 (black being one and white being zero):
2037
2038     png_set_invert_mono(png_ptr);
2039
2040 Finally, you can write your own transformation function if none of
2041 the existing ones meets your needs.  This is done by setting a callback
2042 with
2043
2044     png_set_write_user_transform_fn(png_ptr,
2045        write_transform_fn);
2046
2047 You must supply the function
2048
2049     void write_transform_fn(png_ptr ptr, row_info_ptr
2050        row_info, png_bytep data)
2051
2052 See pngtest.c for a working example.  Your function will be called
2053 before any of the other transformations are processed.
2054
2055 You can also set up a pointer to a user structure for use by your
2056 callback function.
2057
2058     png_set_user_transform_info(png_ptr, user_ptr, 0, 0);
2059
2060 The user_channels and user_depth parameters of this function are ignored
2061 when writing; you can set them to zero as shown.
2062
2063 You can retrieve the pointer via the function png_get_user_transform_ptr().
2064 For example:
2065
2066     voidp write_user_transform_ptr =
2067        png_get_user_transform_ptr(png_ptr);
2068
2069 It is possible to have libpng flush any pending output, either manually,
2070 or automatically after a certain number of lines have been written.  To
2071 flush the output stream a single time call:
2072
2073     png_write_flush(png_ptr);
2074
2075 and to have libpng flush the output stream periodically after a certain
2076 number of scanlines have been written, call:
2077
2078     png_set_flush(png_ptr, nrows);
2079
2080 Note that the distance between rows is from the last time png_write_flush()
2081 was called, or the first row of the image if it has never been called.
2082 So if you write 50 lines, and then png_set_flush 25, it will flush the
2083 output on the next scanline, and every 25 lines thereafter, unless
2084 png_write_flush() is called before 25 more lines have been written.
2085 If nrows is too small (less than about 10 lines for a 640 pixel wide
2086 RGB image) the image compression may decrease noticeably (although this
2087 may be acceptable for real-time applications).  Infrequent flushing will
2088 only degrade the compression performance by a few percent over images
2089 that do not use flushing.
2090
2091 Writing the image data
2092
2093 That's it for the transformations.  Now you can write the image data.
2094 The simplest way to do this is in one function call.  If you have the
2095 whole image in memory, you can just call png_write_image() and libpng
2096 will write the image.  You will need to pass in an array of pointers to
2097 each row.  This function automatically handles interlacing, so you don't
2098 need to call png_set_interlace_handling() or call this function multiple
2099 times, or any of that other stuff necessary with png_write_rows().
2100
2101     png_write_image(png_ptr, row_pointers);
2102
2103 where row_pointers is:
2104
2105     png_byte *row_pointers[height];
2106
2107 You can point to void or char or whatever you use for pixels.
2108
2109 If you don't want to write the whole image at once, you can
2110 use png_write_rows() instead.  If the file is not interlaced,
2111 this is simple:
2112
2113     png_write_rows(png_ptr, row_pointers,
2114        number_of_rows);
2115
2116 row_pointers is the same as in the png_write_image() call.
2117
2118 If you are just writing one row at a time, you can do this with
2119 a single row_pointer instead of an array of row_pointers:
2120
2121     png_bytep row_pointer = row;
2122
2123     png_write_row(png_ptr, row_pointer);
2124
2125 When the file is interlaced, things can get a good deal more
2126 complicated.  The only currently (as of the PNG Specification
2127 version 1.2, dated July 1999) defined interlacing scheme for PNG files
2128 is the "Adam7" interlace scheme, that breaks down an
2129 image into seven smaller images of varying size.  libpng will build
2130 these images for you, or you can do them yourself.  If you want to
2131 build them yourself, see the PNG specification for details of which
2132 pixels to write when.
2133
2134 If you don't want libpng to handle the interlacing details, just
2135 use png_set_interlace_handling() and call png_write_rows() the
2136 correct number of times to write all seven sub-images.
2137
2138 If you want libpng to build the sub-images, call this before you start
2139 writing any rows:
2140
2141     number_of_passes =
2142        png_set_interlace_handling(png_ptr);
2143
2144 This will return the number of passes needed.  Currently, this
2145 is seven, but may change if another interlace type is added.
2146
2147 Then write the complete image number_of_passes times.
2148
2149     png_write_rows(png_ptr, row_pointers,
2150        number_of_rows);
2151
2152 As some of these rows are not used, and thus return immediately,
2153 you may want to read about interlacing in the PNG specification,
2154 and only update the rows that are actually used.
2155
2156 Finishing a sequential write
2157
2158 After you are finished writing the image, you should finish writing
2159 the file.  If you are interested in writing comments or time, you should
2160 pass an appropriately filled png_info pointer.  If you are not interested,
2161 you can pass NULL.
2162
2163     png_write_end(png_ptr, info_ptr);
2164
2165 When you are done, you can free all memory used by libpng like this:
2166
2167     png_destroy_write_struct(&png_ptr, &info_ptr);
2168
2169 It is also possible to individually free the info_ptr members that
2170 point to libpng-allocated storage with the following function:
2171
2172     png_free_data(png_ptr, info_ptr, mask, n)
2173     mask  - identifies data to be freed, a mask
2174             containing the logical OR of one or
2175             more of
2176               PNG_FREE_PLTE, PNG_FREE_TRNS,
2177               PNG_FREE_HIST, PNG_FREE_ICCP,
2178               PNG_FREE_PCAL, PNG_FREE_ROWS,
2179               PNG_FREE_SCAL, PNG_FREE_SPLT,
2180               PNG_FREE_TEXT, PNG_FREE_UNKN,
2181             or simply PNG_FREE_ALL
2182     n     - sequence number of item to be freed
2183             (-1 for all items)
2184
2185 This function may be safely called when the relevant storage has
2186 already been freed, or has not yet been allocated, or was allocated
2187 by the user  and not by libpng,  and will in those
2188 cases do nothing.  The "n" parameter is ignored if only one item
2189 of the selected data type, such as PLTE, is allowed.  If "n" is not
2190 -1, and multiple items are allowed for the data type identified in
2191 the mask, such as text or sPLT, only the n'th item is freed.
2192
2193 If you allocated data such as a palette that you passed
2194 in to libpng with png_set_*, you must not free it until just before the call to
2195 png_destroy_write_struct().
2196
2197 The default behavior is only to free data that was allocated internally
2198 by libpng.  This can be changed, so that libpng will not free the data,
2199 or so that it will free data that was allocated by the user with png_malloc()
2200 or png_zalloc() and passed in via a png_set_*() function, with
2201
2202     png_data_freer(png_ptr, info_ptr, freer, mask)
2203     mask   - which data elements are affected
2204              same choices as in png_free_data()
2205     freer  - one of
2206                PNG_DESTROY_WILL_FREE_DATA
2207                PNG_SET_WILL_FREE_DATA
2208                PNG_USER_WILL_FREE_DATA
2209
2210 For example, to transfer responsibility for some data from a read structure
2211 to a write structure, you could use
2212
2213     png_data_freer(read_ptr, read_info_ptr,
2214        PNG_USER_WILL_FREE_DATA,
2215        PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
2216     png_data_freer(write_ptr, write_info_ptr,
2217        PNG_DESTROY_WILL_FREE_DATA,
2218        PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
2219
2220 thereby briefly reassigning responsibility for freeing to the user but
2221 immediately afterwards reassigning it once more to the write_destroy
2222 function.  Having done this, it would then be safe to destroy the read
2223 structure and continue to use the PLTE, tRNS, and hIST data in the write
2224 structure.
2225
2226 This function only affects data that has already been allocated.
2227 You can call this function before calling after the png_set_*() functions
2228 to control whether the user or png_destroy_*() is supposed to free the data.
2229 When the user assumes responsibility for libpng-allocated data, the
2230 application must use
2231 png_free() to free it, and when the user transfers responsibility to libpng
2232 for data that the user has allocated, the user must have used png_malloc()
2233 or png_zalloc() to allocate it.
2234
2235 If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
2236 separately, do not transfer responsibility for freeing text_ptr to libpng,
2237 because when libpng fills a png_text structure it combines these members with
2238 the key member, and png_free_data() will free only text_ptr.key.  Similarly,
2239 if you transfer responsibility for free'ing text_ptr from libpng to your
2240 application, your application must not separately free those members.
2241 For a more compact example of writing a PNG image, see the file example.c.
2242
2243 V. Modifying/Customizing libpng:
2244
2245 There are three issues here.  The first is changing how libpng does
2246 standard things like memory allocation, input/output, and error handling.
2247 The second deals with more complicated things like adding new chunks,
2248 adding new transformations, and generally changing how libpng works.
2249 Both of those are compile-time issues; that is, they are generally
2250 determined at the time the code is written, and there is rarely a need
2251 to provide the user with a means of changing them.  The third is a
2252 run-time issue:  choosing between and/or tuning one or more alternate
2253 versions of computationally intensive routines; specifically, optimized
2254 assembly-language (and therefore compiler- and platform-dependent)
2255 versions.
2256
2257 Memory allocation, input/output, and error handling
2258
2259 All of the memory allocation, input/output, and error handling in libpng
2260 goes through callbacks that are user-settable.  The default routines are
2261 in pngmem.c, pngrio.c, pngwio.c, and pngerror.c, respectively.  To change
2262 these functions, call the appropriate png_set_*_fn() function.
2263
2264 Memory allocation is done through the functions png_malloc(), png_zalloc(),
2265 and png_free().  These currently just call the standard C functions.  If
2266 your pointers can't access more then 64K at a time, you will want to set
2267 MAXSEG_64K in zlib.h.  Since it is unlikely that the method of handling
2268 memory allocation on a platform will change between applications, these
2269 functions must be modified in the library at compile time.  If you prefer
2270 to use a different method of allocating and freeing data, you can use
2271
2272     png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
2273       malloc_fn, png_free_ptr free_fn)
2274
2275 This function also provides a void pointer that can be retrieved via
2276
2277     mem_ptr=png_get_mem_ptr(png_ptr);
2278
2279 Your replacement memory functions must have prototypes as follows:
2280
2281     png_voidp malloc_fn(png_structp png_ptr, png_uint_32 size);
2282     void free_fn(png_structp png_ptr, png_voidp ptr);
2283
2284 Input/Output in libpng is done through png_read() and png_write(),
2285 which currently just call fread() and fwrite().  The FILE * is stored in
2286 png_struct and is initialized via png_init_io().  If you wish to change
2287 the method of I/O, the library supplies callbacks that you can set
2288 through the function png_set_read_fn() and png_set_write_fn() at run
2289 time, instead of calling the png_init_io() function.  These functions
2290 also provide a void pointer that can be retrieved via the function
2291 png_get_io_ptr().  For example:
2292
2293     png_set_read_fn(png_structp read_ptr,
2294         voidp read_io_ptr, png_rw_ptr read_data_fn)
2295
2296     png_set_write_fn(png_structp write_ptr,
2297         voidp write_io_ptr, png_rw_ptr write_data_fn,
2298         png_flush_ptr output_flush_fn);
2299
2300     voidp read_io_ptr = png_get_io_ptr(read_ptr);
2301     voidp write_io_ptr = png_get_io_ptr(write_ptr);
2302
2303 The replacement I/O functions must have prototypes as follows:
2304
2305     void user_read_data(png_structp png_ptr,
2306         png_bytep data, png_uint_32 length);
2307     void user_write_data(png_structp png_ptr,
2308         png_bytep data, png_uint_32 length);
2309     void user_flush_data(png_structp png_ptr);
2310
2311 Supplying NULL for the read, write, or flush functions sets them back
2312 to using the default C stream functions.  It is an error to read from
2313 a write stream, and vice versa.
2314
2315 Error handling in libpng is done through png_error() and png_warning().
2316 Errors handled through png_error() are fatal, meaning that png_error()
2317 should never return to its caller.  Currently, this is handled via
2318 setjmp() and longjmp() (unless you have compiled libpng with
2319 PNG_SETJMP_NOT_SUPPORTED, in which case it is handled via PNG_ABORT()),
2320 but you could change this to do things like exit() if you should wish.
2321
2322 On non-fatal errors, png_warning() is called
2323 to print a warning message, and then control returns to the calling code.
2324 By default png_error() and png_warning() print a message on stderr via
2325 fprintf() unless the library is compiled with PNG_NO_CONSOLE_IO defined
2326 (because you don't want the messages) or PNG_NO_STDIO defined (because
2327 fprintf() isn't available).  If you wish to change the behavior of the error
2328 functions, you will need to set up your own message callbacks.  These
2329 functions are normally supplied at the time that the png_struct is created.
2330 It is also possible to redirect errors and warnings to your own replacement
2331 functions after png_create_*_struct() has been called by calling:
2332
2333     png_set_error_fn(png_structp png_ptr,
2334         png_voidp error_ptr, png_error_ptr error_fn,
2335         png_error_ptr warning_fn);
2336
2337     png_voidp error_ptr = png_get_error_ptr(png_ptr);
2338
2339 If NULL is supplied for either error_fn or warning_fn, then the libpng
2340 default function will be used, calling fprintf() and/or longjmp() if a
2341 problem is encountered.  The replacement error functions should have
2342 parameters as follows:
2343
2344     void user_error_fn(png_structp png_ptr,
2345         png_const_charp error_msg);
2346     void user_warning_fn(png_structp png_ptr,
2347         png_const_charp warning_msg);
2348
2349 The motivation behind using setjmp() and longjmp() is the C++ throw and
2350 catch exception handling methods.  This makes the code much easier to write,
2351 as there is no need to check every return code of every function call.
2352 However, there are some uncertainties about the status of local variables
2353 after a longjmp, so the user may want to be careful about doing anything after
2354 setjmp returns non-zero besides returning itself.  Consult your compiler
2355 documentation for more details.  For an alternative approach, you may wish
2356 to use the "cexcept" facility (see http://cexcept.sourceforge.net).
2357
2358 Custom chunks
2359
2360 If you need to read or write custom chunks, you may need to get deeper
2361 into the libpng code.  The library now has mechanisms for storing
2362 and writing chunks of unknown type; you can even declare callbacks
2363 for custom chunks.  Hoewver, this may not be good enough if the
2364 library code itself needs to know about interactions between your
2365 chunk and existing `intrinsic' chunks.
2366
2367 If you need to write a new intrinsic chunk, first read the PNG
2368 specification. Acquire a first level of
2369 understanding of how it works.  Pay particular attention to the
2370 sections that describe chunk names, and look at how other chunks were
2371 designed, so you can do things similarly.  Second, check out the
2372 sections of libpng that read and write chunks.  Try to find a chunk
2373 that is similar to yours and use it as a template.  More details can
2374 be found in the comments inside the code.  It is best to handle unknown
2375 chunks in a generic method, via callback functions, instead of by
2376 modifying libpng functions.
2377
2378 If you wish to write your own transformation for the data, look through
2379 the part of the code that does the transformations, and check out some of
2380 the simpler ones to get an idea of how they work.  Try to find a similar
2381 transformation to the one you want to add and copy off of it.  More details
2382 can be found in the comments inside the code itself.
2383
2384 Configuring for 16 bit platforms
2385
2386 You will want to look into zconf.h to tell zlib (and thus libpng) that
2387 it cannot allocate more then 64K at a time.  Even if you can, the memory
2388 won't be accessible.  So limit zlib and libpng to 64K by defining MAXSEG_64K.
2389
2390 Configuring for DOS
2391
2392 For DOS users who only have access to the lower 640K, you will
2393 have to limit zlib's memory usage via a png_set_compression_mem_level()
2394 call.  See zlib.h or zconf.h in the zlib library for more information.
2395
2396 Configuring for Medium Model
2397
2398 Libpng's support for medium model has been tested on most of the popular
2399 compilers.  Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
2400 defined, and FAR gets defined to far in pngconf.h, and you should be
2401 all set.  Everything in the library (except for zlib's structure) is
2402 expecting far data.  You must use the typedefs with the p or pp on
2403 the end for pointers (or at least look at them and be careful).  Make
2404 note that the rows of data are defined as png_bytepp, which is an
2405 unsigned char far * far *.
2406
2407 Configuring for gui/windowing platforms:
2408
2409 You will need to write new error and warning functions that use the GUI
2410 interface, as described previously, and set them to be the error and
2411 warning functions at the time that png_create_*_struct() is called,
2412 in order to have them available during the structure initialization.
2413 They can be changed later via png_set_error_fn().  On some compilers,
2414 you may also have to change the memory allocators (png_malloc, etc.).
2415
2416 Configuring for compiler xxx:
2417
2418 All includes for libpng are in pngconf.h.  If you need to add/change/delete
2419 an include, this is the place to do it.  The includes that are not
2420 needed outside libpng are protected by the PNG_INTERNAL definition,
2421 which is only defined for those routines inside libpng itself.  The
2422 files in libpng proper only include png.h, which includes pngconf.h.
2423
2424 Configuring zlib:
2425
2426 There are special functions to configure the compression.  Perhaps the
2427 most useful one changes the compression level, which currently uses
2428 input compression values in the range 0 - 9.  The library normally
2429 uses the default compression level (Z_DEFAULT_COMPRESSION = 6).  Tests
2430 have shown that for a large majority of images, compression values in
2431 the range 3-6 compress nearly as well as higher levels, and do so much
2432 faster.  For online applications it may be desirable to have maximum speed
2433 (Z_BEST_SPEED = 1).  With versions of zlib after v0.99, you can also
2434 specify no compression (Z_NO_COMPRESSION = 0), but this would create
2435 files larger than just storing the raw bitmap.  You can specify the
2436 compression level by calling:
2437
2438     png_set_compression_level(png_ptr, level);
2439
2440 Another useful one is to reduce the memory level used by the library.
2441 The memory level defaults to 8, but it can be lowered if you are
2442 short on memory (running DOS, for example, where you only have 640K).
2443
2444     png_set_compression_mem_level(png_ptr, level);
2445
2446 The other functions are for configuring zlib.  They are not recommended
2447 for normal use and may result in writing an invalid PNG file.  See
2448 zlib.h for more information on what these mean.
2449
2450     png_set_compression_strategy(png_ptr,
2451         strategy);
2452     png_set_compression_window_bits(png_ptr,
2453         window_bits);
2454     png_set_compression_method(png_ptr, method);
2455     png_set_compression_buffer_size(png_ptr, size);
2456
2457 Controlling row filtering
2458
2459 If you want to control whether libpng uses filtering or not, which
2460 filters are used, and how it goes about picking row filters, you
2461 can call one of these functions.  The selection and configuration
2462 of row filters can have a significant impact on the size and
2463 encoding speed and a somewhat lesser impact on the decoding speed
2464 of an image.  Filtering is enabled by default for RGB and grayscale
2465 images (with and without alpha), but not for paletted images nor
2466 for any images with bit depths less than 8 bits/pixel.
2467
2468 The 'method' parameter sets the main filtering method, which is
2469 currently only '0' in the PNG 1.2 specification.  The 'filters'
2470 parameter sets which filter(s), if any, should be used for each
2471 scanline.  Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
2472 to turn filtering on and off, respectively.
2473
2474 Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
2475 PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
2476 ORed together with '|' to specify one or more filters to use.
2477 These filters are described in more detail in the PNG specification.  If
2478 you intend to change the filter type during the course of writing
2479 the image, you should start with flags set for all of the filters
2480 you intend to use so that libpng can initialize its internal
2481 structures appropriately for all of the filter types.
2482
2483     filters = PNG_FILTER_NONE | PNG_FILTER_SUB
2484               PNG_FILTER_UP | PNG_FILTER_AVE |
2485               PNG_FILTER_PAETH | PNG_ALL_FILTERS;
2486     or
2487     filters = one of PNG_FILTER_VALUE_NONE,
2488               PNG_FILTER_VALUE_SUB, PNG_FILTER_VALUE_UP,
2489               PNG_FILTER_VALUE_AVE, PNG_FILTER_VALUE_PAETH
2490
2491     png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
2492        filters);
2493               The second parameter can also be PNG_INTRAPIXEL_DIFFERENCING
2494               if you are writing a PNG to be embedded in a MNG
2495               datastream.  This parameter must be the same as the
2496               value of filter_method used in png_set_IHDR().
2497
2498 It is also possible to influence how libpng chooses from among the
2499 available filters.  This is done in two ways - by telling it how
2500 important it is to keep the same filter for successive rows, and
2501 by telling it the relative computational costs of the filters.
2502
2503     double weights[3] = {1.5, 1.3, 1.1},
2504        costs[PNG_FILTER_VALUE_LAST] =
2505        {1.0, 1.3, 1.3, 1.5, 1.7};
2506
2507     png_set_filter_selection(png_ptr,
2508        PNG_FILTER_SELECTION_WEIGHTED, 3,
2509        weights, costs);
2510
2511 The weights are multiplying factors that indicate to libpng that the
2512 row filter should be the same for successive rows unless another row filter
2513 is that many times better than the previous filter.  In the above example,
2514 if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
2515 "sum of absolute differences" 1.5 x 1.3 times higher than other filters
2516 and still be chosen, while the NONE filter could have a sum 1.1 times
2517 higher than other filters and still be chosen.  Unspecified weights are
2518 taken to be 1.0, and the specified weights should probably be declining
2519 like those above in order to emphasize recent filters over older filters.
2520
2521 The filter costs specify for each filter type a relative decoding cost
2522 to be considered when selecting row filters.  This means that filters
2523 with higher costs are less likely to be chosen over filters with lower
2524 costs, unless their "sum of absolute differences" is that much smaller.
2525 The costs do not necessarily reflect the exact computational speeds of
2526 the various filters, since this would unduly influence the final image
2527 size.
2528
2529 Note that the numbers above were invented purely for this example and
2530 are given only to help explain the function usage.  Little testing has
2531 been done to find optimum values for either the costs or the weights.
2532
2533 Removing unwanted object code
2534
2535 There are a bunch of #define's in pngconf.h that control what parts of
2536 libpng are compiled.  All the defines end in _SUPPORTED.  If you are
2537 never going to use a capability, you can change the #define to #undef
2538 before recompiling libpng and save yourself code and data space, or
2539 you can turn off individual capabilities with defines that begin with
2540 PNG_NO_.
2541
2542 You can also turn all of the transforms and ancillary chunk capabilities
2543 off en masse with compiler directives that define
2544 PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS,
2545 or all four,
2546 along with directives to turn on any of the capabilities that you do
2547 want.  The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable
2548 the extra transformations but still leave the library fully capable of reading
2549 and writing PNG files with all known public chunks
2550 Use of the PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive
2551 produces a library that is incapable of reading or writing ancillary chunks.
2552 If you are not using the progressive reading capability, you can
2553 turn that off with PNG_NO_PROGRESSIVE_READ (don't confuse
2554 this with the INTERLACING capability, which you'll still have).
2555
2556 All the reading and writing specific code are in separate files, so the
2557 linker should only grab the files it needs.  However, if you want to
2558 make sure, or if you are building a stand alone library, all the
2559 reading files start with pngr and all the writing files start with
2560 pngw.  The files that don't match either (like png.c, pngtrans.c, etc.)
2561 are used for both reading and writing, and always need to be included.
2562 The progressive reader is in pngpread.c
2563
2564 If you are creating or distributing a dynamically linked library (a .so
2565 or DLL file), you should not remove or disable any parts of the library,
2566 as this will cause applications linked with different versions of the
2567 library to fail if they call functions not available in your library.
2568 The size of the library itself should not be an issue, because only
2569 those sections that are actually used will be loaded into memory.
2570
2571 Requesting debug printout
2572
2573 The macro definition PNG_DEBUG can be used to request debugging
2574 printout.  Set it to an integer value in the range 0 to 3.  Higher
2575 numbers result in increasing amounts of debugging information.  The
2576 information is printed to the "stderr" file, unless another file
2577 name is specified in the PNG_DEBUG_FILE macro definition.
2578
2579 When PNG_DEBUG > 0, the following functions (macros) become available:
2580
2581    png_debug(level, message)
2582    png_debug1(level, message, p1)
2583    png_debug2(level, message, p1, p2)
2584
2585 in which "level" is compared to PNG_DEBUG to decide whether to print
2586 the message, "message" is the formatted string to be printed,
2587 and p1 and p2 are parameters that are to be embedded in the string
2588 according to printf-style formatting directives.  For example,
2589
2590    png_debug1(2, "foo=%d\n", foo);
2591
2592 is expanded to
2593
2594    if(PNG_DEBUG > 2)
2595      fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
2596
2597 When PNG_DEBUG is defined but is zero, the macros aren't defined, but you
2598 can still use PNG_DEBUG to control your own debugging:
2599
2600    #ifdef PNG_DEBUG
2601        fprintf(stderr, ...
2602    #endif
2603
2604 When PNG_DEBUG = 1, the macros are defined, but only png_debug statements
2605 having level = 0 will be printed.  There aren't any such statements in
2606 this version of libpng, but if you insert some they will be printed.
2607
2608
2609 VI.  MNG support
2610
2611 The MNG specification (available at http://www.libpng.org/pub/mng) allows
2612 certain extensions to PNG for PNG images that are embedded in MNG datastreams.
2613 Libpng can support some of these extensions.  To enable them, use the
2614 png_permit_mng_features() function:
2615
2616    feature_set = png_permit_mng_features(png_ptr, mask)
2617    mask is a png_uint_32 containing the logical OR of the
2618         features you want to enable.  These include
2619         PNG_FLAG_MNG_EMPTY_PLTE
2620         PNG_FLAG_MNG_FILTER_64
2621         PNG_ALL_MNG_FEATURES
2622    feature_set is a png_32_uint that is the logical AND of
2623       your mask with the set of MNG features that is
2624       supported by the version of libpng that you are using.
2625
2626 It is an error to use this function when reading or writing a standalone
2627 PNG file with the PNG 8-byte signature.  The PNG datastream must be wrapped
2628 in a MNG datastream.  As a minimum, it must have the MNG 8-byte signature
2629 and the MHDR and MEND chunks.  Libpng does not provide support for these
2630 or any other MNG chunks; your application must provide its own support for
2631 them.  You may wish to consider using libmng (available at
2632 http://www.libmng.com) instead.
2633
2634 VII.  Changes to Libpng from version 0.88
2635
2636 It should be noted that versions of libpng later than 0.96 are not
2637 distributed by the original libpng author, Guy Schalnat, nor by
2638 Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
2639 distributed versions 0.89 through 0.96, but rather by another member
2640 of the original PNG Group, Glenn Randers-Pehrson.  Guy and Andreas are
2641 still alive and well, but they have moved on to other things.
2642
2643 The old libpng functions png_read_init(), png_write_init(),
2644 png_info_init(), png_read_destroy(), and png_write_destory() have been
2645 moved to PNG_INTERNAL in version 0.95 to discourage their use.  These
2646 functions will be removed from libpng version 2.0.0.
2647
2648 The preferred method of creating and initializing the libpng structures is
2649 via the png_create_read_struct(), png_create_write_struct(), and
2650 png_create_info_struct() because they isolate the size of the structures
2651 from the application, allow version error checking, and also allow the
2652 use of custom error handling routines during the initialization, which
2653 the old functions do not.  The functions png_read_destroy() and
2654 png_write_destroy() do not actually free the memory that libpng
2655 allocated for these structs, but just reset the data structures, so they
2656 can be used instead of png_destroy_read_struct() and
2657 png_destroy_write_struct() if you feel there is too much system overhead
2658 allocating and freeing the png_struct for each image read.
2659
2660 Setting the error callbacks via png_set_message_fn() before
2661 png_read_init() as was suggested in libpng-0.88 is no longer supported
2662 because this caused applications that do not use custom error functions
2663 to fail if the png_ptr was not initialized to zero.  It is still possible
2664 to set the error callbacks AFTER png_read_init(), or to change them with
2665 png_set_error_fn(), which is essentially the same function, but with a new
2666 name to force compilation errors with applications that try to use the old
2667 method.
2668
2669 Starting with version 1.0.7, you can find out which version of the library
2670 you are using at run-time:
2671
2672    png_uint_32 libpng_vn = png_access_version_number();
2673
2674 The number libpng_vn is constructed from the major version, minor
2675 version with leading zero, and release number with leading zero,
2676 (e.g., libpng_vn for version 1.0.7 is 10007).
2677
2678 You can also check which version of png.h you used when compiling your
2679 application:
2680
2681    png_uint_32 application_vn = PNG_LIBPNG_VER;
2682
2683 VIII. Y2K Compliance in libpng
2684
2685 January 31, 2001
2686
2687 Since the PNG Development group is an ad-hoc body, we can't make
2688 an official declaration.
2689
2690 This is your unofficial assurance that libpng from version 0.71 and
2691 upward through 1.0.9 are Y2K compliant.  It is my belief that earlier
2692 versions were also Y2K compliant.
2693
2694 Libpng only has three year fields.  One is a 2-byte unsigned integer that
2695 will hold years up to 65535.  The other two hold the date in text
2696 format, and will hold years up to 9999.
2697
2698 The integer is
2699     "png_uint_16 year" in png_time_struct.
2700
2701 The strings are
2702     "png_charp time_buffer" in png_struct and
2703     "near_time_buffer", which is a local character string in png.c.
2704
2705 There are seven time-related functions:
2706
2707     png_convert_to_rfc_1123() in png.c
2708       (formerly png_convert_to_rfc_1152() in error)
2709     png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
2710     png_convert_from_time_t() in pngwrite.c
2711     png_get_tIME() in pngget.c
2712     png_handle_tIME() in pngrutil.c, called in pngread.c
2713     png_set_tIME() in pngset.c
2714     png_write_tIME() in pngwutil.c, called in pngwrite.c
2715
2716 All appear to handle dates properly in a Y2K environment.  The
2717 png_convert_from_time_t() function calls gmtime() to convert from system
2718 clock time, which returns (year - 1900), which we properly convert to
2719 the full 4-digit year.  There is a possibility that applications using
2720 libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
2721 function, or that they are incorrectly passing only a 2-digit year
2722 instead of "year - 1900" into the png_convert_from_struct_tm() function,
2723 but this is not under our control.  The libpng documentation has always
2724 stated that it works with 4-digit years, and the APIs have been
2725 documented as such.
2726
2727 The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
2728 integer to hold the year, and can hold years as large as 65535.
2729
2730 zlib, upon which libpng depends, is also Y2K compliant.  It contains
2731 no date-related code.
2732
2733
2734    Glenn Randers-Pehrson
2735    libpng maintainer
2736    PNG Development Group