merge of wxMac into main repository
[wxWidgets.git] / src / png / libpng.txt
1 libpng.txt - A description on how to use and modify libpng
2
3  libpng version 1.0.3 - January 14, 1999
4  Updated and distributed by Glenn Randers-Pehrson
5  <randeg@alumni.rpi.edu>
6  Copyright (c) 1998, 1999 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 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.  The PNG specification is available
39 as RFC 2083 <ftp://ftp.uu.net/graphics/png/documents/> and as a
40 W3C Recommendation <http://www.w3.org/TR/REC.png.html>. Some
41 additional chunks are described in the special-purpose public chunks
42 documents at <ftp://ftp.uu.net/graphics/png/documents/>.  Other information
43 about PNG, and the latest version of libpng, can be found at the PNG home
44 page, <http://www.cdrom.com/pub/png/>.
45
46 Most users will not have to modify the library significantly; advanced
47 users may want to modify it more.  All attempts were made to make it as
48 complete as possible, while keeping the code easy to understand.
49 Currently, this library only supports C.  Support for other languages
50 is being considered.
51
52 Libpng has been designed to handle multiple sessions at one time,
53 to be easily modifiable, to be portable to the vast majority of
54 machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
55 to use.  The ultimate goal of libpng is to promote the acceptance of
56 the PNG file format in whatever way possible.  While there is still
57 work to be done (see the TODO file), libpng should cover the
58 majority of the needs of its users.
59
60 Libpng uses zlib for its compression and decompression of PNG files.
61 Further information about zlib, and the latest version of zlib, can
62 be found at the zlib home page, <http://www.cdrom.com/pub/infozip/zlib/>.
63 The zlib compression utility is a general purpose utility that is
64 useful for more than PNG files, and can be used without libpng.
65 See the documentation delivered with zlib for more details.
66 You can usually find the source files for the zlib utility wherever you
67 find the libpng source files.
68
69 Libpng is thread safe, provided the threads are using different
70 instances of the structures.  Each thread should have its own
71 png_struct and png_info instances, and thus its own image.
72 Libpng does not protect itself against two threads using the
73 same instance of a structure.
74
75
76 II. Structures
77
78 There are two main structures that are important to libpng, png_struct
79 and png_info.  The first, png_struct, is an internal structure that
80 will not, for the most part, be used by a user except as the first
81 variable passed to every libpng function call.
82
83 The png_info structure is designed to provide information about the
84 PNG file.  At one time, the fields of png_info were intended to be
85 directly accessible to the user.  However, this tended to cause problems
86 with applications using dynamically loaded libraries, and as a result
87 a set of interface functions for png_info was developed.  The fields
88 of png_info are still available for older applications, but it is
89 suggested that applications use the new interfaces if at all possible.
90
91 The png.h header file is an invaluable reference for programming with libpng.
92 And while I'm on the topic, make sure you include the libpng header file:
93
94 #include <png.h>
95
96 III. Reading
97
98 Reading PNG files:
99
100 We'll now walk you through the possible functions to call when reading
101 in a PNG file, briefly explaining the syntax and purpose of each one.
102 See example.c and png.h for more detail.  While Progressive reading
103 is covered in the next section, you will still need some of the
104 functions discussed in this section to read a PNG file.
105
106 You will want to do the I/O initialization(*) before you get into libpng,
107 so if it doesn't work, you don't have much to undo.  Of course, you
108 will also want to insure that you are, in fact, dealing with a PNG
109 file.  Libpng provides a simple check to see if a file is a PNG file.
110 To use it, pass in the first 1 to 8 bytes of the file, and it will
111 return true or false (1 or 0) depending on whether the bytes could be
112 part of a PNG file.  Of course, the more bytes you pass in, the
113 greater the accuracy of the prediction.
114
115 If you are intending to keep the file pointer open for use in libpng,
116 you must ensure you don't read more than 8 bytes from the beginning
117 of the file, and you also have to make a call to png_set_sig_bytes_read()
118 with the number of bytes you read from the beginning.  Libpng will
119 then only check the bytes (if any) that your program didn't read.
120
121 (*): If you are not using the standard I/O functions, you will need
122 to replace them with custom functions.  See the discussion under
123 Customizing libpng.
124
125
126     FILE *fp = fopen(file_name, "rb");
127     if (!fp)
128     {
129         return;
130     }
131     fread(header, 1, number, fp);
132     is_png = !png_sig_cmp(header, 0, number);
133     if (!is_png)
134     {
135         return;
136     }
137
138
139 Next, png_struct and png_info need to be allocated and initialized.  In
140 order to ensure that the size of these structures is correct even with a
141 dynamically linked libpng, there are functions to initialize and
142 allocate the structures.  We also pass the library version, optional
143 pointers to error handling functions, and a pointer to a data struct for
144 use by the error functions, if necessary (the pointer and functions can
145 be NULL if the default error handlers are to be used).  See the section
146 on Changes to Libpng below regarding the old initialization functions.
147
148     png_structp png_ptr = png_create_read_struct
149        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
150         user_error_fn, user_warning_fn);
151     if (!png_ptr)
152         return;
153
154     png_infop info_ptr = png_create_info_struct(png_ptr);
155     if (!info_ptr)
156     {
157         png_destroy_read_struct(&png_ptr,
158            (png_infopp)NULL, (png_infopp)NULL);
159         return;
160     }
161
162     png_infop end_info = png_create_info_struct(png_ptr);
163     if (!end_info)
164     {
165         png_destroy_read_struct(&png_ptr, &info_ptr,
166           (png_infopp)NULL);
167         return;
168     }
169
170 If you want to use your own memory allocation routines,
171 define PNG_USER_MEM_SUPPORTED and use
172 png_create_read_struct_2() instead of png_create_read_struct():
173
174     png_structp png_ptr = png_create_read_struct_2
175        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
176         user_error_fn, user_warning_fn, (png_voidp)
177         user_mem_ptr, user_malloc_fn, user_free_fn);
178
179 The error handling routines passed to png_create_read_struct()
180 and the memory alloc/free routines passed to png_create_struct_2()
181 are only necessary if you are not using the libpng supplied error
182 handling and memory alloc/free functions.
183
184 When libpng encounters an error, it expects to longjmp back
185 to your routine.  Therefore, you will need to call setjmp and pass
186 your png_ptr->jmpbuf.  If you read the file from different
187 routines, you will need to update the jmpbuf field every time you enter
188 a new routine that will call a png_ function.
189
190 See your documentation of setjmp/longjmp for your compiler for more
191 handling in the Customizing Libpng section below for more information on
192 the libpng error handling.  If an error occurs, and libpng longjmp's
193 back to your setjmp, you will want to call png_destroy_read_struct() to
194 free any memory.
195
196     if (setjmp(png_ptr->jmpbuf))
197     {
198         png_destroy_read_struct(&png_ptr, &info_ptr,
199            &end_info);
200         fclose(fp);
201         return;
202     }
203
204 Now you need to set up the input code.  The default for libpng is to
205 use the C function fread().  If you use this, you will need to pass a
206 valid FILE * in the function png_init_io().  Be sure that the file is
207 opened in binary mode.  If you wish to handle reading data in another
208 way, you need not call the png_init_io() function, but you must then
209 implement the libpng I/O methods discussed in the Customizing Libpng
210 section below.
211
212     png_init_io(png_ptr, fp);
213
214 If you had previously opened the file and read any of the signature from
215 the beginning in order to see if this was a PNG file, you need to let
216 libpng know that there are some bytes missing from the start of the file.
217
218     png_set_sig_bytes(png_ptr, number);
219
220 At this point, you can set up a callback function that will be
221 called after each row has been read, which you can use to control
222 a progress meter or the like.  It's demonstrated in pngtest.c.
223 You must supply a function
224
225     void read_row_callback(png_ptr, png_uint_32 row, int pass);
226     {
227       /* put your code here */
228     }
229
230 (You can give it another name that you like instead of "read_row_callback")
231
232 To inform libpng about your function, use
233
234     png_set_read_status_fn(png_ptr, read_row_callback);
235
236 In PNG files, the alpha channel in an image is the level of opacity.
237 If you need the alpha channel in an image to be the level of transparency
238 instead of opacity, you can invert the alpha channel (or the tRNS chunk
239 data) after it's read, so that 0 is fully opaque and 255 (in 8-bit or
240 paletted images) or 65535 (in 16-bit images) is fully transparent, with
241
242     png_set_invert_alpha(png_ptr);
243
244 This has to appear here rather than later with the other transformations
245 because the tRNS chunk data must be modified in the case of paletted images.
246 If your image is not a paletted image, the tRNS data (which in such cases
247 represents a single color to be rendered as transparent) won't be changed.
248
249 Finally, you can write your own transformation function if none of
250 the existing ones meets your needs.  This is done by setting a callback
251 with
252
253     png_set_read_user_transform_fn(png_ptr,
254        read_transform_fn);
255
256 You must supply the function
257
258     void read_transform_fn(png_ptr ptr, row_info_ptr
259        row_info, png_bytep data)
260
261 See pngtest.c for a working example.  Your function will be called
262 after all of the other transformations have been processed.
263
264 You are now ready to read all the file information up to the actual
265 image data.  You do this with a call to png_read_info().
266
267     png_read_info(png_ptr, info_ptr);
268
269 Functions are used to get the information from the info_ptr:
270
271     png_get_IHDR(png_ptr, info_ptr, &width, &height,
272        &bit_depth, &color_type, &interlace_type,
273        &compression_type, &filter_type);
274
275     width          - holds the width of the image
276                      in pixels (up to 2^31).
277     height         - holds the height of the image
278                      in pixels (up to 2^31).
279     bit_depth      - holds the bit depth of one of the
280                      image channels.  (valid values are
281                      1, 2, 4, 8, 16 and depend also on
282                      the color_type.  See also
283                      significant bits (sBIT) below).
284     color_type     - describes which color/alpha channels
285                          are present.
286                      PNG_COLOR_TYPE_GRAY
287                         (bit depths 1, 2, 4, 8, 16)
288                      PNG_COLOR_TYPE_GRAY_ALPHA
289                         (bit depths 8, 16)
290                      PNG_COLOR_TYPE_PALETTE
291                         (bit depths 1, 2, 4, 8)
292                      PNG_COLOR_TYPE_RGB
293                         (bit_depths 8, 16)
294                      PNG_COLOR_TYPE_RGB_ALPHA
295                         (bit_depths 8, 16)
296
297                      PNG_COLOR_MASK_PALETTE
298                      PNG_COLOR_MASK_COLOR
299                      PNG_COLOR_MASK_ALPHA
300
301     filter_type    - (must be PNG_FILTER_TYPE_BASE
302                      for PNG 1.0)
303     compression_type - (must be PNG_COMPRESSION_TYPE_BASE
304                      for PNG 1.0)
305     interlace_type - (PNG_INTERLACE_NONE or
306                      PNG_INTERLACE_ADAM7)
307     Any or all of interlace_type, compression_type, of
308                      filter_type can be
309     NULL if you are not interested in their values.
310
311     channels = png_get_channels(png_ptr, info_ptr);
312     channels       - number of channels of info for the
313                      color type (valid values are 1 (GRAY,
314                      PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
315                      4 (RGB_ALPHA or RGB + filler byte))
316     rowbytes = png_get_rowbytes(png_ptr, info_ptr);
317     rowbytes       - number of bytes needed to hold a row
318
319     signature = png_get_signature(png_ptr, info_ptr);
320     signature      - holds the signature read from the
321                      file (if any).  The data is kept in
322                      the same offset it would be if the
323                      whole signature were read (i.e. if an
324                      application had already read in 4
325                      bytes of signature before starting
326                      libpng, the remaining 4 bytes would
327                      be in signature[4] through signature[7]
328                      (see png_set_sig_bytes())).
329
330
331     width            = png_get_image_width(png_ptr,
332                          info_ptr);
333     height           = png_get_image_height(png_ptr,
334                          info_ptr);
335     bit_depth        = png_get_bit_depth(png_ptr,
336                          info_ptr);
337     color_type       = png_get_color_type(png_ptr,
338                          info_ptr);
339     filter_type      = png_get_filter_type(png_ptr,
340                          info_ptr);
341     compression_type = png_get_compression_type(png_ptr,
342                          info_ptr);
343     interlace_type   = png_get_interlace_type(png_ptr,
344                          info_ptr);
345
346
347 These are also important, but their validity depends on whether the chunk
348 has been read.  The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
349 png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
350 data has been read, or zero if it is missing.  The parameters to the
351 png_get_<chunk> are set directly if they are simple data types, or a pointer
352 into the info_ptr is returned for any complex types.
353
354     png_get_PLTE(png_ptr, info_ptr, &palette,
355                      &num_palette);
356     palette        - the palette for the file
357                      (array of png_color)
358     num_palette    - number of entries in the palette
359
360     png_get_gAMA(png_ptr, info_ptr, &gamma);
361     gamma          - the gamma the file is written
362                      at (PNG_INFO_gAMA)
363
364     png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
365     srgb_intent    - the rendering intent (PNG_INFO_sRGB)
366                      The presence of the sRGB chunk
367                      means that the pixel data is in the
368                      sRGB color space.  This chunk also
369                      implies specific values of gAMA and
370                      cHRM.
371
372     png_get_sBIT(png_ptr, info_ptr, &sig_bit);
373     sig_bit        - the number of significant bits for
374                      (PNG_INFO_sBIT) each of the gray,
375                      red, green, and blue channels,
376                      whichever are appropriate for the
377                      given color type (png_color_16)
378
379     png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
380                      &trans_values);
381     trans          - array of transparent entries for
382                      palette (PNG_INFO_tRNS)
383     trans_values   - transparent pixel for non-paletted
384                      images (PNG_INFO_tRNS)
385     num_trans      - number of transparent entries
386                      (PNG_INFO_tRNS)
387
388     png_get_hIST(png_ptr, info_ptr, &hist);
389                      (PNG_INFO_hIST)
390     hist           - histogram of palette (array of
391                      png_color_16)
392
393     png_get_tIME(png_ptr, info_ptr, &mod_time);
394     mod_time       - time image was last modified
395                     (PNG_VALID_tIME)
396
397     png_get_bKGD(png_ptr, info_ptr, &background);
398     background     - background color (PNG_VALID_bKGD)
399
400     num_text = png_get_text(png_ptr, info_ptr, &text_ptr);
401     text_ptr       - array of png_text holding image
402                      comments
403     text_ptr[i]->key   - keyword for comment.
404     text_ptr[i]->text  - text comments for current
405                          keyword.
406     text_ptr[i]->compression - type of compression used
407                      on "text" PNG_TEXT_COMPRESSION_NONE
408                      or PNG_TEXT_COMPRESSION_zTXt
409     num_text       - number of comments
410
411     png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
412                      &unit_type);
413     offset_x       - positive offset from the left edge
414                      of the screen
415     offset_y       - positive offset from the top edge
416                      of the screen
417     unit_type      - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
418
419     png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
420                      &unit_type);
421     res_x          - pixels/unit physical resolution in
422                      x direction
423     res_y          - pixels/unit physical resolution in
424                      x direction
425     unit_type      - PNG_RESOLUTION_UNKNOWN,
426                      PNG_RESOLUTION_METER
427
428 The data from the pHYs chunk can be retrieved in several convenient
429 forms:
430
431     res_x = png_get_x_pixels_per_meter(png_ptr,
432                   info_ptr)
433     res_y = png_get_y_pixels_per_meter(png_ptr,
434                   info_ptr)
435     res_x_and_y = png_get_pixels_per_meter(png_ptr,
436                   info_ptr)
437     aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
438                   info_ptr)
439
440    (Each of these returns 0 [signifying "unknown"] if
441        the data is not present or if res_x is 0;
442        res_x_and_y is 0 if res_x != res_y)
443
444 For more information, see the png_info definition in png.h and the
445 PNG specification for chunk contents.  Be careful with trusting
446 rowbytes, as some of the transformations could increase the space
447 needed to hold a row (expand, filler, gray_to_rgb, etc.).
448 See png_read_update_info(), below.
449
450 A quick word about text_ptr and num_text.  PNG stores comments in
451 keyword/text pairs, one pair per chunk, with no limit on the number
452 of text chunks, and a 2^31 byte limit on their size.  While there are
453 suggested keywords, there is no requirement to restrict the use to these
454 strings.  It is strongly suggested that keywords and text be sensible
455 to humans (that's the point), so don't use abbreviations.  Non-printing
456 symbols are not allowed.  See the PNG specification for more details.
457 There is also no requirement to have text after the keyword.
458
459 Keywords should be limited to 79 Latin-1 characters without leading or
460 trailing spaces, but non-consecutive spaces are allowed within the
461 keyword.  It is possible to have the same keyword any number of times.
462 The text_ptr is an array of png_text structures, each holding pointer
463 to a keyword and a pointer to a text string.  Only the text string may
464 be null.  The keyword/text pairs are put into the array in the order
465 that they are received.  However, some or all of the text chunks may be
466 after the image, so, to make sure you have read all the text chunks,
467 don't mess with these until after you read the stuff after the image.
468 This will be mentioned again below in the discussion that goes with
469 png_read_end().
470
471 After you've read the header information, you can set up the library
472 to handle any special transformations of the image data.  The various
473 ways to transform the data will be described in the order that they
474 should occur.  This is important, as some of these change the color
475 type and/or bit depth of the data, and some others only work on
476 certain color types and bit depths.  Even though each transformation
477 checks to see if it has data that it can do something with, you should
478 make sure to only enable a transformation if it will be valid for the
479 data.  For example, don't swap red and blue on grayscale data.
480
481 The colors used for the background and transparency values should be
482 supplied in the same format/depth as the current image data.  They
483 are stored in the same format/depth as the image data in a bKGD or tRNS
484 chunk, so this is what libpng expects for this data.  The colors are
485 transformed to keep in sync with the image data when an application
486 calls the png_read_update_info() routine (see below).
487
488 Data will be decoded into the supplied row buffers packed into bytes
489 unless the library has been told to transform it into another format.
490 For example, 4 bit/pixel paletted or grayscale data will be returned
491 2 pixels/byte with the leftmost pixel in the high-order bits of the
492 byte, unless png_set_packing() is called.  8-bit RGB data will be stored
493 in RGB RGB RGB format unless png_set_filler() is called to insert filler
494 bytes, either before or after each RGB triplet.  16-bit RGB data will
495 be returned RRGGBB RRGGBB, with the most significant byte of the color
496 value first, unless png_set_strip_16() is called to transform it to
497 regular RGB RGB triplets, or png_set_filler() is called to insert
498 filler bytes, either before or after each RRGGBB triplet.  Similarly,
499 8-bit or 16-bit grayscale data can be modified with png_set_filler()
500 or png_set_strip_16().
501
502 The following code transforms grayscale images of less than 8 to 8 bits,
503 changes paletted images to RGB, and adds a full alpha channel if there is
504 transparency information in a tRNS chunk.  This is most useful on
505 grayscale images with bit depths of 2 or 4 or if there is a multiple-image
506 viewing application that wishes to treat all images in the same way.
507
508     if (color_type == PNG_COLOR_TYPE_PALETTE &&
509         bit_depth <= 8) png_set_expand(png_ptr);
510
511     if (color_type == PNG_COLOR_TYPE_GRAY &&
512         bit_depth < 8) png_set_expand(png_ptr);
513
514     if (png_get_valid(png_ptr, info_ptr,
515         PNG_INFO_tRNS)) png_set_expand(png_ptr);
516
517 PNG can have files with 16 bits per channel.  If you only can handle
518 8 bits per channel, this will strip the pixels down to 8 bit.
519
520     if (bit_depth == 16)
521         png_set_strip_16(png_ptr);
522
523 The png_set_background() function tells libpng to composite images
524 with alpha or simple transparency against the supplied background
525 color.  If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
526 you may use this color, or supply another color more suitable for
527 the current display (e.g., the background color from a web page).  You
528 need to tell libpng whether the color is in the gamma space of the
529 display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
530 (PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
531 that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
532 know why anyone would use this, but it's here).
533
534 If, for some reason, you don't need the alpha channel on an image,
535 and you want to remove it rather than combining it with the background
536 (but the image author certainly had in mind that you *would* combine
537 it with the background, so that's what you should probably do):
538
539     if (color_type & PNG_COLOR_MASK_ALPHA)
540         png_set_strip_alpha(png_ptr);
541
542 PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
543 they can, resulting in, for example, 8 pixels per byte for 1 bit
544 files.  This code expands to 1 pixel per byte without changing the
545 values of the pixels:
546
547     if (bit_depth < 8)
548         png_set_packing(png_ptr);
549
550 PNG files have possible bit depths of 1, 2, 4, 8, and 16.  All pixels
551 stored in a PNG image have been "scaled" or "shifted" up to the next
552 higher possible bit depth (e.g. from 5 bits/sample in the range [0,31] to
553 8 bits/sample in the range [0, 255]).  However, it is also possible to
554 convert the PNG pixel data back to the original bit depth of the image.
555 This call reduces the pixels back down to the original bit depth:
556
557     png_color_16p sig_bit;
558
559     if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
560         png_set_shift(png_ptr, sig_bit);
561
562 PNG files store 3-color pixels in red, green, blue order.  This code
563 changes the storage of the pixels to blue, green, red:
564
565     if (color_type == PNG_COLOR_TYPE_RGB ||
566         color_type == PNG_COLOR_TYPE_RGB_ALPHA)
567         png_set_bgr(png_ptr);
568
569 PNG files store RGB pixels packed into 3 bytes. This code expands them
570 into 4 bytes for windowing systems that need them in this format:
571
572     if (bit_depth == 8 && color_type ==
573         PNG_COLOR_TYPE_RGB) png_set_filler(png_ptr,
574         filler, PNG_FILLER_BEFORE);
575
576 where "filler" is the 8 or 16-bit number to fill with, and the location is
577 either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
578 you want the filler before the RGB or after.  This transformation
579 does not affect images that already have full alpha channels.
580
581 If you are reading an image with an alpha channel, and you need the
582 data as ARGB instead of the normal PNG format RGBA:
583
584     if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
585         png_set_swap_alpha(png_ptr);
586
587 For some uses, you may want a grayscale image to be represented as
588 RGB.  This code will do that conversion:
589
590     if (color_type == PNG_COLOR_TYPE_GRAY ||
591         color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
592           png_set_gray_to_rgb(png_ptr);
593
594 Conversely, you can convert an RGB or RGBA image to grayscale or grayscale
595 with alpha.  This is intended for conversion of images that really are
596 gray (red == green == blue), so the function simply strips out the red
597 and blue channels, leaving the green channel in the gray position.
598
599     if (color_type == PNG_COLOR_TYPE_RGB ||
600         color_type == PNG_COLOR_TYPE_RGB_ALPHA)
601           png_set_rgb_to_gray(png_ptr, error_action,
602              float red_weight, float green_weight);
603
604     error_action = 1: silently do the conversion
605     error_action = 2: issue a warning if the original
606                       image has any pixel where
607                       red != green or red != blue
608     error_action = 3: issue an error and abort the
609                       conversion if the original
610                       image has any pixel where
611                       red != green or red != blue
612
613     red_weight:       weight of red component
614                       (NULL -> default 54/256)
615     green_weight:     weight of green component
616                       (NULL -> default 183/256)
617
618 If you have set error_action = 1 or 2, you can
619 later check whether the image really was gray, after processing
620 the image rows, with the png_get_rgb_to_gray_status(png_ptr) function.
621 It will return a png_byte that is zero if the image was gray or
622 1 if there were any non-gray pixels.  bKGD and sBIT data
623 will be silently converted to grayscale, using the green channel
624 data, regardless of the error_action setting.
625
626 With 0.0<=red_weight+green_weight<=1.0,
627 the normalized graylevel is computed:
628
629     int rw = red_weight * 256;
630     int gw = green_weight * 256;
631     int bw = 256 - (rw + gw);
632     gray = (rw*red + gw*green + bw*blue)/256;
633
634 The default values approximate those recommended in the Charles
635 Poynton's Color FAQ, <http://www.inforamp.net/~poynton/>
636 Copyright (c) 1998-01-04 Charles Poynton poynton@inforamp.net
637
638     Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
639
640 Libpng approximates this with
641
642     Y = 0.211 * R    + 0.715 * G    + 0.074 * B
643
644 which can be expressed with integers as
645
646     Y = (54 * R + 183 * G + 19 * B)/256
647
648 The calculation is done in a linear colorspace, if the image gamma
649 is known.
650
651 If you have a grayscale and you are using png_set_expand() to change to
652 a higher bit-depth, you must either supply the background color as a gray
653 value at the original file bit-depth (need_expand = 1) or else supply the
654 background color as an RGB triplet at the final, expanded bit depth
655 (need_expand = 0).  Similarly, if you are reading a paletted image, you
656 must either supply the background color as a palette index (need_expand = 1)
657 or as an RGB triplet that may or may not be in the palette (need_expand = 0).
658
659     png_color_16 my_background;
660     png_color_16p image_background;
661
662     if (png_get_bKGD(png_ptr, info_ptr, &image_background))
663         png_set_background(png_ptr, image_background,
664           PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
665     else
666         png_set_background(png_ptr, &my_background,
667           PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
668
669 To properly display PNG images on any kind of system, the application needs
670 to know what the display gamma is.  Ideally, the user will know this, and
671 the application will allow them to set it.  One method of allowing the user
672 to set the display gamma separately for each system is to check for the
673 DISPLAY_GAMMA and VIEWING_GAMMA environment variables or for a SCREEN_GAMMA
674 environment variable, which will hopefully be correctly set.
675
676 Note that display_gamma is the gamma of your display, while screen_gamma is
677 the overall gamma correction required to produce pleasing results,
678 which depends on the lighting conditions in the surrounding environment.
679 Screen_gamma is display_gamma/viewing_gamma, where viewing_gamma is
680 the amount of additional gamma correction needed to compensate for
681 a (viewing_gamma=1.25) environment.  In a dim or brightly lit room, no
682 compensation other than the display_gamma is needed (viewing_gamma=1.0).
683
684    if (/* We have a user-defined screen
685        gamma value */)
686    {
687       screen_gamma = user_defined_screen_gamma;
688    }
689    /* One way that applications can share the same
690       screen gamma value */
691    else if ((gamma_str = getenv("SCREEN_GAMMA"))
692       != NULL)
693    {
694       screen_gamma = atof(gamma_str);
695    }
696    /* If we don't have another value */
697    else
698    {
699       screen_gamma = 2.2; /* A good guess for a
700            PC monitor in a bright office or a dim room */
701       screen_gamma = 2.0; /* A good guess for a
702            PC monitor in a dark room */
703       screen_gamma = 1.7 or 1.0;  /* A good
704            guess for Mac systems */
705    }
706
707 The png_set_gamma() function handles gamma transformations of the data.
708 Pass both the file gamma and the current screen_gamma.  If the file does
709 not have a gamma value, you can pass one anyway if you have an idea what
710 it is (usually 0.45455 is a good guess for GIF images on PCs).  Note
711 that file gammas are inverted from screen gammas.  See the discussions
712 on gamma in the PNG specification for an excellent description of what
713 gamma is, and why all applications should support it.  It is strongly
714 recommended that PNG viewers support gamma correction.
715
716    if (png_get_gAMA(png_ptr, info_ptr, &gamma))
717       png_set_gamma(png_ptr, screen_gamma, gamma);
718    else
719       png_set_gamma(png_ptr, screen_gamma, 0.45455);
720
721 If you need to reduce an RGB file to a paletted file, or if a paletted
722 file has more entries then will fit on your screen, png_set_dither()
723 will do that.  Note that this is a simple match dither that merely
724 finds the closest color available.  This should work fairly well with
725 optimized palettes, and fairly badly with linear color cubes.  If you
726 pass a palette that is larger then maximum_colors, the file will
727 reduce the number of colors in the palette so it will fit into
728 maximum_colors.  If there is a histogram, it will use it to make
729 more intelligent choices when reducing the palette.  If there is no
730 histogram, it may not do as good a job.
731
732    if (color_type & PNG_COLOR_MASK_COLOR)
733    {
734       if (png_get_valid(png_ptr, info_ptr,
735          PNG_INFO_PLTE))
736       {
737          png_color_16p histogram;
738
739          png_get_hIST(png_ptr, info_ptr,
740             &histogram);
741          png_set_dither(png_ptr, palette, num_palette,
742             max_screen_colors, histogram, 1);
743       }
744       else
745       {
746          png_color std_color_cube[MAX_SCREEN_COLORS] =
747             { ... colors ... };
748
749          png_set_dither(png_ptr, std_color_cube,
750             MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
751             NULL,0);
752       }
753    }
754
755 PNG files describe monochrome as black being zero and white being one.
756 The following code will reverse this (make black be one and white be
757 zero):
758
759    if (bit_depth == 1 && color_type == PNG_COLOR_GRAY)
760       png_set_invert_mono(png_ptr);
761
762 PNG files store 16 bit pixels in network byte order (big-endian,
763 ie. most significant bits first).  This code changes the storage to the
764 other way (little-endian, i.e. least significant bits first, the
765 way PCs store them):
766
767     if (bit_depth == 16)
768         png_set_swap(png_ptr);
769
770 If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
771 need to change the order the pixels are packed into bytes, you can use:
772
773     if (bit_depth < 8)
774        png_set_packswap(png_ptr);
775
776 The last thing to handle is interlacing; this is covered in detail below,
777 but you must call the function here if you want libpng to handle expansion
778 of the interlaced image.
779
780     number_of_passes = png_set_interlace_handling(png_ptr);
781
782 After setting the transformations, libpng can update your png_info
783 structure to reflect any transformations you've requested with this
784 call.  This is most useful to update the info structure's rowbytes
785 field so you can use it to allocate your image memory.  This function
786 will also update your palette with the correct screen_gamma and
787 background if these have been given with the calls above.
788
789     png_read_update_info(png_ptr, info_ptr);
790
791 After you call png_read_update_info(), you can allocate any
792 memory you need to hold the image.  The row data is simply
793 raw byte data for all forms of images.  As the actual allocation
794 varies among applications, no example will be given.  If you
795 are allocating one large chunk, you will need to build an
796 array of pointers to each row, as it will be needed for some
797 of the functions below.
798
799 After you've allocated memory, you can read the image data.
800 The simplest way to do this is in one function call.  If you are
801 allocating enough memory to hold the whole image, you can just
802 call png_read_image() and libpng will read in all the image data
803 and put it in the memory area supplied.  You will need to pass in
804 an array of pointers to each row.
805
806 This function automatically handles interlacing, so you don't need
807 to call png_set_interlace_handling() or call this function multiple
808 times, or any of that other stuff necessary with png_read_rows().
809
810    png_read_image(png_ptr, row_pointers);
811
812 where row_pointers is:
813
814    png_bytep row_pointers[height];
815
816 You can point to void or char or whatever you use for pixels.
817
818 If you don't want to read in the whole image at once, you can
819 use png_read_rows() instead.  If there is no interlacing (check
820 interlace_type == PNG_INTERLACE_NONE), this is simple:
821
822     png_read_rows(png_ptr, row_pointers, NULL,
823        number_of_rows);
824
825 where row_pointers is the same as in the png_read_image() call.
826
827 If you are doing this just one row at a time, you can do this with
828 row_pointers:
829
830     png_bytep row_pointers = row;
831     png_read_row(png_ptr, &row_pointers, NULL);
832
833 If the file is interlaced (info_ptr->interlace_type != 0), things get
834 somewhat harder.  The only current (PNG Specification version 1.0)
835 interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7)
836 is a somewhat complicated 2D interlace scheme, known as Adam7, that
837 breaks down an image into seven smaller images of varying size, based
838 on an 8x8 grid.
839
840 libpng can fill out those images or it can give them to you "as is".
841 If you want them filled out, there are two ways to do that.  The one
842 mentioned in the PNG specification is to expand each pixel to cover
843 those pixels that have not been read yet (the "rectangle" method).
844 This results in a blocky image for the first pass, which gradually
845 smooths out as more pixels are read.  The other method is the "sparkle"
846 method, where pixels are drawn only in their final locations, with the
847 rest of the image remaining whatever colors they were initialized to
848 before the start of the read.  The first method usually looks better,
849 but tends to be slower, as there are more pixels to put in the rows.
850
851 If you don't want libpng to handle the interlacing details, just call
852 png_read_rows() seven times to read in all seven images.  Each of the
853 images is a valid image by itself, or they can all be combined on an
854 8x8 grid to form a single image (although if you intend to combine them
855 you would be far better off using the libpng interlace handling).
856
857 The first pass will return an image 1/8 as wide as the entire image
858 (every 8th column starting in column 0) and 1/8 as high as the original
859 (every 8th row starting in row 0), the second will be 1/8 as wide
860 (starting in column 4) and 1/8 as high (also starting in row 0).  The
861 third pass will be 1/4 as wide (every 4th pixel starting in column 0) and
862 1/8 as high (every 8th row starting in row 4), and the fourth pass will
863 be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
864 and every 4th row starting in row 0).  The fifth pass will return an
865 image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
866 while the sixth pass will be 1/2 as wide and 1/2 as high as the original
867 (starting in column 1 and row 0).  The seventh and final pass will be as
868 wide as the original, and 1/2 as high, containing all of the odd
869 numbered scanlines.  Phew!
870
871 If you want libpng to expand the images, call this before calling
872 png_start_read_image() or png_read_update_info():
873
874     if (interlace_type == PNG_INTERLACE_ADAM7)
875         number_of_passes
876            = png_set_interlace_handling(png_ptr);
877
878 This will return the number of passes needed.  Currently, this
879 is seven, but may change if another interlace type is added.
880 This function can be called even if the file is not interlaced,
881 where it will return one pass.
882
883 If you are not going to display the image after each pass, but are
884 going to wait until the entire image is read in, use the sparkle
885 effect.  This effect is faster and the end result of either method
886 is exactly the same.  If you are planning on displaying the image
887 after each pass, the "rectangle" effect is generally considered the
888 better looking one.
889
890 If you only want the "sparkle" effect, just call png_read_rows() as
891 normal, with the third parameter NULL.  Make sure you make pass over
892 the image number_of_passes times, and you don't change the data in the
893 rows between calls.  You can change the locations of the data, just
894 not the data.  Each pass only writes the pixels appropriate for that
895 pass, and assumes the data from previous passes is still valid.
896
897     png_read_rows(png_ptr, row_pointers, NULL,
898        number_of_rows);
899
900 If you only want the first effect (the rectangles), do the same as
901 before except pass the row buffer in the third parameter, and leave
902 the second parameter NULL.
903
904     png_read_rows(png_ptr, NULL, row_pointers,
905        number_of_rows);
906
907 After you are finished reading the image, you can finish reading
908 the file.  If you are interested in comments or time, which may be
909 stored either before or after the image data, you should pass the
910 separate png_info struct if you want to keep the comments from
911 before and after the image separate.  If you are not interested, you
912 can pass NULL.
913
914    png_read_end(png_ptr, end_info);
915
916 When you are done, you can free all memory allocated by libpng like this:
917
918    png_destroy_read_struct(&png_ptr, &info_ptr,
919        &end_info);
920
921 For a more compact example of reading a PNG image, see the file example.c.
922
923
924 Reading PNG files progressively:
925
926 The progressive reader is slightly different then the non-progressive
927 reader.  Instead of calling png_read_info(), png_read_rows(), and
928 png_read_end(), you make one call to png_process_data(), which calls
929 callbacks when it has the info, a row, or the end of the image.  You
930 set up these callbacks with png_set_progressive_read_fn().  You don't
931 have to worry about the input/output functions of libpng, as you are
932 giving the library the data directly in png_process_data().  I will
933 assume that you have read the section on reading PNG files above,
934 so I will only highlight the differences (although I will show
935 all of the code).
936
937 png_structp png_ptr;
938 png_infop info_ptr;
939
940  /*  An example code fragment of how you would
941      initialize the progressive reader in your
942      application. */
943  int
944  initialize_png_reader()
945  {
946     png_ptr = png_create_read_struct
947         (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
948          user_error_fn, user_warning_fn);
949     if (!png_ptr)
950         return -1;
951     info_ptr = png_create_info_struct(png_ptr);
952     if (!info_ptr)
953     {
954         png_destroy_read_struct(&png_ptr, (png_infopp)NULL,
955            (png_infopp)NULL);
956         return -1;
957     }
958
959     if (setjmp(png_ptr->jmpbuf))
960     {
961         png_destroy_read_struct(&png_ptr, &info_ptr,
962            (png_infopp)NULL);
963         return -1;
964     }
965
966     /* This one's new.  You can provide functions
967        to be called when the header info is valid,
968        when each row is completed, and when the image
969        is finished.  If you aren't using all functions,
970        you can specify NULL parameters.  Even when all
971        three functions are NULL, you need to call
972        png_set_progressive_read_fn().  You can use
973        any struct as the user_ptr (cast to a void pointer
974        for the function call), and retrieve the pointer
975        from inside the callbacks using the function
976
977           png_get_progressive_ptr(png_ptr);
978
979        which will return a void pointer, which you have
980        to cast appropriately.
981      */
982     png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
983         info_callback, row_callback, end_callback);
984
985     return 0;
986  }
987
988  /* A code fragment that you call as you receive blocks
989    of data */
990  int
991  process_data(png_bytep buffer, png_uint_32 length)
992  {
993     if (setjmp(png_ptr->jmpbuf))
994     {
995         png_destroy_read_struct(&png_ptr, &info_ptr,
996            (png_infopp)NULL);
997         return -1;
998     }
999
1000     /* This one's new also.  Simply give it a chunk
1001        of data from the file stream (in order, of
1002        course).  On machines with segmented memory
1003        models machines, don't give it any more than
1004        64K.  The library seems to run fine with sizes
1005        of 4K. Although you can give it much less if
1006        necessary (I assume you can give it chunks of
1007        1 byte, I haven't tried less then 256 bytes
1008        yet).  When this function returns, you may
1009        want to display any rows that were generated
1010        in the row callback if you don't already do
1011        so there.
1012      */
1013     png_process_data(png_ptr, info_ptr, buffer, length);
1014     return 0;
1015  }
1016
1017  /* This function is called (as set by
1018     png_set_progressive_read_fn() above) when enough data
1019     has been supplied so all of the header has been
1020     read.
1021  */
1022  void
1023  info_callback(png_structp png_ptr, png_infop info)
1024  {
1025     /* Do any setup here, including setting any of
1026        the transformations mentioned in the Reading
1027        PNG files section.  For now, you _must_ call
1028        either png_start_read_image() or
1029        png_read_update_info() after all the
1030        transformations are set (even if you don't set
1031        any).  You may start getting rows before
1032        png_process_data() returns, so this is your
1033        last chance to prepare for that.
1034      */
1035  }
1036
1037  /* This function is called when each row of image
1038     data is complete */
1039  void
1040  row_callback(png_structp png_ptr, png_bytep new_row,
1041     png_uint_32 row_num, int pass)
1042  {
1043     /* If the image is interlaced, and you turned
1044        on the interlace handler, this function will
1045        be called for every row in every pass.  Some
1046        of these rows will not be changed from the
1047        previous pass.  When the row is not changed,
1048        the new_row variable will be NULL.  The rows
1049        and passes are called in order, so you don't
1050        really need the row_num and pass, but I'm
1051        supplying them because it may make your life
1052        easier.
1053
1054        For the non-NULL rows of interlaced images,
1055        you must call png_progressive_combine_row()
1056        passing in the row and the old row.  You can
1057        call this function for NULL rows (it will just
1058        return) and for non-interlaced images (it just
1059        does the memcpy for you) if it will make the
1060        code easier.  Thus, you can just do this for
1061        all cases:
1062      */
1063
1064         png_progressive_combine_row(png_ptr, old_row,
1065           new_row);
1066
1067     /* where old_row is what was displayed for
1068        previously for the row.  Note that the first
1069        pass (pass == 0, really) will completely cover
1070        the old row, so the rows do not have to be
1071        initialized.  After the first pass (and only
1072        for interlaced images), you will have to pass
1073        the current row, and the function will combine
1074        the old row and the new row.
1075     */
1076  }
1077
1078  void
1079  end_callback(png_structp png_ptr, png_infop info)
1080  {
1081     /* This function is called after the whole image
1082        has been read, including any chunks after the
1083        image (up to and including the IEND).  You
1084        will usually have the same info chunk as you
1085        had in the header, although some data may have
1086        been added to the comments and time fields.
1087
1088        Most people won't do much here, perhaps setting
1089        a flag that marks the image as finished.
1090      */
1091  }
1092
1093
1094
1095 IV. Writing
1096
1097 Much of this is very similar to reading.  However, everything of
1098 importance is repeated here, so you won't have to constantly look
1099 back up in the reading section to understand writing.
1100
1101 You will want to do the I/O initialization before you get into libpng,
1102 so if it doesn't work, you don't have anything to undo. If you are not
1103 using the standard I/O functions, you will need to replace them with
1104 custom writing functions.  See the discussion under Customizing libpng.
1105
1106     FILE *fp = fopen(file_name, "wb");
1107     if (!fp)
1108     {
1109        return;
1110     }
1111
1112 Next, png_struct and png_info need to be allocated and initialized.
1113 As these can be both relatively large, you may not want to store these
1114 on the stack, unless you have stack space to spare.  Of course, you
1115 will want to check if they return NULL.  If you are also reading,
1116 you won't want to name your read structure and your write structure
1117 both "png_ptr"; you can call them anything you like, such as
1118 "read_ptr" and "write_ptr".  Look at pngtest.c, for example.
1119
1120     png_structp png_ptr = png_create_write_struct
1121        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1122         user_error_fn, user_warning_fn);
1123     if (!png_ptr)
1124        return;
1125
1126     png_infop info_ptr = png_create_info_struct(png_ptr);
1127     if (!info_ptr)
1128     {
1129        png_destroy_write_struct(&png_ptr,
1130          (png_infopp)NULL);
1131        return;
1132     }
1133
1134 If you want to use your own memory allocation routines,
1135 define PNG_USER_MEM_SUPPORTED and use
1136 png_create_write_struct_2() instead of png_create_read_struct():
1137
1138     png_structp png_ptr = png_create_write_struct_2
1139        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1140         user_error_fn, user_warning_fn, (png_voidp)
1141         user_mem_ptr, user_malloc_fn, user_free_fn);
1142
1143 After you have these structures, you will need to set up the
1144 error handling.  When libpng encounters an error, it expects to
1145 longjmp() back to your routine.  Therefore, you will need to call
1146 setjmp() and pass the png_ptr->jmpbuf.  If you
1147 write the file from different routines, you will need to update
1148 the jmpbuf field every time you enter a new routine that will
1149 call a png_ function.  See your documentation of setjmp/longjmp
1150 for your compiler for more information on setjmp/longjmp.  See
1151 the discussion on libpng error handling in the Customizing Libpng
1152 section below for more information on the libpng error handling.
1153
1154     if (setjmp(png_ptr->jmpbuf))
1155     {
1156         png_destroy_write_struct(&png_ptr, &info_ptr);
1157         fclose(fp);
1158         return;
1159     }
1160     ...
1161     return;
1162
1163 Now you need to set up the output code.  The default for libpng is to
1164 use the C function fwrite().  If you use this, you will need to pass a
1165 valid FILE * in the function png_init_io().  Be sure that the file is
1166 opened in binary mode.  Again, if you wish to handle writing data in
1167 another way, see the discussion on libpng I/O handling in the Customizing
1168 Libpng section below.
1169
1170     png_init_io(png_ptr, fp);
1171
1172 At this point, you can set up a callback function that will be
1173 called after each row has been written, which you can use to control
1174 a progress meter or the like.  It's demonstrated in pngtest.c.
1175 You must supply a function
1176
1177     void write_row_callback(png_ptr, png_uint_32 row, int pass);
1178     {
1179       /* put your code here */
1180     }
1181
1182 (You can give it another name that you like instead of "write_row_callback")
1183
1184 To inform libpng about your function, use
1185
1186     png_set_write_status_fn(png_ptr, write_row_callback);
1187
1188 You now have the option of modifying how the compression library will
1189 run.  The following functions are mainly for testing, but may be useful
1190 in some cases, like if you need to write PNG files extremely fast and
1191 are willing to give up some compression, or if you want to get the
1192 maximum possible compression at the expense of slower writing.  If you
1193 have no special needs in this area, let the library do what it wants by
1194 not calling this function at all, as it has been tuned to deliver a good
1195 speed/compression ratio. The second parameter to png_set_filter() is
1196 the filter method, for which the only valid value is '0' (as of the
1197 October 1996 PNG specification, version 1.0).  The third parameter is a
1198 flag that indicates which filter type(s) are to be tested for each
1199 scanline.  See the Compression Library for details on the specific filter
1200 types.
1201
1202
1203     /* turn on or off filtering, and/or choose
1204        specific filters */
1205     png_set_filter(png_ptr, 0,
1206        PNG_FILTER_NONE | PNG_FILTER_SUB |
1207        PNG_FILTER_PAETH);
1208
1209 The png_set_compression_???() functions interface to the zlib compression
1210 library, and should mostly be ignored unless you really know what you are
1211 doing.  The only generally useful call is png_set_compression_level()
1212 which changes how much time zlib spends on trying to compress the image
1213 data.  See the Compression Library for details on the compression levels.
1214
1215     /* set the zlib compression level */
1216     png_set_compression_level(png_ptr,
1217         Z_BEST_COMPRESSION);
1218
1219     /* set other zlib parameters */
1220     png_set_compression_mem_level(png_ptr, 8);
1221     png_set_compression_strategy(png_ptr,
1222         Z_DEFAULT_STRATEGY);
1223     png_set_compression_window_bits(png_ptr, 15);
1224     png_set_compression_method(png_ptr, 8);
1225
1226 You now need to fill in the png_info structure with all the data you
1227 wish to write before the actual image.  Note that the only thing you
1228 are allowed to write after the image is the text chunks and the time
1229 chunk (as of PNG Specification 1.0, anyway).  See png_write_end() and
1230 the latest PNG specification for more information on that.  If you
1231 wish to write them before the image, fill them in now, and flag that
1232 data as being valid.  If you want to wait until after the data, don't
1233 fill them until png_write_end().  For all the fields in png_info and
1234 their data types, see png.h.  For explanations of what the fields
1235 contain, see the PNG specification.
1236
1237 Some of the more important parts of the png_info are:
1238
1239     png_set_IHDR(png_ptr, info_ptr, width, height,
1240        bit_depth, color_type, interlace_type,
1241        compression_type, filter_type)
1242     width          - holds the width of the image
1243                      in pixels (up to 2^31).
1244     height         - holds the height of the image
1245                      in pixels (up to 2^31).
1246     bit_depth      - holds the bit depth of one of the
1247                      image channels.
1248                      (valid values are 1, 2, 4, 8, 16
1249                      and depend also on the
1250                      color_type.  See also significant
1251                      bits (sBIT) below).
1252     color_type     - describes which color/alpha
1253                      channels are present.
1254                      PNG_COLOR_TYPE_GRAY
1255                         (bit depths 1, 2, 4, 8, 16)
1256                      PNG_COLOR_TYPE_GRAY_ALPHA
1257                         (bit depths 8, 16)
1258                      PNG_COLOR_TYPE_PALETTE
1259                         (bit depths 1, 2, 4, 8)
1260                      PNG_COLOR_TYPE_RGB
1261                         (bit_depths 8, 16)
1262                      PNG_COLOR_TYPE_RGB_ALPHA
1263                         (bit_depths 8, 16)
1264
1265                      PNG_COLOR_MASK_PALETTE
1266                      PNG_COLOR_MASK_COLOR
1267                      PNG_COLOR_MASK_ALPHA
1268
1269     interlace_type - PNG_INTERLACE_NONE or
1270                      PNG_INTERLACE_ADAM7
1271     compression_type - (must be
1272                      PNG_COMPRESSION_TYPE_DEFAULT)
1273     filter_type    - (must be PNG_FILTER_TYPE_DEFAULT)
1274
1275     png_set_PLTE(png_ptr, info_ptr, palette,
1276        num_palette);
1277     palette        - the palette for the file
1278                      (array of png_color)
1279     num_palette    - number of entries in the palette
1280
1281     png_set_gAMA(png_ptr, info_ptr, gamma);
1282     gamma          - the gamma the image was created
1283                      at (PNG_INFO_gAMA)
1284
1285     png_set_sRGB(png_ptr, info_ptr, srgb_intent);
1286     srgb_intent    - the rendering intent
1287                      (PNG_INFO_sRGB) The presence of
1288                      the sRGB chunk means that the pixel
1289                      data is in the sRGB color space.
1290                      This chunk also implies specific
1291                      values of gAMA and cHRM.  Rendering
1292                      intent is the CSS-1 property that
1293                      has been defined by the International
1294                      Color Consortium
1295                      (http://www.color.org).
1296                      It can be one of
1297                      PNG_SRGB_INTENT_SATURATION,
1298                      PNG_SRGB_INTENT_PERCEPTUAL,
1299                      PNG_SRGB_INTENT_ABSOLUTE, or
1300                      PNG_SRGB_INTENT_RELATIVE.
1301
1302
1303     png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
1304        srgb_intent);
1305     srgb_intent    - the rendering intent
1306                      (PNG_INFO_sRGB) The presence of the
1307                      sRGB chunk means that the pixel
1308                      data is in the sRGB color space.
1309                      This function also causes gAMA and
1310                      cHRM chunks with the specific values
1311                      that are consistent with sRGB to be
1312                      written.
1313
1314     png_set_sBIT(png_ptr, info_ptr, sig_bit);
1315     sig_bit        - the number of significant bits for
1316                      (PNG_INFO_sBIT) each of the gray, red,
1317                      green, and blue channels, whichever are
1318                      appropriate for the given color type
1319                      (png_color_16)
1320
1321     png_set_tRNS(png_ptr, info_ptr, trans, num_trans,
1322        trans_values);
1323     trans          - array of transparent entries for
1324                      palette (PNG_INFO_tRNS)
1325     trans_values   - transparent pixel for non-paletted
1326                      images (PNG_INFO_tRNS)
1327     num_trans      - number of transparent entries
1328                      (PNG_INFO_tRNS)
1329
1330     png_set_hIST(png_ptr, info_ptr, hist);
1331                     (PNG_INFO_hIST)
1332     hist           - histogram of palette (array of
1333                      png_color_16)
1334
1335     png_set_tIME(png_ptr, info_ptr, mod_time);
1336     mod_time       - time image was last modified
1337                      (PNG_VALID_tIME)
1338
1339     png_set_bKGD(png_ptr, info_ptr, background);
1340     background     - background color (PNG_VALID_bKGD)
1341
1342     png_set_text(png_ptr, info_ptr, text_ptr, num_text);
1343     text_ptr       - array of png_text holding image
1344                      comments
1345     text_ptr[i]->key   - keyword for comment.
1346     text_ptr[i]->text  - text comments for current
1347                          keyword.
1348     text_ptr[i]->compression - type of compression used
1349          on "text" PNG_TEXT_COMPRESSION_NONE or
1350          PNG_TEXT_COMPRESSION_zTXt
1351     num_text    - number of comments in text_ptr
1352
1353     png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
1354         unit_type);
1355     offset_x  - positive offset from the left
1356                      edge of the screen
1357     offset_y  - positive offset from the top
1358                      edge of the screen
1359     unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
1360
1361     png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
1362         unit_type);
1363     res_x       - pixels/unit physical resolution
1364                   in x direction
1365     res_y       - pixels/unit physical resolution
1366                   in y direction
1367     unit_type   - PNG_RESOLUTION_UNKNOWN,
1368                   PNG_RESOLUTION_METER
1369
1370 In PNG files, the alpha channel in an image is the level of opacity.
1371 If your data is supplied as a level of transparency, you can invert the
1372 alpha channel before you write it, so that 0 is fully transparent and 255
1373 (in 8-bit or paletted images) or 65535 (in 16-bit images) is fully opaque,
1374 with
1375
1376     png_set_invert_alpha(png_ptr);
1377
1378 This must appear here instead of later with the other transformations
1379 because in the case of paletted images the tRNS chunk data has to
1380 be inverted before the tRNS chunk is written.  If your image is not a
1381 paletted image, the tRNS data (which in such cases represents a single
1382 color to be rendered as transparent) won't be changed.
1383
1384 A quick word about text and num_text.  text is an array of png_text
1385 structures.  num_text is the number of valid structures in the array.
1386 If you want, you can use max_text to hold the size of the array, but
1387 libpng ignores it for writing (it does use it for reading).  Each
1388 png_text structure holds a keyword-text value, and a compression type.
1389 The compression types have the same valid numbers as the compression
1390 types of the image data.  Currently, the only valid number is zero.
1391 However, you can store text either compressed or uncompressed, unlike
1392 images, which always have to be compressed.  So if you don't want the
1393 text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
1394 Until text gets around 1000 bytes, it is not worth compressing it.
1395 After the text has been written out to the file, the compression type
1396 is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
1397 so that it isn't written out again at the end (in case you are calling
1398 png_write_end() with the same struct.
1399
1400 The keywords that are given in the PNG Specification are:
1401
1402     Title            Short (one line) title or
1403                      caption for image
1404     Author           Name of image's creator
1405     Description      Description of image (possibly long)
1406     Copyright        Copyright notice
1407     Creation Time    Time of original image creation
1408                      (usually RFC 1123 format, see below)
1409     Software         Software used to create the image
1410     Disclaimer       Legal disclaimer
1411     Warning          Warning of nature of content
1412     Source           Device used to create the image
1413     Comment          Miscellaneous comment; conversion
1414                      from other image format
1415
1416 The keyword-text pairs work like this.  Keywords should be short
1417 simple descriptions of what the comment is about.  Some typical
1418 keywords are found in the PNG specification, as is some recommendations
1419 on keywords.  You can repeat keywords in a file.  You can even write
1420 some text before the image and some after.  For example, you may want
1421 to put a description of the image before the image, but leave the
1422 disclaimer until after, so viewers working over modem connections
1423 don't have to wait for the disclaimer to go over the modem before
1424 they start seeing the image.  Finally, keywords should be full
1425 words, not abbreviations.  Keywords and text are in the ISO 8859-1
1426 (Latin-1) character set (a superset of regular ASCII) and can not
1427 contain NUL characters, and should not contain control or other
1428 unprintable characters.  To make the comments widely readable, stick
1429 with basic ASCII, and avoid machine specific character set extensions
1430 like the IBM-PC character set.  The keyword must be present, but
1431 you can leave off the text string on non-compressed pairs.
1432 Compressed pairs must have a text string, as only the text string
1433 is compressed anyway, so the compression would be meaningless.
1434
1435 PNG supports modification time via the png_time structure.  Two
1436 conversion routines are proved, png_convert_from_time_t() for
1437 time_t and png_convert_from_struct_tm() for struct tm.  The
1438 time_t routine uses gmtime().  You don't have to use either of
1439 these, but if you wish to fill in the png_time structure directly,
1440 you should provide the time in universal time (GMT) if possible
1441 instead of your local time.  Note that the year number is the full
1442 year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and
1443 that months start with 1.
1444
1445 If you want to store the time of the original image creation, you should
1446 use a plain tEXt chunk with the "Creation Time" keyword.  This is
1447 necessary because the "creation time" of a PNG image is somewhat vague,
1448 depending on whether you mean the PNG file, the time the image was
1449 created in a non-PNG format, a still photo from which the image was
1450 scanned, or possibly the subject matter itself.  In order to facilitate
1451 machine-readable dates, it is recommended that the "Creation Time"
1452 tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"),
1453 although this isn't a requirement.  Unlike the tIME chunk, the
1454 "Creation Time" tEXt chunk is not expected to be automatically changed
1455 by the software.  To facilitate the use of RFC 1123 dates, a function
1456 png_convert_to_rfc1123(png_timep) is provided to convert from PNG
1457 time to an RFC 1123 format string.
1458
1459 You are now ready to write all the file information up to the actual
1460 image data.  You do this with a call to png_write_info().
1461
1462     png_write_info(png_ptr, info_ptr);
1463
1464 After you've written the file information, you can set up the library
1465 to handle any special transformations of the image data.  The various
1466 ways to transform the data will be described in the order that they
1467 should occur.  This is important, as some of these change the color
1468 type and/or bit depth of the data, and some others only work on
1469 certain color types and bit depths.  Even though each transformation
1470 checks to see if it has data that it can do something with, you should
1471 make sure to only enable a transformation if it will be valid for the
1472 data.  For example, don't swap red and blue on grayscale data.
1473
1474 PNG files store RGB pixels packed into 3 or 6 bytes.  This code tells
1475 the library to expand the input data to 4 or 8 bytes per pixel
1476 (or expand 1 or 2-byte grayscale data to 2 or 4 bytes per pixel).
1477
1478     png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1479
1480 where the 0 is the value that will be put in the 4th byte, and the
1481 location is either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending
1482 upon whether the filler byte is stored XRGB or RGBX.
1483
1484 PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
1485 they can, resulting in, for example, 8 pixels per byte for 1 bit files.
1486 If the data is supplied at 1 pixel per byte, use this code, which will
1487 correctly pack the pixels into a single byte:
1488
1489     png_set_packing(png_ptr);
1490
1491 PNG files reduce possible bit depths to 1, 2, 4, 8, and 16.  If your
1492 data is of another bit depth, you can write an sBIT chunk into the
1493 file so that decoders can get the original data if desired.
1494
1495     /* Set the true bit depth of the image data */
1496     if (color_type & PNG_COLOR_MASK_COLOR)
1497     {
1498         sig_bit.red = true_bit_depth;
1499         sig_bit.green = true_bit_depth;
1500         sig_bit.blue = true_bit_depth;
1501     }
1502     else
1503     {
1504         sig_bit.gray = true_bit_depth;
1505     }
1506     if (color_type & PNG_COLOR_MASK_ALPHA)
1507     {
1508         sig_bit.alpha = true_bit_depth;
1509     }
1510
1511     png_set_sBIT(png_ptr, info_ptr, &sig_bit);
1512
1513 If the data is stored in the row buffer in a bit depth other than
1514 one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG),
1515 this will scale the values to appear to be the correct bit depth as
1516 is required by PNG.
1517
1518     png_set_shift(png_ptr, &sig_bit);
1519
1520 PNG files store 16 bit pixels in network byte order (big-endian,
1521 ie. most significant bits first).  This code would be used if they are
1522 supplied the other way (little-endian, i.e. least significant bits
1523 first, the way PCs store them):
1524
1525     if (bit_depth > 8)
1526        png_set_swap(png_ptr);
1527
1528 If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
1529 need to change the order the pixels are packed into bytes, you can use:
1530
1531     if (bit_depth < 8)
1532        png_set_packswap(png_ptr);
1533
1534 PNG files store 3 color pixels in red, green, blue order.  This code
1535 would be used if they are supplied as blue, green, red:
1536
1537     png_set_bgr(png_ptr);
1538
1539 PNG files describe monochrome as black being zero and white being
1540 one. This code would be used if the pixels are supplied with this reversed
1541 (black being one and white being zero):
1542
1543     png_set_invert_mono(png_ptr);
1544
1545 Finally, you can write your own transformation function if none of
1546 the existing ones meets your needs.  This is done by setting a callback
1547 with
1548
1549     png_set_write_user_transform_fn(png_ptr,
1550        write_transform_fn);
1551
1552 You must supply the function
1553
1554     void write_transform_fn(png_ptr ptr, row_info_ptr
1555        row_info, png_bytep data)
1556
1557 See pngtest.c for a working example.  Your function will be called
1558 before any of the other transformations have been processed.
1559
1560 It is possible to have libpng flush any pending output, either manually,
1561 or automatically after a certain number of lines have been written.  To
1562 flush the output stream a single time call:
1563
1564     png_write_flush(png_ptr);
1565
1566 and to have libpng flush the output stream periodically after a certain
1567 number of scanlines have been written, call:
1568
1569     png_set_flush(png_ptr, nrows);
1570
1571 Note that the distance between rows is from the last time png_write_flush()
1572 was called, or the first row of the image if it has never been called.
1573 So if you write 50 lines, and then png_set_flush 25, it will flush the
1574 output on the next scanline, and every 25 lines thereafter, unless
1575 png_write_flush() is called before 25 more lines have been written.
1576 If nrows is too small (less than about 10 lines for a 640 pixel wide
1577 RGB image) the image compression may decrease noticeably (although this
1578 may be acceptable for real-time applications).  Infrequent flushing will
1579 only degrade the compression performance by a few percent over images
1580 that do not use flushing.
1581
1582 That's it for the transformations.  Now you can write the image data.
1583 The simplest way to do this is in one function call.  If have the
1584 whole image in memory, you can just call png_write_image() and libpng
1585 will write the image.  You will need to pass in an array of pointers to
1586 each row.  This function automatically handles interlacing, so you don't
1587 need to call png_set_interlace_handling() or call this function multiple
1588 times, or any of that other stuff necessary with png_write_rows().
1589
1590     png_write_image(png_ptr, row_pointers);
1591
1592 where row_pointers is:
1593
1594     png_byte *row_pointers[height];
1595
1596 You can point to void or char or whatever you use for pixels.
1597
1598 If you don't want to write the whole image at once, you can
1599 use png_write_rows() instead.  If the file is not interlaced,
1600 this is simple:
1601
1602     png_write_rows(png_ptr, row_pointers,
1603        number_of_rows);
1604
1605 row_pointers is the same as in the png_write_image() call.
1606
1607 If you are just writing one row at a time, you can do this with
1608 row_pointers:
1609
1610     png_bytep row_pointer = row;
1611
1612     png_write_row(png_ptr, &row_pointer);
1613
1614 When the file is interlaced, things can get a good deal more
1615 complicated.  The only currently (as of February 1998 -- PNG Specification
1616 version 1.0, dated October 1996) defined interlacing scheme for PNG files
1617 is the "Adam7" interlace scheme, that breaks down an
1618 image into seven smaller images of varying size.  libpng will build
1619 these images for you, or you can do them yourself.  If you want to
1620 build them yourself, see the PNG specification for details of which
1621 pixels to write when.
1622
1623 If you don't want libpng to handle the interlacing details, just
1624 use png_set_interlace_handling() and call png_write_rows() the
1625 correct number of times to write all seven sub-images.
1626
1627 If you want libpng to build the sub-images, call this before you start
1628 writing any rows:
1629
1630     number_of_passes =
1631        png_set_interlace_handling(png_ptr);
1632
1633 This will return the number of passes needed.  Currently, this
1634 is seven, but may change if another interlace type is added.
1635
1636 Then write the complete image number_of_passes times.
1637
1638     png_write_rows(png_ptr, row_pointers,
1639        number_of_rows);
1640
1641 As some of these rows are not used, and thus return immediately,
1642 you may want to read about interlacing in the PNG specification,
1643 and only update the rows that are actually used.
1644
1645 After you are finished writing the image, you should finish writing
1646 the file.  If you are interested in writing comments or time, you should
1647 pass an appropriately filled png_info pointer.  If you are not interested,
1648 you can pass NULL.
1649
1650     png_write_end(png_ptr, info_ptr);
1651
1652 When you are done, you can free all memory used by libpng like this:
1653
1654     png_destroy_write_struct(&png_ptr, &info_ptr);
1655
1656 You must free any data you allocated for info_ptr, such as comments,
1657 palette, or histogram, before the call to png_destroy_write_struct();
1658
1659 For a more compact example of writing a PNG image, see the file example.c.
1660
1661
1662 V. Modifying/Customizing libpng:
1663
1664 There are two issues here.  The first is changing how libpng does
1665 standard things like memory allocation, input/output, and error handling.
1666 The second deals with more complicated things like adding new chunks,
1667 adding new transformations, and generally changing how libpng works.
1668
1669 All of the memory allocation, input/output, and error handling in libpng
1670 goes through callbacks that are user settable.  The default routines are
1671 in pngmem.c, pngrio.c, pngwio.c, and pngerror.c respectively.  To change
1672 these functions, call the appropriate png_set_???_fn() function.
1673
1674 Memory allocation is done through the functions png_large_malloc(),
1675 png_malloc(), png_realloc(), png_large_free(), and png_free().  These
1676 currently just call the standard C functions.  The large functions must
1677 handle exactly 64K, but they don't have to handle more than that.  If
1678 your pointers can't access more then 64K at a time, you will want to set
1679 MAXSEG_64K in zlib.h.  Since it is unlikely that the method of handling
1680 memory allocation on a platform will change between applications, these
1681 functions must be modified in the library at compile time.
1682
1683 Input/Output in libpng is done through png_read() and png_write(),
1684 which currently just call fread() and fwrite().  The FILE * is stored in
1685 png_struct and is initialized via png_init_io().  If you wish to change
1686 the method of I/O, the library supplies callbacks that you can set
1687 through the function png_set_read_fn() and png_set_write_fn() at run
1688 time, instead of calling the png_init_io() function.  These functions
1689 also provide a void pointer that can be retrieved via the function
1690 png_get_io_ptr().  For example:
1691
1692     png_set_read_fn(png_structp read_ptr,
1693         voidp read_io_ptr, png_rw_ptr read_data_fn)
1694
1695     png_set_write_fn(png_structp write_ptr,
1696         voidp write_io_ptr, png_rw_ptr write_data_fn,
1697         png_flush_ptr output_flush_fn);
1698
1699     voidp read_io_ptr = png_get_io_ptr(read_ptr);
1700     voidp write_io_ptr = png_get_io_ptr(write_ptr);
1701
1702 The replacement I/O functions should have prototypes as follows:
1703
1704     void user_read_data(png_structp png_ptr,
1705         png_bytep data, png_uint_32 length);
1706     void user_write_data(png_structp png_ptr,
1707         png_bytep data, png_uint_32 length);
1708     void user_flush_data(png_structp png_ptr);
1709
1710 Supplying NULL for the read, write, or flush functions sets them back
1711 to using the default C stream functions.  It is an error to read from
1712 a write stream, and vice versa.
1713
1714 Error handling in libpng is done through png_error() and png_warning().
1715 Errors handled through png_error() are fatal, meaning that png_error()
1716 should never return to its caller.  Currently, this is handled via
1717 setjmp() and longjmp(), but you could change this to do things like
1718 exit() if you should wish.  On non-fatal errors, png_warning() is called
1719 to print a warning message, and then control returns to the calling code.
1720 By default png_error() and png_warning() print a message on stderr via
1721 fprintf() unless the library is compiled with PNG_NO_STDIO defined.  If
1722 you wish to change the behavior of the error functions, you will need to
1723 set up your own message callbacks.  These functions are normally supplied
1724 at the time that the png_struct is created.  It is also possible to change
1725 these functions after png_create_???_struct() has been called by calling:
1726
1727     png_set_error_fn(png_structp png_ptr,
1728         png_voidp error_ptr, png_error_ptr error_fn,
1729         png_error_ptr warning_fn);
1730
1731     png_voidp error_ptr = png_get_error_ptr(png_ptr);
1732
1733 If NULL is supplied for either error_fn or warning_fn, then the libpng
1734 default function will be used, calling fprintf() and/or longjmp() if a
1735 problem is encountered.  The replacement error functions should have
1736 parameters as follows:
1737
1738     void user_error_fn(png_structp png_ptr,
1739         png_const_charp error_msg);
1740     void user_warning_fn(png_structp png_ptr,
1741         png_const_charp warning_msg);
1742
1743 The motivation behind using setjmp() and longjmp() is the C++ throw and
1744 catch exception handling methods.  This makes the code much easier to write,
1745 as there is no need to check every return code of every function call.
1746 However, there are some uncertainties about the status of local variables
1747 after a longjmp, so the user may want to be careful about doing anything after
1748 setjmp returns non-zero besides returning itself.  Consult your compiler
1749 documentation for more details.
1750
1751 If you need to read or write custom chunks, you will need to get deeper
1752 into the libpng code, as a mechanism has not yet been supplied for user
1753 callbacks with custom chunks.  First, read the PNG specification, and have
1754 a first level of understanding of how it works.  Pay particular attention
1755 to the sections that describe chunk names, and look at how other chunks
1756 were designed, so you can do things similarly.  Second, check out the
1757 sections of libpng that read and write chunks.  Try to find a chunk that
1758 is similar to yours and copy off of it.  More details can be found in the
1759 comments inside the code.  A way of handling unknown chunks in a generic
1760 method, potentially via callback functions, would be best.
1761
1762 If you wish to write your own transformation for the data, look through
1763 the part of the code that does the transformations, and check out some of
1764 the simpler ones to get an idea of how they work.  Try to find a similar
1765 transformation to the one you want to add and copy off of it.  More details
1766 can be found in the comments inside the code itself.
1767
1768 Configuring for 16 bit platforms:
1769
1770 You may need to change the png_large_malloc() and png_large_free()
1771 routines in pngmem.c, as these are required to allocate 64K, although
1772 there is already support for many of the common DOS compilers.  Also,
1773 you will want to look into zconf.h to tell zlib (and thus libpng) that
1774 it cannot allocate more then 64K at a time.  Even if you can, the memory
1775 won't be accessible.  So limit zlib and libpng to 64K by defining MAXSEG_64K.
1776
1777 Configuring for DOS:
1778
1779 For DOS users who only have access to the lower 640K, you will
1780 have to limit zlib's memory usage via a png_set_compression_mem_level()
1781 call.  See zlib.h or zconf.h in the zlib library for more information.
1782
1783 Configuring for Medium Model:
1784
1785 Libpng's support for medium model has been tested on most of the popular
1786 compilers.  Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
1787 defined, and FAR gets defined to far in pngconf.h, and you should be
1788 all set.  Everything in the library (except for zlib's structure) is
1789 expecting far data.  You must use the typedefs with the p or pp on
1790 the end for pointers (or at least look at them and be careful).  Make
1791 note that the row's of data are defined as png_bytepp, which is an
1792 unsigned char far * far *.
1793
1794 Configuring for gui/windowing platforms:
1795
1796 You will need to write new error and warning functions that use the GUI
1797 interface, as described previously, and set them to be the error and
1798 warning functions at the time that png_create_???_struct() is called,
1799 in order to have them available during the structure initialization.
1800 They can be changed later via png_set_error_fn().  On some compilers,
1801 you may also have to change the memory allocators (png_malloc, etc.).
1802
1803 Configuring for compiler xxx:
1804
1805 All includes for libpng are in pngconf.h.  If you need to add/change/delete
1806 an include, this is the place to do it.  The includes that are not
1807 needed outside libpng are protected by the PNG_INTERNAL definition,
1808 which is only defined for those routines inside libpng itself.  The
1809 files in libpng proper only include png.h, which includes pngconf.h.
1810
1811 Configuring zlib:
1812
1813 There are special functions to configure the compression.  Perhaps the
1814 most useful one changes the compression level, which currently uses
1815 input compression values in the range 0 - 9.  The library normally
1816 uses the default compression level (Z_DEFAULT_COMPRESSION = 6).  Tests
1817 have shown that for a large majority of images, compression values in
1818 the range 3-6 compress nearly as well as higher levels, and do so much
1819 faster.  For online applications it may be desirable to have maximum speed
1820 (Z_BEST_SPEED = 1).  With versions of zlib after v0.99, you can also
1821 specify no compression (Z_NO_COMPRESSION = 0), but this would create
1822 files larger than just storing the raw bitmap.  You can specify the
1823 compression level by calling:
1824
1825     png_set_compression_level(png_ptr, level);
1826
1827 Another useful one is to reduce the memory level used by the library.
1828 The memory level defaults to 8, but it can be lowered if you are
1829 short on memory (running DOS, for example, where you only have 640K).
1830
1831     png_set_compression_mem_level(png_ptr, level);
1832
1833 The other functions are for configuring zlib.  They are not recommended
1834 for normal use and may result in writing an invalid PNG file.  See
1835 zlib.h for more information on what these mean.
1836
1837     png_set_compression_strategy(png_ptr,
1838         strategy);
1839     png_set_compression_window_bits(png_ptr,
1840         window_bits);
1841     png_set_compression_method(png_ptr, method);
1842
1843 Controlling row filtering:
1844
1845 If you want to control whether libpng uses filtering or not, which
1846 filters are used, and how it goes about picking row filters, you
1847 can call one of these functions.  The selection and configuration
1848 of row filters can have a significant impact on the size and
1849 encoding speed and a somewhat lesser impact on the decoding speed
1850 of an image.  Filtering is enabled by default for RGB and grayscale
1851 images (with and without alpha), but not for paletted images nor
1852 for any images with bit depths less than 8 bits/pixel.
1853
1854 The 'method' parameter sets the main filtering method, which is
1855 currently only '0' in the PNG 1.0 specification.  The 'filters'
1856 parameter sets which filter(s), if any, should be used for each
1857 scanline.  Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
1858 to turn filtering on and off, respectively.
1859
1860 Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
1861 PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
1862 ORed together '|' to specify one or more filters to use.  These
1863 filters are described in more detail in the PNG specification.  If
1864 you intend to change the filter type during the course of writing
1865 the image, you should start with flags set for all of the filters
1866 you intend to use so that libpng can initialize its internal
1867 structures appropriately for all of the filter types.
1868
1869     filters = PNG_FILTER_NONE | PNG_FILTER_SUB
1870        | PNG_FILTER_UP;
1871     png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
1872        filters);
1873
1874 It is also possible to influence how libpng chooses from among the
1875 available filters.  This is done in two ways - by telling it how
1876 important it is to keep the same filter for successive rows, and
1877 by telling it the relative computational costs of the filters.
1878
1879     double weights[3] = {1.5, 1.3, 1.1},
1880        costs[PNG_FILTER_VALUE_LAST] =
1881        {1.0, 1.3, 1.3, 1.5, 1.7};
1882
1883     png_set_filter_selection(png_ptr,
1884        PNG_FILTER_SELECTION_WEIGHTED, 3,
1885        weights, costs);
1886
1887 The weights are multiplying factors that indicate to libpng that the
1888 row filter should be the same for successive rows unless another row filter
1889 is that many times better than the previous filter.  In the above example,
1890 if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
1891 "sum of absolute differences" 1.5 x 1.3 times higher than other filters
1892 and still be chosen, while the NONE filter could have a sum 1.1 times
1893 higher than other filters and still be chosen.  Unspecified weights are
1894 taken to be 1.0, and the specified weights should probably be declining
1895 like those above in order to emphasize recent filters over older filters.
1896
1897 The filter costs specify for each filter type a relative decoding cost
1898 to be considered when selecting row filters.  This means that filters
1899 with higher costs are less likely to be chosen over filters with lower
1900 costs, unless their "sum of absolute differences" is that much smaller.
1901 The costs do not necessarily reflect the exact computational speeds of
1902 the various filters, since this would unduly influence the final image
1903 size.
1904
1905 Note that the numbers above were invented purely for this example and
1906 are given only to help explain the function usage.  Little testing has
1907 been done to find optimum values for either the costs or the weights.
1908
1909 Removing unwanted object code:
1910
1911 There are a bunch of #define's in pngconf.h that control what parts of
1912 libpng are compiled.  All the defines end in _SUPPORTED.  If you are
1913 never going to use a capability, you can change the #define to #undef
1914 before recompiling libpng and save yourself code and data space, or
1915 you can turn off individual capabilities with defines that begin with
1916 PNG_NO_.
1917
1918 You can also turn all of the transforms and ancillary chunk capabilities
1919 off en masse with  compiler directives that define
1920 PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS,
1921 or all four,
1922 along with directives to turn on any of the capabilities that you do
1923 want.  The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable
1924 the extra transformations but still leave the library fully capable of reading
1925 and writing PNG files with all known public chunks [except for sPLT].
1926 Use of the PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive
1927 produces a library that is incapable of reading or writing ancillary chunks.
1928 If you are not using the progressive reading capability, you can
1929 turn that off with PNG_NO_PROGRESSIVE_READ (don't confuse
1930 this with the INTERLACING capability, which you'll still have).
1931
1932 All the reading and writing specific code are in separate files, so the
1933 linker should only grab the files it needs.  However, if you want to
1934 make sure, or if you are building a stand alone library, all the
1935 reading files start with pngr and all the writing files start with
1936 pngw.  The files that don't match either (like png.c, pngtrans.c, etc.)
1937 are used for both reading and writing, and always need to be included.
1938 The progressive reader is in pngpread.c
1939
1940 If you are creating or distributing a dynamically linked library (a .so
1941 or DLL file), you should not remove or disable any parts of the library,
1942 as this will cause applications linked with different versions of the
1943 library to fail if they call functions not available in your library.
1944 The size of the library itself should not be an issue, because only
1945 those sections that are actually used will be loaded into memory.
1946
1947 Requesting debug printout:
1948
1949 The macro definition PNG_DEBUG can be used to request debugging
1950 printout.  Set it to an integer value in the range 0 to 3.  Higher
1951 numbers result in increasing amounts of debugging information.  The
1952 information is printed to the "stderr" file, unless another file
1953 name is specified in the PNG_DEBUG_FILE macro definition.
1954
1955 When PNG_DEBUG > 0, the following functions (macros) become available:
1956
1957    png_debug(level, message)
1958    png_debug1(level, message, p1)
1959    png_debug2(level, message, p1, p2)
1960
1961 in which "level" is compared to PNG_DEBUG to decide whether to print
1962 the message, "message" is the formatted string to be printed,
1963 and p1 and p2 are parameters that are to be embedded in the string
1964 according to printf-style formatting directives.  For example,
1965
1966    png_debug1(2, "foo=%d\n", foo);
1967
1968 is expanded to
1969
1970    if(PNG_DEBUG > 2)
1971      fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
1972
1973 When PNG_DEBUG is defined but is zero, the macros aren't defined, but you
1974 can still use PNG_DEBUG to control your own debugging:
1975
1976    #ifdef PNG_DEBUG
1977        fprintf(stderr, ...
1978    #endif
1979
1980 When PNG_DEBUG = 1, the macros are defined, but only png_debug statements
1981 having level = 0 will be printed.  There aren't any such statements in
1982 this version of libpng, but if you insert some they will be printed.
1983
1984 VI.  Changes to Libpng from version 0.88
1985
1986 It should be noted that versions of libpng later than 0.96 are not
1987 distributed by the original libpng author, Guy Schalnat, nor by
1988 Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
1989 distributed versions 0.89 through 0.96, but rather by another member
1990 of the original PNG Group, Glenn Randers-Pehrson.  Guy and Andreas are
1991 still alive and well, but they have moved on to other things.
1992
1993 The old libpng functions png_read_init(), png_write_init(),
1994 png_info_init(), png_read_destroy(), and png_write_destory() have been
1995 moved to PNG_INTERNAL in version 0.95 to discourage their use.  The
1996 preferred method of creating and initializing the libpng structures is
1997 via the png_create_read_struct(), png_create_write_struct(), and
1998 png_create_info_struct() because they isolate the size of the structures
1999 from the application, allow version error checking, and also allow the
2000 use of custom error handling routines during the initialization, which
2001 the old functions do not.  The functions png_read_destroy() and
2002 png_write_destroy() do not actually free the memory that libpng
2003 allocated for these structs, but just reset the data structures, so they
2004 can be used instead of png_destroy_read_struct() and
2005 png_destroy_write_struct() if you feel there is too much system overhead
2006 allocating and freeing the png_struct for each image read.
2007
2008 Setting the error callbacks via png_set_message_fn() before
2009 png_read_init() as was suggested in libpng-0.88 is no longer supported
2010 because this caused applications that do not use custom error functions
2011 to fail if the png_ptr was not initialized to zero.  It is still possible
2012 to set the error callbacks AFTER png_read_init(), or to change them with
2013 png_set_error_fn(), which is essentially the same function, but with a
2014 new name to force compilation errors with applications that try to use
2015 the old method.
2016
2017 VII. Y2K Compliance in libpng
2018
2019 January 13, 1999
2020
2021 Since the PNG Development group is an ad-hoc body, we can't make
2022 an official declaration.
2023
2024 This is your unofficial assurance that libpng from version 0.81 and
2025 upward are Y2K compliant.  It is my belief that earlier versions were
2026 also Y2K compliant.
2027
2028 Libpng only has three year fields.  One is a 2-byte unsigned integer that
2029 will hold years up to 65535.  The other two hold the date in text
2030 format, and will hold years up to 9999.
2031
2032 The integer is
2033     "png_uint_16 year" in png_time_struct.
2034
2035 The strings are
2036     "png_charp time_buffer" in png_struct and
2037     "near_time_buffer", which is a local character string in png.c.
2038
2039 There are seven time-related functions:
2040
2041     png_convert_to_rfc_1123() in png.c 
2042       (formerly png_convert_to_rfc_1152() in error)
2043     png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
2044     png_convert_from_time_t() in pngwrite.c
2045     png_get_tIME() in pngget.c
2046     png_handle_tIME() in pngrutil.c, called in pngread.c
2047     png_set_tIME() in pngset.c
2048     png_write_tIME() in pngwutil.c, called in pngwrite.c
2049
2050 All appear to handle dates properly in a Y2K environment.  The 
2051 png_convert_from_time_t() function calls gmtime() to convert from system
2052 clock time, which returns (year - 1900), which we properly convert to
2053 the full 4-digit year.  There is a possibility that applications using
2054 libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
2055 function, or incorrectly passing only a 2-digit year instead of
2056 "year - 1900" into the png_convert_from_struct_tm() function, but this
2057 is not under our control.  The libpng documentation has always stated
2058 that it works with 4-digit years, and the APIs have been documented as
2059 such.
2060
2061 The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
2062 integer to hold the year, and can hold years as large as 65535.
2063
2064
2065    Glenn Randers-Pehrson
2066    libpng maintainer
2067    PNG Development Group