1 libpng.txt - A description on how to use and modify libpng
3 libpng version 1.4.1 - February 25, 2010
4 Updated and distributed by Glenn Randers-Pehrson
5 <glennrp at users.sourceforge.net>
6 Copyright (c) 1998-2009 Glenn Randers-Pehrson
8 This document is released under the libpng license.
9 For conditions of distribution and use, see the disclaimer
14 libpng versions 0.97, January 1998, through 1.4.1 - February 25, 2010
15 Updated and distributed by Glenn Randers-Pehrson
16 Copyright (c) 1998-2009 Glenn Randers-Pehrson
18 libpng 1.0 beta 6 version 0.96 May 28, 1997
19 Updated and distributed by Andreas Dilger
20 Copyright (c) 1996, 1997 Andreas Dilger
22 libpng 1.0 beta 2 - version 0.88 January 26, 1996
23 For conditions of distribution and use, see copyright
24 notice in png.h. Copyright (c) 1995, 1996 Guy Eric
25 Schalnat, Group 42, Inc.
27 Updated/rewritten per request in the libpng FAQ
28 Copyright (c) 1995, 1996 Frank J. T. Wojcik
29 December 18, 1995 & January 20, 1996
33 This file describes how to use and modify the PNG reference library
34 (known as libpng) for your own use. There are five sections to this
35 file: introduction, structures, reading, writing, and modification and
36 configuration notes for various special platforms. In addition to this
37 file, example.c is a good starting point for using the library, as
38 it is heavily commented and should include everything most people
39 will need. We assume that libpng is already installed; see the
40 INSTALL file for instructions on how to install libpng.
42 For examples of libpng usage, see the files "example.c", "pngtest.c",
43 and the files in the "contrib" directory, all of which are included in
44 the libpng distribution.
46 Libpng was written as a companion to the PNG specification, as a way
47 of reducing the amount of time and effort it takes to support the PNG
48 file format in application programs.
50 The PNG specification (second edition), November 2003, is available as
51 a W3C Recommendation and as an ISO Standard (ISO/IEC 15948:2003 (E)) at
52 <http://www.w3.org/TR/2003/REC-PNG-20031110/
53 The W3C and ISO documents have identical technical content.
55 The PNG-1.2 specification is available at
56 <http://www.libpng.org/pub/png/documents/>. It is technically equivalent
57 to the PNG specification (second edition) but has some additional material.
59 The PNG-1.0 specification is available
60 as RFC 2083 <http://www.libpng.org/pub/png/documents/> and as a
61 W3C Recommendation <http://www.w3.org/TR/REC.png.html>.
63 Some additional chunks are described in the special-purpose public chunks
64 documents at <http://www.libpng.org/pub/png/documents/>.
67 about PNG, and the latest version of libpng, can be found at the PNG home
68 page, <http://www.libpng.org/pub/png/>.
70 Most users will not have to modify the library significantly; advanced
71 users may want to modify it more. All attempts were made to make it as
72 complete as possible, while keeping the code easy to understand.
73 Currently, this library only supports C. Support for other languages
76 Libpng has been designed to handle multiple sessions at one time,
77 to be easily modifiable, to be portable to the vast majority of
78 machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
79 to use. The ultimate goal of libpng is to promote the acceptance of
80 the PNG file format in whatever way possible. While there is still
81 work to be done (see the TODO file), libpng should cover the
82 majority of the needs of its users.
84 Libpng uses zlib for its compression and decompression of PNG files.
85 Further information about zlib, and the latest version of zlib, can
86 be found at the zlib home page, <http://www.info-zip.org/pub/infozip/zlib/>.
87 The zlib compression utility is a general purpose utility that is
88 useful for more than PNG files, and can be used without libpng.
89 See the documentation delivered with zlib for more details.
90 You can usually find the source files for the zlib utility wherever you
91 find the libpng source files.
93 Libpng is thread safe, provided the threads are using different
94 instances of the structures. Each thread should have its own
95 png_struct and png_info instances, and thus its own image.
96 Libpng does not protect itself against two threads using the
97 same instance of a structure.
101 There are two main structures that are important to libpng, png_struct
102 and png_info. The first, png_struct, is an internal structure that
103 will not, for the most part, be used by a user except as the first
104 variable passed to every libpng function call.
106 The png_info structure is designed to provide information about the
107 PNG file. At one time, the fields of png_info were intended to be
108 directly accessible to the user. However, this tended to cause problems
109 with applications using dynamically loaded libraries, and as a result
110 a set of interface functions for png_info (the png_get_*() and png_set_*()
111 functions) was developed. The fields of png_info are still available for
112 older applications, but it is suggested that applications use the new
113 interfaces if at all possible.
115 Applications that do make direct access to the members of png_struct (except
116 for png_ptr->jmpbuf) must be recompiled whenever the library is updated,
117 and applications that make direct access to the members of png_info must
118 be recompiled if they were compiled or loaded with libpng version 1.0.6,
119 in which the members were in a different order. In version 1.0.7, the
120 members of the png_info structure reverted to the old order, as they were
121 in versions 0.97c through 1.0.5. Starting with version 2.0.0, both
122 structures are going to be hidden, and the contents of the structures will
123 only be accessible through the png_get/png_set functions.
125 The png.h header file is an invaluable reference for programming with libpng.
126 And while I'm on the topic, make sure you include the libpng header file:
132 We'll now walk you through the possible functions to call when reading
133 in a PNG file sequentially, briefly explaining the syntax and purpose
134 of each one. See example.c and png.h for more detail. While
135 progressive reading is covered in the next section, you will still
136 need some of the functions discussed in this section to read a PNG
141 You will want to do the I/O initialization(*) before you get into libpng,
142 so if it doesn't work, you don't have much to undo. Of course, you
143 will also want to insure that you are, in fact, dealing with a PNG
144 file. Libpng provides a simple check to see if a file is a PNG file.
145 To use it, pass in the first 1 to 8 bytes of the file to the function
146 png_sig_cmp(), and it will return 0 (false) if the bytes match the
147 corresponding bytes of the PNG signature, or nonzero (true) otherwise.
148 Of course, the more bytes you pass in, the greater the accuracy of the
151 If you are intending to keep the file pointer open for use in libpng,
152 you must ensure you don't read more than 8 bytes from the beginning
153 of the file, and you also have to make a call to png_set_sig_bytes_read()
154 with the number of bytes you read from the beginning. Libpng will
155 then only check the bytes (if any) that your program didn't read.
157 (*): If you are not using the standard I/O functions, you will need
158 to replace them with custom functions. See the discussion under
162 FILE *fp = fopen(file_name, "rb");
167 fread(header, 1, number, fp);
168 is_png = !png_sig_cmp(header, 0, number);
175 Next, png_struct and png_info need to be allocated and initialized. In
176 order to ensure that the size of these structures is correct even with a
177 dynamically linked libpng, there are functions to initialize and
178 allocate the structures. We also pass the library version, optional
179 pointers to error handling functions, and a pointer to a data struct for
180 use by the error functions, if necessary (the pointer and functions can
181 be NULL if the default error handlers are to be used). See the section
182 on Changes to Libpng below regarding the old initialization functions.
183 The structure allocation functions quietly return NULL if they fail to
184 create the structure, so your application should check for that.
186 png_structp png_ptr = png_create_read_struct
187 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
188 user_error_fn, user_warning_fn);
192 png_infop info_ptr = png_create_info_struct(png_ptr);
195 png_destroy_read_struct(&png_ptr,
196 (png_infopp)NULL, (png_infopp)NULL);
200 png_infop end_info = png_create_info_struct(png_ptr);
203 png_destroy_read_struct(&png_ptr, &info_ptr,
208 If you want to use your own memory allocation routines,
209 define PNG_USER_MEM_SUPPORTED and use
210 png_create_read_struct_2() instead of png_create_read_struct():
212 png_structp png_ptr = png_create_read_struct_2
213 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
214 user_error_fn, user_warning_fn, (png_voidp)
215 user_mem_ptr, user_malloc_fn, user_free_fn);
217 The error handling routines passed to png_create_read_struct()
218 and the memory alloc/free routines passed to png_create_struct_2()
219 are only necessary if you are not using the libpng supplied error
220 handling and memory alloc/free functions.
222 When libpng encounters an error, it expects to longjmp back
223 to your routine. Therefore, you will need to call setjmp and pass
224 your png_jmpbuf(png_ptr). If you read the file from different
225 routines, you will need to update the jmpbuf field every time you enter
226 a new routine that will call a png_*() function.
228 See your documentation of setjmp/longjmp for your compiler for more
229 information on setjmp/longjmp. See the discussion on libpng error
230 handling in the Customizing Libpng section below for more information
231 on the libpng error handling. If an error occurs, and libpng longjmp's
232 back to your setjmp, you will want to call png_destroy_read_struct() to
235 if (setjmp(png_jmpbuf(png_ptr)))
237 png_destroy_read_struct(&png_ptr, &info_ptr,
243 If you would rather avoid the complexity of setjmp/longjmp issues,
244 you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case
245 errors will result in a call to PNG_ABORT() which defaults to abort().
247 Now you need to set up the input code. The default for libpng is to
248 use the C function fread(). If you use this, you will need to pass a
249 valid FILE * in the function png_init_io(). Be sure that the file is
250 opened in binary mode. If you wish to handle reading data in another
251 way, you need not call the png_init_io() function, but you must then
252 implement the libpng I/O methods discussed in the Customizing Libpng
255 png_init_io(png_ptr, fp);
257 If you had previously opened the file and read any of the signature from
258 the beginning in order to see if this was a PNG file, you need to let
259 libpng know that there are some bytes missing from the start of the file.
261 png_set_sig_bytes(png_ptr, number);
263 You can change the zlib compression buffer size to be used while
264 reading compressed data with
266 png_set_compression_buffer_size(png_ptr, buffer_size);
268 where the default size is 8192 bytes. Note that the buffer size
269 is changed immediately and the buffer is reallocated immediately,
270 instead of setting a flag to be acted upon later.
272 Setting up callback code
274 You can set up a callback function to handle any unknown chunks in the
275 input stream. You must supply the function
277 read_chunk_callback(png_ptr ptr,
278 png_unknown_chunkp chunk);
280 /* The unknown chunk structure contains your
281 chunk data, along with similar data for any other
288 /* Note that libpng has already taken care of
291 /* put your code here. Search for your chunk in the
292 unknown chunk structure, process it, and return one
295 return (-n); /* chunk had an error */
296 return (0); /* did not recognize */
297 return (n); /* success */
300 (You can give your function another name that you like instead of
301 "read_chunk_callback")
303 To inform libpng about your function, use
305 png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr,
306 read_chunk_callback);
308 This names not only the callback function, but also a user pointer that
309 you can retrieve with
311 png_get_user_chunk_ptr(png_ptr);
313 If you call the png_set_read_user_chunk_fn() function, then all unknown
314 chunks will be saved when read, in case your callback function will need
315 one or more of them. This behavior can be changed with the
316 png_set_keep_unknown_chunks() function, described below.
318 At this point, you can set up a callback function that will be
319 called after each row has been read, which you can use to control
320 a progress meter or the like. It's demonstrated in pngtest.c.
321 You must supply a function
323 void read_row_callback(png_ptr ptr, png_uint_32 row,
326 /* put your code here */
329 (You can give it another name that you like instead of "read_row_callback")
331 To inform libpng about your function, use
333 png_set_read_status_fn(png_ptr, read_row_callback);
335 Unknown-chunk handling
337 Now you get to set the way the library processes unknown chunks in the
338 input PNG stream. Both known and unknown chunks will be read. Normal
339 behavior is that known chunks will be parsed into information in
340 various info_ptr members while unknown chunks will be discarded. This
341 behavior can be wasteful if your application will never use some known
342 chunk types. To change this, you can call:
344 png_set_keep_unknown_chunks(png_ptr, keep,
345 chunk_list, num_chunks);
346 keep - 0: default unknown chunk handling
347 1: ignore; do not keep
348 2: keep only if safe-to-copy
349 3: keep even if unsafe-to-copy
350 You can use these definitions:
351 PNG_HANDLE_CHUNK_AS_DEFAULT 0
352 PNG_HANDLE_CHUNK_NEVER 1
353 PNG_HANDLE_CHUNK_IF_SAFE 2
354 PNG_HANDLE_CHUNK_ALWAYS 3
355 chunk_list - list of chunks affected (a byte string,
356 five bytes per chunk, NULL or '\0' if
358 num_chunks - number of chunks affected; if 0, all
359 unknown chunks are affected. If nonzero,
360 only the chunks in the list are affected
362 Unknown chunks declared in this way will be saved as raw data onto a
363 list of png_unknown_chunk structures. If a chunk that is normally
364 known to libpng is named in the list, it will be handled as unknown,
365 according to the "keep" directive. If a chunk is named in successive
366 instances of png_set_keep_unknown_chunks(), the final instance will
367 take precedence. The IHDR and IEND chunks should not be named in
368 chunk_list; if they are, libpng will process them normally anyway.
370 Here is an example of the usage of png_set_keep_unknown_chunks(),
371 where the private "vpAg" chunk will later be processed by a user chunk
374 png_byte vpAg[5]={118, 112, 65, 103, (png_byte) '\0'};
376 #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
377 png_byte unused_chunks[]=
379 104, 73, 83, 84, (png_byte) '\0', /* hIST */
380 105, 84, 88, 116, (png_byte) '\0', /* iTXt */
381 112, 67, 65, 76, (png_byte) '\0', /* pCAL */
382 115, 67, 65, 76, (png_byte) '\0', /* sCAL */
383 115, 80, 76, 84, (png_byte) '\0', /* sPLT */
384 116, 73, 77, 69, (png_byte) '\0', /* tIME */
390 #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
391 /* ignore all unknown chunks: */
392 png_set_keep_unknown_chunks(read_ptr, 1, NULL, 0);
393 /* except for vpAg: */
394 png_set_keep_unknown_chunks(read_ptr, 2, vpAg, 1);
395 /* also ignore unused known chunks: */
396 png_set_keep_unknown_chunks(read_ptr, 1, unused_chunks,
397 (int)sizeof(unused_chunks)/5);
402 The PNG specification allows the width and height of an image to be as
403 large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.
404 Since very few applications really need to process such large images,
405 we have imposed an arbitrary 1-million limit on rows and columns.
406 Larger images will be rejected immediately with a png_error() call. If
407 you wish to override this limit, you can use
409 png_set_user_limits(png_ptr, width_max, height_max);
411 to set your own limits, or use width_max = height_max = 0x7fffffffL
412 to allow all valid dimensions (libpng may reject some very large images
413 anyway because of potential buffer overflow conditions).
415 You should put this statement after you create the PNG structure and
416 before calling png_read_info(), png_read_png(), or png_process_data().
417 If you need to retrieve the limits that are being applied, use
419 width_max = png_get_user_width_max(png_ptr);
420 height_max = png_get_user_height_max(png_ptr);
422 The PNG specification sets no limit on the number of ancillary chunks
423 allowed in a PNG datastream. You can impose a limit on the total number
424 of sPLT, tEXt, iTXt, zTXt, and unknown chunks that will be stored, with
426 png_set_chunk_cache_max(png_ptr, user_chunk_cache_max);
428 where 0x7fffffffL means unlimited. You can retrieve this limit with
430 chunk_cache_max = png_get_chunk_cache_max(png_ptr);
432 This limit also applies to the number of buffers that can be allocated
433 by png_decompress_chunk() while decompressing iTXt, zTXt, and iCCP chunks.
435 You can also set a limit on the amount of memory that a compressed chunk
436 other than IDAT can occupy, with
438 png_set_chunk_malloc_max(png_ptr, user_chunk_malloc_max);
440 and you can retrieve the limit with
442 chunk_malloc_max = png_get_chunk_malloc_max(png_ptr);
444 Any chunks that would cause either of these limits to be exceeded will
447 The high-level read interface
449 At this point there are two ways to proceed; through the high-level
450 read interface, or through a sequence of low-level read operations.
451 You can use the high-level interface if (a) you are willing to read
452 the entire image into memory, and (b) the input transformations
453 you want to do are limited to the following set:
455 PNG_TRANSFORM_IDENTITY No transformation
456 PNG_TRANSFORM_STRIP_16 Strip 16-bit samples to
458 PNG_TRANSFORM_STRIP_ALPHA Discard the alpha channel
459 PNG_TRANSFORM_PACKING Expand 1, 2 and 4-bit
461 PNG_TRANSFORM_PACKSWAP Change order of packed
463 PNG_TRANSFORM_EXPAND Perform set_expand()
464 PNG_TRANSFORM_INVERT_MONO Invert monochrome images
465 PNG_TRANSFORM_SHIFT Normalize pixels to the
467 PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
469 PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
471 PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
473 PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
474 PNG_TRANSFORM_GRAY_TO_RGB Expand grayscale samples
475 to RGB (or GA to RGBA)
477 (This excludes setting a background color, doing gamma transformation,
478 dithering, and setting filler.) If this is the case, simply do this:
480 png_read_png(png_ptr, info_ptr, png_transforms, NULL)
482 where png_transforms is an integer containing the bitwise OR of some
483 set of transformation flags. This call is equivalent to png_read_info(),
484 followed the set of transformations indicated by the transform mask,
485 then png_read_image(), and finally png_read_end().
487 (The final parameter of this call is not yet used. Someday it might point
488 to transformation parameters required by some future input transform.)
490 You must use png_transforms and not call any png_set_transform() functions
491 when you use png_read_png().
493 After you have called png_read_png(), you can retrieve the image data
496 row_pointers = png_get_rows(png_ptr, info_ptr);
498 where row_pointers is an array of pointers to the pixel data for each row:
500 png_bytep row_pointers[height];
502 If you know your image size and pixel size ahead of time, you can allocate
503 row_pointers prior to calling png_read_png() with
505 if (height > PNG_UINT_32_MAX/png_sizeof(png_byte))
507 "Image is too tall to process in memory");
508 if (width > PNG_UINT_32_MAX/pixel_size)
510 "Image is too wide to process in memory");
511 row_pointers = png_malloc(png_ptr,
512 height*png_sizeof(png_bytep));
513 for (int i=0; i<height, i++)
514 row_pointers[i]=NULL; /* security precaution */
515 for (int i=0; i<height, i++)
516 row_pointers[i]=png_malloc(png_ptr,
518 png_set_rows(png_ptr, info_ptr, &row_pointers);
520 Alternatively you could allocate your image in one big block and define
521 row_pointers[i] to point into the proper places in your block.
523 If you use png_set_rows(), the application is responsible for freeing
524 row_pointers (and row_pointers[i], if they were separately allocated).
526 If you don't allocate row_pointers ahead of time, png_read_png() will
527 do it, and it'll be free'ed when you call png_destroy_*().
529 The low-level read interface
531 If you are going the low-level route, you are now ready to read all
532 the file information up to the actual image data. You do this with a
533 call to png_read_info().
535 png_read_info(png_ptr, info_ptr);
537 This will process all chunks up to but not including the image data.
539 Querying the info structure
541 Functions are used to get the information from the info_ptr once it
542 has been read. Note that these fields may not be completely filled
543 in until png_read_end() has read the chunk data following the image.
545 png_get_IHDR(png_ptr, info_ptr, &width, &height,
546 &bit_depth, &color_type, &interlace_type,
547 &compression_type, &filter_method);
549 width - holds the width of the image
550 in pixels (up to 2^31).
551 height - holds the height of the image
552 in pixels (up to 2^31).
553 bit_depth - holds the bit depth of one of the
554 image channels. (valid values are
555 1, 2, 4, 8, 16 and depend also on
556 the color_type. See also
557 significant bits (sBIT) below).
558 color_type - describes which color/alpha channels
561 (bit depths 1, 2, 4, 8, 16)
562 PNG_COLOR_TYPE_GRAY_ALPHA
564 PNG_COLOR_TYPE_PALETTE
565 (bit depths 1, 2, 4, 8)
568 PNG_COLOR_TYPE_RGB_ALPHA
571 PNG_COLOR_MASK_PALETTE
575 filter_method - (must be PNG_FILTER_TYPE_BASE
576 for PNG 1.0, and can also be
577 PNG_INTRAPIXEL_DIFFERENCING if
578 the PNG datastream is embedded in
579 a MNG-1.0 datastream)
580 compression_type - (must be PNG_COMPRESSION_TYPE_BASE
582 interlace_type - (PNG_INTERLACE_NONE or
585 Any or all of interlace_type, compression_type, or
586 filter_method can be NULL if you are
587 not interested in their values.
589 Note that png_get_IHDR() returns 32-bit data into
590 the application's width and height variables.
591 This is an unsafe situation if these are 16-bit
592 variables. In such situations, the
593 png_get_image_width() and png_get_image_height()
594 functions described below are safer.
596 width = png_get_image_width(png_ptr,
598 height = png_get_image_height(png_ptr,
600 bit_depth = png_get_bit_depth(png_ptr,
602 color_type = png_get_color_type(png_ptr,
604 filter_method = png_get_filter_type(png_ptr,
606 compression_type = png_get_compression_type(png_ptr,
608 interlace_type = png_get_interlace_type(png_ptr,
611 channels = png_get_channels(png_ptr, info_ptr);
612 channels - number of channels of info for the
613 color type (valid values are 1 (GRAY,
614 PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
615 4 (RGB_ALPHA or RGB + filler byte))
616 rowbytes = png_get_rowbytes(png_ptr, info_ptr);
617 rowbytes - number of bytes needed to hold a row
619 signature = png_get_signature(png_ptr, info_ptr);
620 signature - holds the signature read from the
621 file (if any). The data is kept in
622 the same offset it would be if the
623 whole signature were read (i.e. if an
624 application had already read in 4
625 bytes of signature before starting
626 libpng, the remaining 4 bytes would
627 be in signature[4] through signature[7]
628 (see png_set_sig_bytes())).
630 These are also important, but their validity depends on whether the chunk
631 has been read. The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
632 png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
633 data has been read, or zero if it is missing. The parameters to the
634 png_get_<chunk> are set directly if they are simple data types, or a
635 pointer into the info_ptr is returned for any complex types.
637 png_get_PLTE(png_ptr, info_ptr, &palette,
639 palette - the palette for the file
641 num_palette - number of entries in the palette
643 png_get_gAMA(png_ptr, info_ptr, &gamma);
644 gamma - the gamma the file is written
647 png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
648 srgb_intent - the rendering intent (PNG_INFO_sRGB)
649 The presence of the sRGB chunk
650 means that the pixel data is in the
651 sRGB color space. This chunk also
652 implies specific values of gAMA and
655 png_get_iCCP(png_ptr, info_ptr, &name,
656 &compression_type, &profile, &proflen);
657 name - The profile name.
658 compression - The compression type; always
659 PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
660 You may give NULL to this argument to
662 profile - International Color Consortium color
663 profile data. May contain NULs.
664 proflen - length of profile data in bytes.
666 png_get_sBIT(png_ptr, info_ptr, &sig_bit);
667 sig_bit - the number of significant bits for
668 (PNG_INFO_sBIT) each of the gray,
669 red, green, and blue channels,
670 whichever are appropriate for the
671 given color type (png_color_16)
673 png_get_tRNS(png_ptr, info_ptr, &trans_alpha,
674 &num_trans, &trans_color);
675 trans_alpha - array of alpha (transparency)
676 entries for palette (PNG_INFO_tRNS)
677 trans_color - graylevel or color sample values of
678 the single transparent color for
679 non-paletted images (PNG_INFO_tRNS)
680 num_trans - number of transparent entries
683 png_get_hIST(png_ptr, info_ptr, &hist);
685 hist - histogram of palette (array of
688 png_get_tIME(png_ptr, info_ptr, &mod_time);
689 mod_time - time image was last modified
692 png_get_bKGD(png_ptr, info_ptr, &background);
693 background - background color (PNG_VALID_bKGD)
694 valid 16-bit red, green and blue
695 values, regardless of color_type
697 num_comments = png_get_text(png_ptr, info_ptr,
698 &text_ptr, &num_text);
699 num_comments - number of comments
700 text_ptr - array of png_text holding image
702 text_ptr[i].compression - type of compression used
703 on "text" PNG_TEXT_COMPRESSION_NONE
704 PNG_TEXT_COMPRESSION_zTXt
705 PNG_ITXT_COMPRESSION_NONE
706 PNG_ITXT_COMPRESSION_zTXt
707 text_ptr[i].key - keyword for comment. Must contain
709 text_ptr[i].text - text comments for current
710 keyword. Can be empty.
711 text_ptr[i].text_length - length of text string,
712 after decompression, 0 for iTXt
713 text_ptr[i].itxt_length - length of itxt string,
714 after decompression, 0 for tEXt/zTXt
715 text_ptr[i].lang - language of comment (empty
717 text_ptr[i].lang_key - keyword in UTF-8
718 (empty string for unknown).
719 Note that the itxt_length, lang, and lang_key
720 members of the text_ptr structure only exist
721 when the library is built with iTXt chunk support.
723 num_text - number of comments (same as
724 num_comments; you can put NULL here
725 to avoid the duplication)
726 Note while png_set_text() will accept text, language,
727 and translated keywords that can be NULL pointers, the
728 structure returned by png_get_text will always contain
729 regular zero-terminated C strings. They might be
730 empty strings but they will never be NULL pointers.
732 num_spalettes = png_get_sPLT(png_ptr, info_ptr,
734 palette_ptr - array of palette structures holding
735 contents of one or more sPLT chunks
737 num_spalettes - number of sPLT chunks read.
739 png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
741 offset_x - positive offset from the left edge
743 offset_y - positive offset from the top edge
745 unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
747 png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
749 res_x - pixels/unit physical resolution in
751 res_y - pixels/unit physical resolution in
753 unit_type - PNG_RESOLUTION_UNKNOWN,
756 png_get_sCAL(png_ptr, info_ptr, &unit, &width,
758 unit - physical scale units (an integer)
759 width - width of a pixel in physical scale units
760 height - height of a pixel in physical scale units
761 (width and height are doubles)
763 png_get_sCAL_s(png_ptr, info_ptr, &unit, &width,
765 unit - physical scale units (an integer)
766 width - width of a pixel in physical scale units
767 height - height of a pixel in physical scale units
768 (width and height are strings like "2.54")
770 num_unknown_chunks = png_get_unknown_chunks(png_ptr,
772 unknowns - array of png_unknown_chunk
773 structures holding unknown chunks
774 unknowns[i].name - name of unknown chunk
775 unknowns[i].data - data of unknown chunk
776 unknowns[i].size - size of unknown chunk's data
777 unknowns[i].location - position of chunk in file
779 The value of "i" corresponds to the order in which the
780 chunks were read from the PNG file or inserted with the
781 png_set_unknown_chunks() function.
783 The data from the pHYs chunk can be retrieved in several convenient
786 res_x = png_get_x_pixels_per_meter(png_ptr,
788 res_y = png_get_y_pixels_per_meter(png_ptr,
790 res_x_and_y = png_get_pixels_per_meter(png_ptr,
792 res_x = png_get_x_pixels_per_inch(png_ptr,
794 res_y = png_get_y_pixels_per_inch(png_ptr,
796 res_x_and_y = png_get_pixels_per_inch(png_ptr,
798 aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
801 (Each of these returns 0 [signifying "unknown"] if
802 the data is not present or if res_x is 0;
803 res_x_and_y is 0 if res_x != res_y)
805 The data from the oFFs chunk can be retrieved in several convenient
808 x_offset = png_get_x_offset_microns(png_ptr, info_ptr);
809 y_offset = png_get_y_offset_microns(png_ptr, info_ptr);
810 x_offset = png_get_x_offset_inches(png_ptr, info_ptr);
811 y_offset = png_get_y_offset_inches(png_ptr, info_ptr);
813 (Each of these returns 0 [signifying "unknown" if both
814 x and y are 0] if the data is not present or if the
815 chunk is present but the unit is the pixel)
817 For more information, see the png_info definition in png.h and the
818 PNG specification for chunk contents. Be careful with trusting
819 rowbytes, as some of the transformations could increase the space
820 needed to hold a row (expand, filler, gray_to_rgb, etc.).
821 See png_read_update_info(), below.
823 A quick word about text_ptr and num_text. PNG stores comments in
824 keyword/text pairs, one pair per chunk, with no limit on the number
825 of text chunks, and a 2^31 byte limit on their size. While there are
826 suggested keywords, there is no requirement to restrict the use to these
827 strings. It is strongly suggested that keywords and text be sensible
828 to humans (that's the point), so don't use abbreviations. Non-printing
829 symbols are not allowed. See the PNG specification for more details.
830 There is also no requirement to have text after the keyword.
832 Keywords should be limited to 79 Latin-1 characters without leading or
833 trailing spaces, but non-consecutive spaces are allowed within the
834 keyword. It is possible to have the same keyword any number of times.
835 The text_ptr is an array of png_text structures, each holding a
836 pointer to a language string, a pointer to a keyword and a pointer to
837 a text string. The text string, language code, and translated
838 keyword may be empty or NULL pointers. The keyword/text
839 pairs are put into the array in the order that they are received.
840 However, some or all of the text chunks may be after the image, so, to
841 make sure you have read all the text chunks, don't mess with these
842 until after you read the stuff after the image. This will be
843 mentioned again below in the discussion that goes with png_read_end().
845 Input transformations
847 After you've read the header information, you can set up the library
848 to handle any special transformations of the image data. The various
849 ways to transform the data will be described in the order that they
850 should occur. This is important, as some of these change the color
851 type and/or bit depth of the data, and some others only work on
852 certain color types and bit depths. Even though each transformation
853 checks to see if it has data that it can do something with, you should
854 make sure to only enable a transformation if it will be valid for the
855 data. For example, don't swap red and blue on grayscale data.
857 The colors used for the background and transparency values should be
858 supplied in the same format/depth as the current image data. They
859 are stored in the same format/depth as the image data in a bKGD or tRNS
860 chunk, so this is what libpng expects for this data. The colors are
861 transformed to keep in sync with the image data when an application
862 calls the png_read_update_info() routine (see below).
864 Data will be decoded into the supplied row buffers packed into bytes
865 unless the library has been told to transform it into another format.
866 For example, 4 bit/pixel paletted or grayscale data will be returned
867 2 pixels/byte with the leftmost pixel in the high-order bits of the
868 byte, unless png_set_packing() is called. 8-bit RGB data will be stored
869 in RGB RGB RGB format unless png_set_filler() or png_set_add_alpha()
870 is called to insert filler bytes, either before or after each RGB triplet.
871 16-bit RGB data will be returned RRGGBB RRGGBB, with the most significant
872 byte of the color value first, unless png_set_strip_16() is called to
873 transform it to regular RGB RGB triplets, or png_set_filler() or
874 png_set_add alpha() is called to insert filler bytes, either before or
875 after each RRGGBB triplet. Similarly, 8-bit or 16-bit grayscale data can
877 png_set_filler(), png_set_add_alpha(), or png_set_strip_16().
879 The following code transforms grayscale images of less than 8 to 8 bits,
880 changes paletted images to RGB, and adds a full alpha channel if there is
881 transparency information in a tRNS chunk. This is most useful on
882 grayscale images with bit depths of 2 or 4 or if there is a multiple-image
883 viewing application that wishes to treat all images in the same way.
885 if (color_type == PNG_COLOR_TYPE_PALETTE)
886 png_set_palette_to_rgb(png_ptr);
888 if (color_type == PNG_COLOR_TYPE_GRAY &&
889 bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png_ptr);
891 if (png_get_valid(png_ptr, info_ptr,
892 PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
894 These three functions are actually aliases for png_set_expand(), added
895 in libpng version 1.0.4, with the function names expanded to improve code
896 readability. In some future version they may actually do different
899 As of libpng version 1.2.9, png_set_expand_gray_1_2_4_to_8() was
900 added. It expands the sample depth without changing tRNS to alpha.
902 As of libpng version 1.4.1, not all possible expansions are supported.
904 In the following table, the 01 means grayscale with depth<8, 31 means
905 indexed with depth<8, other numerals represent the color type, "T" means
906 the tRNS chunk is present, A means an alpha channel is present, and O
907 means tRNS or alpha is present but all pixels in the image are opaque.
909 FROM 01 31 0 0T 0O 2 2T 2O 3 3T 3O 4A 4O 6A 6O
928 "-" means the transformation is not supported.
929 "X" means the transformation is obtained by png_set_expand().
930 "1" means the transformation is obtained by
931 png_set_expand_gray_1_2_4_to_8
932 "G" means the transformation is obtained by
933 png_set_gray_to_rgb().
934 "P" means the transformation is obtained by
935 png_set_expand_palette_to_rgb().
936 "T" means the transformation is obtained by
937 png_set_tRNS_to_alpha().
939 PNG can have files with 16 bits per channel. If you only can handle
940 8 bits per channel, this will strip the pixels down to 8 bit.
943 png_set_strip_16(png_ptr);
945 If, for some reason, you don't need the alpha channel on an image,
946 and you want to remove it rather than combining it with the background
947 (but the image author certainly had in mind that you *would* combine
948 it with the background, so that's what you should probably do):
950 if (color_type & PNG_COLOR_MASK_ALPHA)
951 png_set_strip_alpha(png_ptr);
953 In PNG files, the alpha channel in an image
954 is the level of opacity. If you need the alpha channel in an image to
955 be the level of transparency instead of opacity, you can invert the
956 alpha channel (or the tRNS chunk data) after it's read, so that 0 is
957 fully opaque and 255 (in 8-bit or paletted images) or 65535 (in 16-bit
958 images) is fully transparent, with
960 png_set_invert_alpha(png_ptr);
962 PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
963 they can, resulting in, for example, 8 pixels per byte for 1 bit
964 files. This code expands to 1 pixel per byte without changing the
965 values of the pixels:
968 png_set_packing(png_ptr);
970 PNG files have possible bit depths of 1, 2, 4, 8, and 16. All pixels
971 stored in a PNG image have been "scaled" or "shifted" up to the next
972 higher possible bit depth (e.g. from 5 bits/sample in the range [0,31]
973 to 8 bits/sample in the range [0, 255]). However, it is also possible
974 to convert the PNG pixel data back to the original bit depth of the
975 image. This call reduces the pixels back down to the original bit depth:
977 png_color_8p sig_bit;
979 if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
980 png_set_shift(png_ptr, sig_bit);
982 PNG files store 3-color pixels in red, green, blue order. This code
983 changes the storage of the pixels to blue, green, red:
985 if (color_type == PNG_COLOR_TYPE_RGB ||
986 color_type == PNG_COLOR_TYPE_RGB_ALPHA)
987 png_set_bgr(png_ptr);
989 PNG files store RGB pixels packed into 3 or 6 bytes. This code expands them
990 into 4 or 8 bytes for windowing systems that need them in this format:
992 if (color_type == PNG_COLOR_TYPE_RGB)
993 png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
995 where "filler" is the 8 or 16-bit number to fill with, and the location is
996 either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
997 you want the filler before the RGB or after. This transformation
998 does not affect images that already have full alpha channels. To add an
999 opaque alpha channel, use filler=0xff or 0xffff and PNG_FILLER_AFTER which
1000 will generate RGBA pixels.
1002 Note that png_set_filler() does not change the color type. If you want
1003 to do that, you can add a true alpha channel with
1005 if (color_type == PNG_COLOR_TYPE_RGB ||
1006 color_type == PNG_COLOR_TYPE_GRAY)
1007 png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER);
1009 where "filler" contains the alpha value to assign to each pixel.
1010 This function was added in libpng-1.2.7.
1012 If you are reading an image with an alpha channel, and you need the
1013 data as ARGB instead of the normal PNG format RGBA:
1015 if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1016 png_set_swap_alpha(png_ptr);
1018 For some uses, you may want a grayscale image to be represented as
1019 RGB. This code will do that conversion:
1021 if (color_type == PNG_COLOR_TYPE_GRAY ||
1022 color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
1023 png_set_gray_to_rgb(png_ptr);
1025 Conversely, you can convert an RGB or RGBA image to grayscale or grayscale
1028 if (color_type == PNG_COLOR_TYPE_RGB ||
1029 color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1030 png_set_rgb_to_gray_fixed(png_ptr, error_action,
1031 int red_weight, int green_weight);
1033 error_action = 1: silently do the conversion
1034 error_action = 2: issue a warning if the original
1035 image has any pixel where
1036 red != green or red != blue
1037 error_action = 3: issue an error and abort the
1038 conversion if the original
1039 image has any pixel where
1040 red != green or red != blue
1042 red_weight: weight of red component times 100000
1043 green_weight: weight of green component times 100000
1044 If either weight is negative, default
1045 weights (21268, 71514) are used.
1047 If you have set error_action = 1 or 2, you can
1048 later check whether the image really was gray, after processing
1049 the image rows, with the png_get_rgb_to_gray_status(png_ptr) function.
1050 It will return a png_byte that is zero if the image was gray or
1051 1 if there were any non-gray pixels. bKGD and sBIT data
1052 will be silently converted to grayscale, using the green channel
1053 data, regardless of the error_action setting.
1055 With red_weight+green_weight<=100000,
1056 the normalized graylevel is computed:
1058 int rw = red_weight * 65536;
1059 int gw = green_weight * 65536;
1060 int bw = 65536 - (rw + gw);
1061 gray = (rw*red + gw*green + bw*blue)/65536;
1063 The default values approximate those recommended in the Charles
1064 Poynton's Color FAQ, <http://www.inforamp.net/~poynton/>
1065 Copyright (c) 1998-01-04 Charles Poynton <poynton at inforamp.net>
1067 Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
1069 Libpng approximates this with
1071 Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
1073 which can be expressed with integers as
1075 Y = (6969 * R + 23434 * G + 2365 * B)/32768
1077 The calculation is done in a linear colorspace, if the image gamma
1080 If you have a grayscale and you are using png_set_expand_depth(),
1081 png_set_expand(), or png_set_gray_to_rgb to change to truecolor or to
1082 a higher bit-depth, you must either supply the background color as a gray
1083 value at the original file bit-depth (need_expand = 1) or else supply the
1084 background color as an RGB triplet at the final, expanded bit depth
1085 (need_expand = 0). Similarly, if you are reading a paletted image, you
1086 must either supply the background color as a palette index (need_expand = 1)
1087 or as an RGB triplet that may or may not be in the palette (need_expand = 0).
1089 png_color_16 my_background;
1090 png_color_16p image_background;
1092 if (png_get_bKGD(png_ptr, info_ptr, &image_background))
1093 png_set_background(png_ptr, image_background,
1094 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
1096 png_set_background(png_ptr, &my_background,
1097 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
1099 The png_set_background() function tells libpng to composite images
1100 with alpha or simple transparency against the supplied background
1101 color. If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
1102 you may use this color, or supply another color more suitable for
1103 the current display (e.g., the background color from a web page). You
1104 need to tell libpng whether the color is in the gamma space of the
1105 display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
1106 (PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
1107 that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
1108 know why anyone would use this, but it's here).
1110 To properly display PNG images on any kind of system, the application needs
1111 to know what the display gamma is. Ideally, the user will know this, and
1112 the application will allow them to set it. One method of allowing the user
1113 to set the display gamma separately for each system is to check for a
1114 SCREEN_GAMMA or DISPLAY_GAMMA environment variable, which will hopefully be
1117 Note that display_gamma is the overall gamma correction required to produce
1118 pleasing results, which depends on the lighting conditions in the surrounding
1119 environment. In a dim or brightly lit room, no compensation other than
1120 the physical gamma exponent of the monitor is needed, while in a dark room
1121 a slightly smaller exponent is better.
1123 double gamma, screen_gamma;
1125 if (/* We have a user-defined screen
1128 screen_gamma = user_defined_screen_gamma;
1130 /* One way that applications can share the same
1131 screen gamma value */
1132 else if ((gamma_str = getenv("SCREEN_GAMMA"))
1135 screen_gamma = (double)atof(gamma_str);
1137 /* If we don't have another value */
1140 screen_gamma = 2.2; /* A good guess for a
1141 PC monitor in a bright office or a dim room */
1142 screen_gamma = 2.0; /* A good guess for a
1143 PC monitor in a dark room */
1144 screen_gamma = 1.7 or 1.0; /* A good
1145 guess for Mac systems */
1148 The png_set_gamma() function handles gamma transformations of the data.
1149 Pass both the file gamma and the current screen_gamma. If the file does
1150 not have a gamma value, you can pass one anyway if you have an idea what
1151 it is (usually 0.45455 is a good guess for GIF images on PCs). Note
1152 that file gammas are inverted from screen gammas. See the discussions
1153 on gamma in the PNG specification for an excellent description of what
1154 gamma is, and why all applications should support it. It is strongly
1155 recommended that PNG viewers support gamma correction.
1157 if (png_get_gAMA(png_ptr, info_ptr, &gamma))
1158 png_set_gamma(png_ptr, screen_gamma, gamma);
1160 png_set_gamma(png_ptr, screen_gamma, 0.45455);
1162 PNG files describe monochrome as black being zero and white being one.
1163 The following code will reverse this (make black be one and white be
1166 if (bit_depth == 1 && color_type == PNG_COLOR_TYPE_GRAY)
1167 png_set_invert_mono(png_ptr);
1169 This function can also be used to invert grayscale and gray-alpha images:
1171 if (color_type == PNG_COLOR_TYPE_GRAY ||
1172 color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
1173 png_set_invert_mono(png_ptr);
1175 PNG files store 16 bit pixels in network byte order (big-endian,
1176 ie. most significant bits first). This code changes the storage to the
1177 other way (little-endian, i.e. least significant bits first, the
1178 way PCs store them):
1180 if (bit_depth == 16)
1181 png_set_swap(png_ptr);
1183 If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
1184 need to change the order the pixels are packed into bytes, you can use:
1187 png_set_packswap(png_ptr);
1189 Finally, you can write your own transformation function if none of
1190 the existing ones meets your needs. This is done by setting a callback
1193 png_set_read_user_transform_fn(png_ptr,
1196 You must supply the function
1198 void read_transform_fn(png_ptr ptr, row_info_ptr
1199 row_info, png_bytep data)
1201 See pngtest.c for a working example. Your function will be called
1202 after all of the other transformations have been processed.
1204 You can also set up a pointer to a user structure for use by your
1205 callback function, and you can inform libpng that your transform
1206 function will change the number of channels or bit depth with the
1209 png_set_user_transform_info(png_ptr, user_ptr,
1210 user_depth, user_channels);
1212 The user's application, not libpng, is responsible for allocating and
1213 freeing any memory required for the user structure.
1215 You can retrieve the pointer via the function
1216 png_get_user_transform_ptr(). For example:
1218 voidp read_user_transform_ptr =
1219 png_get_user_transform_ptr(png_ptr);
1221 The last thing to handle is interlacing; this is covered in detail below,
1222 but you must call the function here if you want libpng to handle expansion
1223 of the interlaced image.
1225 number_of_passes = png_set_interlace_handling(png_ptr);
1227 After setting the transformations, libpng can update your png_info
1228 structure to reflect any transformations you've requested with this
1229 call. This is most useful to update the info structure's rowbytes
1230 field so you can use it to allocate your image memory. This function
1231 will also update your palette with the correct screen_gamma and
1232 background if these have been given with the calls above.
1234 png_read_update_info(png_ptr, info_ptr);
1236 After you call png_read_update_info(), you can allocate any
1237 memory you need to hold the image. The row data is simply
1238 raw byte data for all forms of images. As the actual allocation
1239 varies among applications, no example will be given. If you
1240 are allocating one large chunk, you will need to build an
1241 array of pointers to each row, as it will be needed for some
1242 of the functions below.
1246 After you've allocated memory, you can read the image data.
1247 The simplest way to do this is in one function call. If you are
1248 allocating enough memory to hold the whole image, you can just
1249 call png_read_image() and libpng will read in all the image data
1250 and put it in the memory area supplied. You will need to pass in
1251 an array of pointers to each row.
1253 This function automatically handles interlacing, so you don't need
1254 to call png_set_interlace_handling() or call this function multiple
1255 times, or any of that other stuff necessary with png_read_rows().
1257 png_read_image(png_ptr, row_pointers);
1259 where row_pointers is:
1261 png_bytep row_pointers[height];
1263 You can point to void or char or whatever you use for pixels.
1265 If you don't want to read in the whole image at once, you can
1266 use png_read_rows() instead. If there is no interlacing (check
1267 interlace_type == PNG_INTERLACE_NONE), this is simple:
1269 png_read_rows(png_ptr, row_pointers, NULL,
1272 where row_pointers is the same as in the png_read_image() call.
1274 If you are doing this just one row at a time, you can do this with
1275 a single row_pointer instead of an array of row_pointers:
1277 png_bytep row_pointer = row;
1278 png_read_row(png_ptr, row_pointer, NULL);
1280 If the file is interlaced (interlace_type != 0 in the IHDR chunk), things
1281 get somewhat harder. The only current (PNG Specification version 1.2)
1282 interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7)
1283 is a somewhat complicated 2D interlace scheme, known as Adam7, that
1284 breaks down an image into seven smaller images of varying size, based
1287 libpng can fill out those images or it can give them to you "as is".
1288 If you want them filled out, there are two ways to do that. The one
1289 mentioned in the PNG specification is to expand each pixel to cover
1290 those pixels that have not been read yet (the "rectangle" method).
1291 This results in a blocky image for the first pass, which gradually
1292 smooths out as more pixels are read. The other method is the "sparkle"
1293 method, where pixels are drawn only in their final locations, with the
1294 rest of the image remaining whatever colors they were initialized to
1295 before the start of the read. The first method usually looks better,
1296 but tends to be slower, as there are more pixels to put in the rows.
1298 If you don't want libpng to handle the interlacing details, just call
1299 png_read_rows() seven times to read in all seven images. Each of the
1300 images is a valid image by itself, or they can all be combined on an
1301 8x8 grid to form a single image (although if you intend to combine them
1302 you would be far better off using the libpng interlace handling).
1304 The first pass will return an image 1/8 as wide as the entire image
1305 (every 8th column starting in column 0) and 1/8 as high as the original
1306 (every 8th row starting in row 0), the second will be 1/8 as wide
1307 (starting in column 4) and 1/8 as high (also starting in row 0). The
1308 third pass will be 1/4 as wide (every 4th pixel starting in column 0) and
1309 1/8 as high (every 8th row starting in row 4), and the fourth pass will
1310 be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
1311 and every 4th row starting in row 0). The fifth pass will return an
1312 image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
1313 while the sixth pass will be 1/2 as wide and 1/2 as high as the original
1314 (starting in column 1 and row 0). The seventh and final pass will be as
1315 wide as the original, and 1/2 as high, containing all of the odd
1316 numbered scanlines. Phew!
1318 If you want libpng to expand the images, call this before calling
1319 png_start_read_image() or png_read_update_info():
1321 if (interlace_type == PNG_INTERLACE_ADAM7)
1323 = png_set_interlace_handling(png_ptr);
1325 This will return the number of passes needed. Currently, this
1326 is seven, but may change if another interlace type is added.
1327 This function can be called even if the file is not interlaced,
1328 where it will return one pass.
1330 If you are not going to display the image after each pass, but are
1331 going to wait until the entire image is read in, use the sparkle
1332 effect. This effect is faster and the end result of either method
1333 is exactly the same. If you are planning on displaying the image
1334 after each pass, the "rectangle" effect is generally considered the
1337 If you only want the "sparkle" effect, just call png_read_rows() as
1338 normal, with the third parameter NULL. Make sure you make pass over
1339 the image number_of_passes times, and you don't change the data in the
1340 rows between calls. You can change the locations of the data, just
1341 not the data. Each pass only writes the pixels appropriate for that
1342 pass, and assumes the data from previous passes is still valid.
1344 png_read_rows(png_ptr, row_pointers, NULL,
1347 If you only want the first effect (the rectangles), do the same as
1348 before except pass the row buffer in the third parameter, and leave
1349 the second parameter NULL.
1351 png_read_rows(png_ptr, NULL, row_pointers,
1354 Finishing a sequential read
1356 After you are finished reading the image through the
1357 low-level interface, you can finish reading the file. If you are
1358 interested in comments or time, which may be stored either before or
1359 after the image data, you should pass the separate png_info struct if
1360 you want to keep the comments from before and after the image
1361 separate. If you are not interested, you can pass NULL.
1363 png_read_end(png_ptr, end_info);
1365 When you are done, you can free all memory allocated by libpng like this:
1367 png_destroy_read_struct(&png_ptr, &info_ptr,
1370 It is also possible to individually free the info_ptr members that
1371 point to libpng-allocated storage with the following function:
1373 png_free_data(png_ptr, info_ptr, mask, seq)
1374 mask - identifies data to be freed, a mask
1375 containing the bitwise OR of one or
1377 PNG_FREE_PLTE, PNG_FREE_TRNS,
1378 PNG_FREE_HIST, PNG_FREE_ICCP,
1379 PNG_FREE_PCAL, PNG_FREE_ROWS,
1380 PNG_FREE_SCAL, PNG_FREE_SPLT,
1381 PNG_FREE_TEXT, PNG_FREE_UNKN,
1382 or simply PNG_FREE_ALL
1383 seq - sequence number of item to be freed
1386 This function may be safely called when the relevant storage has
1387 already been freed, or has not yet been allocated, or was allocated
1388 by the user and not by libpng, and will in those cases do nothing.
1389 The "seq" parameter is ignored if only one item of the selected data
1390 type, such as PLTE, is allowed. If "seq" is not -1, and multiple items
1391 are allowed for the data type identified in the mask, such as text or
1392 sPLT, only the n'th item in the structure is freed, where n is "seq".
1394 The default behavior is only to free data that was allocated internally
1395 by libpng. This can be changed, so that libpng will not free the data,
1396 or so that it will free data that was allocated by the user with png_malloc()
1397 or png_zalloc() and passed in via a png_set_*() function, with
1399 png_data_freer(png_ptr, info_ptr, freer, mask)
1400 mask - which data elements are affected
1401 same choices as in png_free_data()
1403 PNG_DESTROY_WILL_FREE_DATA
1404 PNG_SET_WILL_FREE_DATA
1405 PNG_USER_WILL_FREE_DATA
1407 This function only affects data that has already been allocated.
1408 You can call this function after reading the PNG data but before calling
1409 any png_set_*() functions, to control whether the user or the png_set_*()
1410 function is responsible for freeing any existing data that might be present,
1411 and again after the png_set_*() functions to control whether the user
1412 or png_destroy_*() is supposed to free the data. When the user assumes
1413 responsibility for libpng-allocated data, the application must use
1414 png_free() to free it, and when the user transfers responsibility to libpng
1415 for data that the user has allocated, the user must have used png_malloc()
1416 or png_zalloc() to allocate it.
1418 If you allocated your row_pointers in a single block, as suggested above in
1419 the description of the high level read interface, you must not transfer
1420 responsibility for freeing it to the png_set_rows or png_read_destroy function,
1421 because they would also try to free the individual row_pointers[i].
1423 If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
1424 separately, do not transfer responsibility for freeing text_ptr to libpng,
1425 because when libpng fills a png_text structure it combines these members with
1426 the key member, and png_free_data() will free only text_ptr.key. Similarly,
1427 if you transfer responsibility for free'ing text_ptr from libpng to your
1428 application, your application must not separately free those members.
1430 The png_free_data() function will turn off the "valid" flag for anything
1431 it frees. If you need to turn the flag off for a chunk that was freed by
1432 your application instead of by libpng, you can use
1434 png_set_invalid(png_ptr, info_ptr, mask);
1435 mask - identifies the chunks to be made invalid,
1436 containing the bitwise OR of one or
1438 PNG_INFO_gAMA, PNG_INFO_sBIT,
1439 PNG_INFO_cHRM, PNG_INFO_PLTE,
1440 PNG_INFO_tRNS, PNG_INFO_bKGD,
1441 PNG_INFO_hIST, PNG_INFO_pHYs,
1442 PNG_INFO_oFFs, PNG_INFO_tIME,
1443 PNG_INFO_pCAL, PNG_INFO_sRGB,
1444 PNG_INFO_iCCP, PNG_INFO_sPLT,
1445 PNG_INFO_sCAL, PNG_INFO_IDAT
1447 For a more compact example of reading a PNG image, see the file example.c.
1449 Reading PNG files progressively
1451 The progressive reader is slightly different then the non-progressive
1452 reader. Instead of calling png_read_info(), png_read_rows(), and
1453 png_read_end(), you make one call to png_process_data(), which calls
1454 callbacks when it has the info, a row, or the end of the image. You
1455 set up these callbacks with png_set_progressive_read_fn(). You don't
1456 have to worry about the input/output functions of libpng, as you are
1457 giving the library the data directly in png_process_data(). I will
1458 assume that you have read the section on reading PNG files above,
1459 so I will only highlight the differences (although I will show
1462 png_structp png_ptr;
1465 /* An example code fragment of how you would
1466 initialize the progressive reader in your
1469 initialize_png_reader()
1471 png_ptr = png_create_read_struct
1472 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1473 user_error_fn, user_warning_fn);
1476 info_ptr = png_create_info_struct(png_ptr);
1479 png_destroy_read_struct(&png_ptr, (png_infopp)NULL,
1484 if (setjmp(png_jmpbuf(png_ptr)))
1486 png_destroy_read_struct(&png_ptr, &info_ptr,
1491 /* This one's new. You can provide functions
1492 to be called when the header info is valid,
1493 when each row is completed, and when the image
1494 is finished. If you aren't using all functions,
1495 you can specify NULL parameters. Even when all
1496 three functions are NULL, you need to call
1497 png_set_progressive_read_fn(). You can use
1498 any struct as the user_ptr (cast to a void pointer
1499 for the function call), and retrieve the pointer
1500 from inside the callbacks using the function
1502 png_get_progressive_ptr(png_ptr);
1504 which will return a void pointer, which you have
1505 to cast appropriately.
1507 png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
1508 info_callback, row_callback, end_callback);
1513 /* A code fragment that you call as you receive blocks
1516 process_data(png_bytep buffer, png_uint_32 length)
1518 if (setjmp(png_jmpbuf(png_ptr)))
1520 png_destroy_read_struct(&png_ptr, &info_ptr,
1525 /* This one's new also. Simply give it a chunk
1526 of data from the file stream (in order, of
1527 course). On machines with segmented memory
1528 models machines, don't give it any more than
1529 64K. The library seems to run fine with sizes
1530 of 4K. Although you can give it much less if
1531 necessary (I assume you can give it chunks of
1532 1 byte, I haven't tried less then 256 bytes
1533 yet). When this function returns, you may
1534 want to display any rows that were generated
1535 in the row callback if you don't already do
1538 png_process_data(png_ptr, info_ptr, buffer, length);
1542 /* This function is called (as set by
1543 png_set_progressive_read_fn() above) when enough data
1544 has been supplied so all of the header has been
1548 info_callback(png_structp png_ptr, png_infop info)
1550 /* Do any setup here, including setting any of
1551 the transformations mentioned in the Reading
1552 PNG files section. For now, you _must_ call
1553 either png_start_read_image() or
1554 png_read_update_info() after all the
1555 transformations are set (even if you don't set
1556 any). You may start getting rows before
1557 png_process_data() returns, so this is your
1558 last chance to prepare for that.
1562 /* This function is called when each row of image
1565 row_callback(png_structp png_ptr, png_bytep new_row,
1566 png_uint_32 row_num, int pass)
1568 /* If the image is interlaced, and you turned
1569 on the interlace handler, this function will
1570 be called for every row in every pass. Some
1571 of these rows will not be changed from the
1572 previous pass. When the row is not changed,
1573 the new_row variable will be NULL. The rows
1574 and passes are called in order, so you don't
1575 really need the row_num and pass, but I'm
1576 supplying them because it may make your life
1579 For the non-NULL rows of interlaced images,
1580 you must call png_progressive_combine_row()
1581 passing in the row and the old row. You can
1582 call this function for NULL rows (it will just
1583 return) and for non-interlaced images (it just
1584 does the memcpy for you) if it will make the
1585 code easier. Thus, you can just do this for
1589 png_progressive_combine_row(png_ptr, old_row,
1592 /* where old_row is what was displayed for
1593 previously for the row. Note that the first
1594 pass (pass == 0, really) will completely cover
1595 the old row, so the rows do not have to be
1596 initialized. After the first pass (and only
1597 for interlaced images), you will have to pass
1598 the current row, and the function will combine
1599 the old row and the new row.
1604 end_callback(png_structp png_ptr, png_infop info)
1606 /* This function is called after the whole image
1607 has been read, including any chunks after the
1608 image (up to and including the IEND). You
1609 will usually have the same info chunk as you
1610 had in the header, although some data may have
1611 been added to the comments and time fields.
1613 Most people won't do much here, perhaps setting
1614 a flag that marks the image as finished.
1622 Much of this is very similar to reading. However, everything of
1623 importance is repeated here, so you won't have to constantly look
1624 back up in the reading section to understand writing.
1628 You will want to do the I/O initialization before you get into libpng,
1629 so if it doesn't work, you don't have anything to undo. If you are not
1630 using the standard I/O functions, you will need to replace them with
1631 custom writing functions. See the discussion under Customizing libpng.
1633 FILE *fp = fopen(file_name, "wb");
1639 Next, png_struct and png_info need to be allocated and initialized.
1640 As these can be both relatively large, you may not want to store these
1641 on the stack, unless you have stack space to spare. Of course, you
1642 will want to check if they return NULL. If you are also reading,
1643 you won't want to name your read structure and your write structure
1644 both "png_ptr"; you can call them anything you like, such as
1645 "read_ptr" and "write_ptr". Look at pngtest.c, for example.
1647 png_structp png_ptr = png_create_write_struct
1648 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1649 user_error_fn, user_warning_fn);
1653 png_infop info_ptr = png_create_info_struct(png_ptr);
1656 png_destroy_write_struct(&png_ptr,
1661 If you want to use your own memory allocation routines,
1662 define PNG_USER_MEM_SUPPORTED and use
1663 png_create_write_struct_2() instead of png_create_write_struct():
1665 png_structp png_ptr = png_create_write_struct_2
1666 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1667 user_error_fn, user_warning_fn, (png_voidp)
1668 user_mem_ptr, user_malloc_fn, user_free_fn);
1670 After you have these structures, you will need to set up the
1671 error handling. When libpng encounters an error, it expects to
1672 longjmp() back to your routine. Therefore, you will need to call
1673 setjmp() and pass the png_jmpbuf(png_ptr). If you
1674 write the file from different routines, you will need to update
1675 the png_jmpbuf(png_ptr) every time you enter a new routine that will
1676 call a png_*() function. See your documentation of setjmp/longjmp
1677 for your compiler for more information on setjmp/longjmp. See
1678 the discussion on libpng error handling in the Customizing Libpng
1679 section below for more information on the libpng error handling.
1681 if (setjmp(png_jmpbuf(png_ptr)))
1683 png_destroy_write_struct(&png_ptr, &info_ptr);
1690 If you would rather avoid the complexity of setjmp/longjmp issues,
1691 you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case
1692 errors will result in a call to PNG_ABORT() which defaults to abort().
1694 Now you need to set up the output code. The default for libpng is to
1695 use the C function fwrite(). If you use this, you will need to pass a
1696 valid FILE * in the function png_init_io(). Be sure that the file is
1697 opened in binary mode. Again, if you wish to handle writing data in
1698 another way, see the discussion on libpng I/O handling in the Customizing
1699 Libpng section below.
1701 png_init_io(png_ptr, fp);
1703 If you are embedding your PNG into a datastream such as MNG, and don't
1704 want libpng to write the 8-byte signature, or if you have already
1705 written the signature in your application, use
1707 png_set_sig_bytes(png_ptr, 8);
1709 to inform libpng that it should not write a signature.
1713 At this point, you can set up a callback function that will be
1714 called after each row has been written, which you can use to control
1715 a progress meter or the like. It's demonstrated in pngtest.c.
1716 You must supply a function
1718 void write_row_callback(png_ptr, png_uint_32 row,
1721 /* put your code here */
1724 (You can give it another name that you like instead of "write_row_callback")
1726 To inform libpng about your function, use
1728 png_set_write_status_fn(png_ptr, write_row_callback);
1730 You now have the option of modifying how the compression library will
1731 run. The following functions are mainly for testing, but may be useful
1732 in some cases, like if you need to write PNG files extremely fast and
1733 are willing to give up some compression, or if you want to get the
1734 maximum possible compression at the expense of slower writing. If you
1735 have no special needs in this area, let the library do what it wants by
1736 not calling this function at all, as it has been tuned to deliver a good
1737 speed/compression ratio. The second parameter to png_set_filter() is
1738 the filter method, for which the only valid values are 0 (as of the
1739 July 1999 PNG specification, version 1.2) or 64 (if you are writing
1740 a PNG datastream that is to be embedded in a MNG datastream). The third
1741 parameter is a flag that indicates which filter type(s) are to be tested
1742 for each scanline. See the PNG specification for details on the specific
1746 /* turn on or off filtering, and/or choose
1747 specific filters. You can use either a single
1748 PNG_FILTER_VALUE_NAME or the bitwise OR of one
1749 or more PNG_FILTER_NAME masks. */
1750 png_set_filter(png_ptr, 0,
1751 PNG_FILTER_NONE | PNG_FILTER_VALUE_NONE |
1752 PNG_FILTER_SUB | PNG_FILTER_VALUE_SUB |
1753 PNG_FILTER_UP | PNG_FILTER_VALUE_UP |
1754 PNG_FILTER_AVG | PNG_FILTER_VALUE_AVG |
1755 PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH|
1759 wants to start and stop using particular filters during compression,
1760 it should start out with all of the filters (to ensure that the previous
1761 row of pixels will be stored in case it's needed later), and then add
1762 and remove them after the start of compression.
1764 If you are writing a PNG datastream that is to be embedded in a MNG
1765 datastream, the second parameter can be either 0 or 64.
1767 The png_set_compression_*() functions interface to the zlib compression
1768 library, and should mostly be ignored unless you really know what you are
1769 doing. The only generally useful call is png_set_compression_level()
1770 which changes how much time zlib spends on trying to compress the image
1771 data. See the Compression Library (zlib.h and algorithm.txt, distributed
1772 with zlib) for details on the compression levels.
1774 /* set the zlib compression level */
1775 png_set_compression_level(png_ptr,
1776 Z_BEST_COMPRESSION);
1778 /* set other zlib parameters */
1779 png_set_compression_mem_level(png_ptr, 8);
1780 png_set_compression_strategy(png_ptr,
1781 Z_DEFAULT_STRATEGY);
1782 png_set_compression_window_bits(png_ptr, 15);
1783 png_set_compression_method(png_ptr, 8);
1784 png_set_compression_buffer_size(png_ptr, 8192)
1786 extern PNG_EXPORT(void,png_set_zbuf_size)
1788 Setting the contents of info for output
1790 You now need to fill in the png_info structure with all the data you
1791 wish to write before the actual image. Note that the only thing you
1792 are allowed to write after the image is the text chunks and the time
1793 chunk (as of PNG Specification 1.2, anyway). See png_write_end() and
1794 the latest PNG specification for more information on that. If you
1795 wish to write them before the image, fill them in now, and flag that
1796 data as being valid. If you want to wait until after the data, don't
1797 fill them until png_write_end(). For all the fields in png_info and
1798 their data types, see png.h. For explanations of what the fields
1799 contain, see the PNG specification.
1801 Some of the more important parts of the png_info are:
1803 png_set_IHDR(png_ptr, info_ptr, width, height,
1804 bit_depth, color_type, interlace_type,
1805 compression_type, filter_method)
1806 width - holds the width of the image
1807 in pixels (up to 2^31).
1808 height - holds the height of the image
1809 in pixels (up to 2^31).
1810 bit_depth - holds the bit depth of one of the
1812 (valid values are 1, 2, 4, 8, 16
1813 and depend also on the
1814 color_type. See also significant
1816 color_type - describes which color/alpha
1817 channels are present.
1819 (bit depths 1, 2, 4, 8, 16)
1820 PNG_COLOR_TYPE_GRAY_ALPHA
1822 PNG_COLOR_TYPE_PALETTE
1823 (bit depths 1, 2, 4, 8)
1826 PNG_COLOR_TYPE_RGB_ALPHA
1829 PNG_COLOR_MASK_PALETTE
1830 PNG_COLOR_MASK_COLOR
1831 PNG_COLOR_MASK_ALPHA
1833 interlace_type - PNG_INTERLACE_NONE or
1835 compression_type - (must be
1836 PNG_COMPRESSION_TYPE_DEFAULT)
1837 filter_method - (must be PNG_FILTER_TYPE_DEFAULT
1838 or, if you are writing a PNG to
1839 be embedded in a MNG datastream,
1841 PNG_INTRAPIXEL_DIFFERENCING)
1843 If you call png_set_IHDR(), the call must appear before any of the
1844 other png_set_*() functions, because they might require access to some of
1845 the IHDR settings. The remaining png_set_*() functions can be called
1848 If you wish, you can reset the compression_type, interlace_type, or
1849 filter_method later by calling png_set_IHDR() again; if you do this, the
1850 width, height, bit_depth, and color_type must be the same in each call.
1852 png_set_PLTE(png_ptr, info_ptr, palette,
1854 palette - the palette for the file
1855 (array of png_color)
1856 num_palette - number of entries in the palette
1858 png_set_gAMA(png_ptr, info_ptr, gamma);
1859 gamma - the gamma the image was created
1862 png_set_sRGB(png_ptr, info_ptr, srgb_intent);
1863 srgb_intent - the rendering intent
1864 (PNG_INFO_sRGB) The presence of
1865 the sRGB chunk means that the pixel
1866 data is in the sRGB color space.
1867 This chunk also implies specific
1868 values of gAMA and cHRM. Rendering
1869 intent is the CSS-1 property that
1870 has been defined by the International
1872 (http://www.color.org).
1874 PNG_sRGB_INTENT_SATURATION,
1875 PNG_sRGB_INTENT_PERCEPTUAL,
1876 PNG_sRGB_INTENT_ABSOLUTE, or
1877 PNG_sRGB_INTENT_RELATIVE.
1880 png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
1882 srgb_intent - the rendering intent
1883 (PNG_INFO_sRGB) The presence of the
1884 sRGB chunk means that the pixel
1885 data is in the sRGB color space.
1886 This function also causes gAMA and
1887 cHRM chunks with the specific values
1888 that are consistent with sRGB to be
1891 png_set_iCCP(png_ptr, info_ptr, name, compression_type,
1893 name - The profile name.
1894 compression - The compression type; always
1895 PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
1896 You may give NULL to this argument to
1898 profile - International Color Consortium color
1899 profile data. May contain NULs.
1900 proflen - length of profile data in bytes.
1902 png_set_sBIT(png_ptr, info_ptr, sig_bit);
1903 sig_bit - the number of significant bits for
1904 (PNG_INFO_sBIT) each of the gray, red,
1905 green, and blue channels, whichever are
1906 appropriate for the given color type
1909 png_set_tRNS(png_ptr, info_ptr, trans_alpha,
1910 num_trans, trans_color);
1911 trans_alpha - array of alpha (transparency)
1912 entries for palette (PNG_INFO_tRNS)
1913 trans_color - graylevel or color sample values
1914 (in order red, green, blue) of the
1915 single transparent color for
1916 non-paletted images (PNG_INFO_tRNS)
1917 num_trans - number of transparent entries
1920 png_set_hIST(png_ptr, info_ptr, hist);
1922 hist - histogram of palette (array of
1925 png_set_tIME(png_ptr, info_ptr, mod_time);
1926 mod_time - time image was last modified
1929 png_set_bKGD(png_ptr, info_ptr, background);
1930 background - background color (PNG_VALID_bKGD)
1932 png_set_text(png_ptr, info_ptr, text_ptr, num_text);
1933 text_ptr - array of png_text holding image
1935 text_ptr[i].compression - type of compression used
1936 on "text" PNG_TEXT_COMPRESSION_NONE
1937 PNG_TEXT_COMPRESSION_zTXt
1938 PNG_ITXT_COMPRESSION_NONE
1939 PNG_ITXT_COMPRESSION_zTXt
1940 text_ptr[i].key - keyword for comment. Must contain
1942 text_ptr[i].text - text comments for current
1943 keyword. Can be NULL or empty.
1944 text_ptr[i].text_length - length of text string,
1945 after decompression, 0 for iTXt
1946 text_ptr[i].itxt_length - length of itxt string,
1947 after decompression, 0 for tEXt/zTXt
1948 text_ptr[i].lang - language of comment (NULL or
1950 text_ptr[i].translated_keyword - keyword in UTF-8 (NULL
1951 or empty for unknown).
1952 Note that the itxt_length, lang, and lang_key
1953 members of the text_ptr structure only exist
1954 when the library is built with iTXt chunk support.
1956 num_text - number of comments
1958 png_set_sPLT(png_ptr, info_ptr, &palette_ptr,
1960 palette_ptr - array of png_sPLT_struct structures
1961 to be added to the list of palettes
1962 in the info structure.
1963 num_spalettes - number of palette structures to be
1966 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
1968 offset_x - positive offset from the left
1970 offset_y - positive offset from the top
1972 unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
1974 png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
1976 res_x - pixels/unit physical resolution
1978 res_y - pixels/unit physical resolution
1980 unit_type - PNG_RESOLUTION_UNKNOWN,
1981 PNG_RESOLUTION_METER
1983 png_set_sCAL(png_ptr, info_ptr, unit, width, height)
1984 unit - physical scale units (an integer)
1985 width - width of a pixel in physical scale units
1986 height - height of a pixel in physical scale units
1987 (width and height are doubles)
1989 png_set_sCAL_s(png_ptr, info_ptr, unit, width, height)
1990 unit - physical scale units (an integer)
1991 width - width of a pixel in physical scale units
1992 height - height of a pixel in physical scale units
1993 (width and height are strings like "2.54")
1995 png_set_unknown_chunks(png_ptr, info_ptr, &unknowns,
1997 unknowns - array of png_unknown_chunk
1998 structures holding unknown chunks
1999 unknowns[i].name - name of unknown chunk
2000 unknowns[i].data - data of unknown chunk
2001 unknowns[i].size - size of unknown chunk's data
2002 unknowns[i].location - position to write chunk in file
2003 0: do not write chunk
2004 PNG_HAVE_IHDR: before PLTE
2005 PNG_HAVE_PLTE: before IDAT
2006 PNG_AFTER_IDAT: after IDAT
2008 The "location" member is set automatically according to
2009 what part of the output file has already been written.
2010 You can change its value after calling png_set_unknown_chunks()
2011 as demonstrated in pngtest.c. Within each of the "locations",
2012 the chunks are sequenced according to their position in the
2013 structure (that is, the value of "i", which is the order in which
2014 the chunk was either read from the input file or defined with
2015 png_set_unknown_chunks).
2017 A quick word about text and num_text. text is an array of png_text
2018 structures. num_text is the number of valid structures in the array.
2019 Each png_text structure holds a language code, a keyword, a text value,
2020 and a compression type.
2022 The compression types have the same valid numbers as the compression
2023 types of the image data. Currently, the only valid number is zero.
2024 However, you can store text either compressed or uncompressed, unlike
2025 images, which always have to be compressed. So if you don't want the
2026 text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
2027 Because tEXt and zTXt chunks don't have a language field, if you
2028 specify PNG_TEXT_COMPRESSION_NONE or PNG_TEXT_COMPRESSION_zTXt
2029 any language code or translated keyword will not be written out.
2031 Until text gets around 1000 bytes, it is not worth compressing it.
2032 After the text has been written out to the file, the compression type
2033 is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
2034 so that it isn't written out again at the end (in case you are calling
2035 png_write_end() with the same struct.
2037 The keywords that are given in the PNG Specification are:
2039 Title Short (one line) title or
2041 Author Name of image's creator
2042 Description Description of image (possibly long)
2043 Copyright Copyright notice
2044 Creation Time Time of original image creation
2045 (usually RFC 1123 format, see below)
2046 Software Software used to create the image
2047 Disclaimer Legal disclaimer
2048 Warning Warning of nature of content
2049 Source Device used to create the image
2050 Comment Miscellaneous comment; conversion
2051 from other image format
2053 The keyword-text pairs work like this. Keywords should be short
2054 simple descriptions of what the comment is about. Some typical
2055 keywords are found in the PNG specification, as is some recommendations
2056 on keywords. You can repeat keywords in a file. You can even write
2057 some text before the image and some after. For example, you may want
2058 to put a description of the image before the image, but leave the
2059 disclaimer until after, so viewers working over modem connections
2060 don't have to wait for the disclaimer to go over the modem before
2061 they start seeing the image. Finally, keywords should be full
2062 words, not abbreviations. Keywords and text are in the ISO 8859-1
2063 (Latin-1) character set (a superset of regular ASCII) and can not
2064 contain NUL characters, and should not contain control or other
2065 unprintable characters. To make the comments widely readable, stick
2066 with basic ASCII, and avoid machine specific character set extensions
2067 like the IBM-PC character set. The keyword must be present, but
2068 you can leave off the text string on non-compressed pairs.
2069 Compressed pairs must have a text string, as only the text string
2070 is compressed anyway, so the compression would be meaningless.
2072 PNG supports modification time via the png_time structure. Two
2073 conversion routines are provided, png_convert_from_time_t() for
2074 time_t and png_convert_from_struct_tm() for struct tm. The
2075 time_t routine uses gmtime(). You don't have to use either of
2076 these, but if you wish to fill in the png_time structure directly,
2077 you should provide the time in universal time (GMT) if possible
2078 instead of your local time. Note that the year number is the full
2079 year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and
2080 that months start with 1.
2082 If you want to store the time of the original image creation, you should
2083 use a plain tEXt chunk with the "Creation Time" keyword. This is
2084 necessary because the "creation time" of a PNG image is somewhat vague,
2085 depending on whether you mean the PNG file, the time the image was
2086 created in a non-PNG format, a still photo from which the image was
2087 scanned, or possibly the subject matter itself. In order to facilitate
2088 machine-readable dates, it is recommended that the "Creation Time"
2089 tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"),
2090 although this isn't a requirement. Unlike the tIME chunk, the
2091 "Creation Time" tEXt chunk is not expected to be automatically changed
2092 by the software. To facilitate the use of RFC 1123 dates, a function
2093 png_convert_to_rfc1123(png_timep) is provided to convert from PNG
2094 time to an RFC 1123 format string.
2096 Writing unknown chunks
2098 You can use the png_set_unknown_chunks function to queue up chunks
2099 for writing. You give it a chunk name, raw data, and a size; that's
2100 all there is to it. The chunks will be written by the next following
2101 png_write_info_before_PLTE, png_write_info, or png_write_end function.
2102 Any chunks previously read into the info structure's unknown-chunk
2103 list will also be written out in a sequence that satisfies the PNG
2104 specification's ordering rules.
2106 The high-level write interface
2108 At this point there are two ways to proceed; through the high-level
2109 write interface, or through a sequence of low-level write operations.
2110 You can use the high-level interface if your image data is present
2111 in the info structure. All defined output
2112 transformations are permitted, enabled by the following masks.
2114 PNG_TRANSFORM_IDENTITY No transformation
2115 PNG_TRANSFORM_PACKING Pack 1, 2 and 4-bit samples
2116 PNG_TRANSFORM_PACKSWAP Change order of packed
2118 PNG_TRANSFORM_INVERT_MONO Invert monochrome images
2119 PNG_TRANSFORM_SHIFT Normalize pixels to the
2121 PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
2123 PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
2125 PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
2127 PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
2128 PNG_TRANSFORM_STRIP_FILLER Strip out filler
2130 PNG_TRANSFORM_STRIP_FILLER_BEFORE Strip out leading
2132 PNG_TRANSFORM_STRIP_FILLER_AFTER Strip out trailing
2135 If you have valid image data in the info structure (you can use
2136 png_set_rows() to put image data in the info structure), simply do this:
2138 png_write_png(png_ptr, info_ptr, png_transforms, NULL)
2140 where png_transforms is an integer containing the bitwise OR of some set of
2141 transformation flags. This call is equivalent to png_write_info(),
2142 followed the set of transformations indicated by the transform mask,
2143 then png_write_image(), and finally png_write_end().
2145 (The final parameter of this call is not yet used. Someday it might point
2146 to transformation parameters required by some future output transform.)
2148 You must use png_transforms and not call any png_set_transform() functions
2149 when you use png_write_png().
2151 The low-level write interface
2153 If you are going the low-level route instead, you are now ready to
2154 write all the file information up to the actual image data. You do
2155 this with a call to png_write_info().
2157 png_write_info(png_ptr, info_ptr);
2159 Note that there is one transformation you may need to do before
2160 png_write_info(). In PNG files, the alpha channel in an image is the
2161 level of opacity. If your data is supplied as a level of transparency,
2162 you can invert the alpha channel before you write it, so that 0 is
2163 fully transparent and 255 (in 8-bit or paletted images) or 65535
2164 (in 16-bit images) is fully opaque, with
2166 png_set_invert_alpha(png_ptr);
2168 This must appear before png_write_info() instead of later with the
2169 other transformations because in the case of paletted images the tRNS
2170 chunk data has to be inverted before the tRNS chunk is written. If
2171 your image is not a paletted image, the tRNS data (which in such cases
2172 represents a single color to be rendered as transparent) won't need to
2173 be changed, and you can safely do this transformation after your
2174 png_write_info() call.
2176 If you need to write a private chunk that you want to appear before
2177 the PLTE chunk when PLTE is present, you can write the PNG info in
2178 two steps, and insert code to write your own chunk between them:
2180 png_write_info_before_PLTE(png_ptr, info_ptr);
2181 png_set_unknown_chunks(png_ptr, info_ptr, ...);
2182 png_write_info(png_ptr, info_ptr);
2184 After you've written the file information, you can set up the library
2185 to handle any special transformations of the image data. The various
2186 ways to transform the data will be described in the order that they
2187 should occur. This is important, as some of these change the color
2188 type and/or bit depth of the data, and some others only work on
2189 certain color types and bit depths. Even though each transformation
2190 checks to see if it has data that it can do something with, you should
2191 make sure to only enable a transformation if it will be valid for the
2192 data. For example, don't swap red and blue on grayscale data.
2194 PNG files store RGB pixels packed into 3 or 6 bytes. This code tells
2195 the library to strip input data that has 4 or 8 bytes per pixel down
2196 to 3 or 6 bytes (or strip 2 or 4-byte grayscale+filler data to 1 or 2
2199 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
2201 where the 0 is unused, and the location is either PNG_FILLER_BEFORE or
2202 PNG_FILLER_AFTER, depending upon whether the filler byte in the pixel
2203 is stored XRGB or RGBX.
2205 PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
2206 they can, resulting in, for example, 8 pixels per byte for 1 bit files.
2207 If the data is supplied at 1 pixel per byte, use this code, which will
2208 correctly pack the pixels into a single byte:
2210 png_set_packing(png_ptr);
2212 PNG files reduce possible bit depths to 1, 2, 4, 8, and 16. If your
2213 data is of another bit depth, you can write an sBIT chunk into the
2214 file so that decoders can recover the original data if desired.
2216 /* Set the true bit depth of the image data */
2217 if (color_type & PNG_COLOR_MASK_COLOR)
2219 sig_bit.red = true_bit_depth;
2220 sig_bit.green = true_bit_depth;
2221 sig_bit.blue = true_bit_depth;
2225 sig_bit.gray = true_bit_depth;
2227 if (color_type & PNG_COLOR_MASK_ALPHA)
2229 sig_bit.alpha = true_bit_depth;
2232 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
2234 If the data is stored in the row buffer in a bit depth other than
2235 one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG),
2236 this will scale the values to appear to be the correct bit depth as
2239 png_set_shift(png_ptr, &sig_bit);
2241 PNG files store 16 bit pixels in network byte order (big-endian,
2242 ie. most significant bits first). This code would be used if they are
2243 supplied the other way (little-endian, i.e. least significant bits
2244 first, the way PCs store them):
2247 png_set_swap(png_ptr);
2249 If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
2250 need to change the order the pixels are packed into bytes, you can use:
2253 png_set_packswap(png_ptr);
2255 PNG files store 3 color pixels in red, green, blue order. This code
2256 would be used if they are supplied as blue, green, red:
2258 png_set_bgr(png_ptr);
2260 PNG files describe monochrome as black being zero and white being
2261 one. This code would be used if the pixels are supplied with this reversed
2262 (black being one and white being zero):
2264 png_set_invert_mono(png_ptr);
2266 Finally, you can write your own transformation function if none of
2267 the existing ones meets your needs. This is done by setting a callback
2270 png_set_write_user_transform_fn(png_ptr,
2271 write_transform_fn);
2273 You must supply the function
2275 void write_transform_fn(png_ptr ptr, row_info_ptr
2276 row_info, png_bytep data)
2278 See pngtest.c for a working example. Your function will be called
2279 before any of the other transformations are processed.
2281 You can also set up a pointer to a user structure for use by your
2284 png_set_user_transform_info(png_ptr, user_ptr, 0, 0);
2286 The user_channels and user_depth parameters of this function are ignored
2287 when writing; you can set them to zero as shown.
2289 You can retrieve the pointer via the function png_get_user_transform_ptr().
2292 voidp write_user_transform_ptr =
2293 png_get_user_transform_ptr(png_ptr);
2295 It is possible to have libpng flush any pending output, either manually,
2296 or automatically after a certain number of lines have been written. To
2297 flush the output stream a single time call:
2299 png_write_flush(png_ptr);
2301 and to have libpng flush the output stream periodically after a certain
2302 number of scanlines have been written, call:
2304 png_set_flush(png_ptr, nrows);
2306 Note that the distance between rows is from the last time png_write_flush()
2307 was called, or the first row of the image if it has never been called.
2308 So if you write 50 lines, and then png_set_flush 25, it will flush the
2309 output on the next scanline, and every 25 lines thereafter, unless
2310 png_write_flush() is called before 25 more lines have been written.
2311 If nrows is too small (less than about 10 lines for a 640 pixel wide
2312 RGB image) the image compression may decrease noticeably (although this
2313 may be acceptable for real-time applications). Infrequent flushing will
2314 only degrade the compression performance by a few percent over images
2315 that do not use flushing.
2317 Writing the image data
2319 That's it for the transformations. Now you can write the image data.
2320 The simplest way to do this is in one function call. If you have the
2321 whole image in memory, you can just call png_write_image() and libpng
2322 will write the image. You will need to pass in an array of pointers to
2323 each row. This function automatically handles interlacing, so you don't
2324 need to call png_set_interlace_handling() or call this function multiple
2325 times, or any of that other stuff necessary with png_write_rows().
2327 png_write_image(png_ptr, row_pointers);
2329 where row_pointers is:
2331 png_byte *row_pointers[height];
2333 You can point to void or char or whatever you use for pixels.
2335 If you don't want to write the whole image at once, you can
2336 use png_write_rows() instead. If the file is not interlaced,
2339 png_write_rows(png_ptr, row_pointers,
2342 row_pointers is the same as in the png_write_image() call.
2344 If you are just writing one row at a time, you can do this with
2345 a single row_pointer instead of an array of row_pointers:
2347 png_bytep row_pointer = row;
2349 png_write_row(png_ptr, row_pointer);
2351 When the file is interlaced, things can get a good deal more complicated.
2352 The only currently (as of the PNG Specification version 1.2, dated July
2353 1999) defined interlacing scheme for PNG files is the "Adam7" interlace
2354 scheme, that breaks down an image into seven smaller images of varying
2355 size. libpng will build these images for you, or you can do them
2356 yourself. If you want to build them yourself, see the PNG specification
2357 for details of which pixels to write when.
2359 If you don't want libpng to handle the interlacing details, just
2360 use png_set_interlace_handling() and call png_write_rows() the
2361 correct number of times to write all seven sub-images.
2363 If you want libpng to build the sub-images, call this before you start
2367 png_set_interlace_handling(png_ptr);
2369 This will return the number of passes needed. Currently, this is seven,
2370 but may change if another interlace type is added.
2372 Then write the complete image number_of_passes times.
2374 png_write_rows(png_ptr, row_pointers,
2377 As some of these rows are not used, and thus return immediately, you may
2378 want to read about interlacing in the PNG specification, and only update
2379 the rows that are actually used.
2381 Finishing a sequential write
2383 After you are finished writing the image, you should finish writing
2384 the file. If you are interested in writing comments or time, you should
2385 pass an appropriately filled png_info pointer. If you are not interested,
2388 png_write_end(png_ptr, info_ptr);
2390 When you are done, you can free all memory used by libpng like this:
2392 png_destroy_write_struct(&png_ptr, &info_ptr);
2394 It is also possible to individually free the info_ptr members that
2395 point to libpng-allocated storage with the following function:
2397 png_free_data(png_ptr, info_ptr, mask, seq)
2398 mask - identifies data to be freed, a mask
2399 containing the bitwise OR of one or
2401 PNG_FREE_PLTE, PNG_FREE_TRNS,
2402 PNG_FREE_HIST, PNG_FREE_ICCP,
2403 PNG_FREE_PCAL, PNG_FREE_ROWS,
2404 PNG_FREE_SCAL, PNG_FREE_SPLT,
2405 PNG_FREE_TEXT, PNG_FREE_UNKN,
2406 or simply PNG_FREE_ALL
2407 seq - sequence number of item to be freed
2410 This function may be safely called when the relevant storage has
2411 already been freed, or has not yet been allocated, or was allocated
2412 by the user and not by libpng, and will in those cases do nothing.
2413 The "seq" parameter is ignored if only one item of the selected data
2414 type, such as PLTE, is allowed. If "seq" is not -1, and multiple items
2415 are allowed for the data type identified in the mask, such as text or
2416 sPLT, only the n'th item in the structure is freed, where n is "seq".
2418 If you allocated data such as a palette that you passed in to libpng
2419 with png_set_*, you must not free it until just before the call to
2420 png_destroy_write_struct().
2422 The default behavior is only to free data that was allocated internally
2423 by libpng. This can be changed, so that libpng will not free the data,
2424 or so that it will free data that was allocated by the user with png_malloc()
2425 or png_zalloc() and passed in via a png_set_*() function, with
2427 png_data_freer(png_ptr, info_ptr, freer, mask)
2428 mask - which data elements are affected
2429 same choices as in png_free_data()
2431 PNG_DESTROY_WILL_FREE_DATA
2432 PNG_SET_WILL_FREE_DATA
2433 PNG_USER_WILL_FREE_DATA
2435 For example, to transfer responsibility for some data from a read structure
2436 to a write structure, you could use
2438 png_data_freer(read_ptr, read_info_ptr,
2439 PNG_USER_WILL_FREE_DATA,
2440 PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
2441 png_data_freer(write_ptr, write_info_ptr,
2442 PNG_DESTROY_WILL_FREE_DATA,
2443 PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
2445 thereby briefly reassigning responsibility for freeing to the user but
2446 immediately afterwards reassigning it once more to the write_destroy
2447 function. Having done this, it would then be safe to destroy the read
2448 structure and continue to use the PLTE, tRNS, and hIST data in the write
2451 This function only affects data that has already been allocated.
2452 You can call this function before calling after the png_set_*() functions
2453 to control whether the user or png_destroy_*() is supposed to free the data.
2454 When the user assumes responsibility for libpng-allocated data, the
2455 application must use
2456 png_free() to free it, and when the user transfers responsibility to libpng
2457 for data that the user has allocated, the user must have used png_malloc()
2458 or png_zalloc() to allocate it.
2460 If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
2461 separately, do not transfer responsibility for freeing text_ptr to libpng,
2462 because when libpng fills a png_text structure it combines these members with
2463 the key member, and png_free_data() will free only text_ptr.key. Similarly,
2464 if you transfer responsibility for free'ing text_ptr from libpng to your
2465 application, your application must not separately free those members.
2466 For a more compact example of writing a PNG image, see the file example.c.
2468 V. Modifying/Customizing libpng:
2470 There are two issues here. The first is changing how libpng does
2471 standard things like memory allocation, input/output, and error handling.
2472 The second deals with more complicated things like adding new chunks,
2473 adding new transformations, and generally changing how libpng works.
2474 Both of those are compile-time issues; that is, they are generally
2475 determined at the time the code is written, and there is rarely a need
2476 to provide the user with a means of changing them.
2478 Memory allocation, input/output, and error handling
2480 All of the memory allocation, input/output, and error handling in libpng
2481 goes through callbacks that are user-settable. The default routines are
2482 in pngmem.c, pngrio.c, pngwio.c, and pngerror.c, respectively. To change
2483 these functions, call the appropriate png_set_*_fn() function.
2485 Memory allocation is done through the functions png_malloc(), png_calloc(),
2486 and png_free(). These currently just call the standard C functions.
2487 png_calloc() calls png_malloc() and then png_memset() to clear the newly
2488 allocated memory to zero. If your pointers can't access more then 64K
2489 at a time, you will want to set MAXSEG_64K in zlib.h. Since it is
2490 unlikely that the method of handling memory allocation on a platform
2491 will change between applications, these functions must be modified in
2492 the library at compile time. If you prefer to use a different method
2493 of allocating and freeing data, you can use png_create_read_struct_2() or
2494 png_create_write_struct_2() to register your own functions as described
2495 above. These functions also provide a void pointer that can be retrieved
2498 mem_ptr=png_get_mem_ptr(png_ptr);
2500 Your replacement memory functions must have prototypes as follows:
2502 png_voidp malloc_fn(png_structp png_ptr,
2503 png_alloc_size_t size);
2504 void free_fn(png_structp png_ptr, png_voidp ptr);
2506 Your malloc_fn() must return NULL in case of failure. The png_malloc()
2507 function will normally call png_error() if it receives a NULL from the
2508 system memory allocator or from your replacement malloc_fn().
2510 Your free_fn() will never be called with a NULL ptr, since libpng's
2511 png_free() checks for NULL before calling free_fn().
2513 Input/Output in libpng is done through png_read() and png_write(),
2514 which currently just call fread() and fwrite(). The FILE * is stored in
2515 png_struct and is initialized via png_init_io(). If you wish to change
2516 the method of I/O, the library supplies callbacks that you can set
2517 through the function png_set_read_fn() and png_set_write_fn() at run
2518 time, instead of calling the png_init_io() function. These functions
2519 also provide a void pointer that can be retrieved via the function
2520 png_get_io_ptr(). For example:
2522 png_set_read_fn(png_structp read_ptr,
2523 voidp read_io_ptr, png_rw_ptr read_data_fn)
2525 png_set_write_fn(png_structp write_ptr,
2526 voidp write_io_ptr, png_rw_ptr write_data_fn,
2527 png_flush_ptr output_flush_fn);
2529 voidp read_io_ptr = png_get_io_ptr(read_ptr);
2530 voidp write_io_ptr = png_get_io_ptr(write_ptr);
2532 The replacement I/O functions must have prototypes as follows:
2534 void user_read_data(png_structp png_ptr,
2535 png_bytep data, png_size_t length);
2536 void user_write_data(png_structp png_ptr,
2537 png_bytep data, png_size_t length);
2538 void user_flush_data(png_structp png_ptr);
2540 The user_read_data() function is responsible for detecting and
2541 handling end-of-data errors.
2543 Supplying NULL for the read, write, or flush functions sets them back
2544 to using the default C stream functions, which expect the io_ptr to
2545 point to a standard *FILE structure. It is probably a mistake
2546 to use NULL for one of write_data_fn and output_flush_fn but not both
2547 of them, unless you have built libpng with PNG_NO_WRITE_FLUSH defined.
2548 It is an error to read from a write stream, and vice versa.
2550 Error handling in libpng is done through png_error() and png_warning().
2551 Errors handled through png_error() are fatal, meaning that png_error()
2552 should never return to its caller. Currently, this is handled via
2553 setjmp() and longjmp() (unless you have compiled libpng with
2554 PNG_SETJMP_NOT_SUPPORTED, in which case it is handled via PNG_ABORT()),
2555 but you could change this to do things like exit() if you should wish.
2557 On non-fatal errors, png_warning() is called
2558 to print a warning message, and then control returns to the calling code.
2559 By default png_error() and png_warning() print a message on stderr via
2560 fprintf() unless the library is compiled with PNG_NO_CONSOLE_IO defined
2561 (because you don't want the messages) or PNG_NO_STDIO defined (because
2562 fprintf() isn't available). If you wish to change the behavior of the error
2563 functions, you will need to set up your own message callbacks. These
2564 functions are normally supplied at the time that the png_struct is created.
2565 It is also possible to redirect errors and warnings to your own replacement
2566 functions after png_create_*_struct() has been called by calling:
2568 png_set_error_fn(png_structp png_ptr,
2569 png_voidp error_ptr, png_error_ptr error_fn,
2570 png_error_ptr warning_fn);
2572 png_voidp error_ptr = png_get_error_ptr(png_ptr);
2574 If NULL is supplied for either error_fn or warning_fn, then the libpng
2575 default function will be used, calling fprintf() and/or longjmp() if a
2576 problem is encountered. The replacement error functions should have
2577 parameters as follows:
2579 void user_error_fn(png_structp png_ptr,
2580 png_const_charp error_msg);
2581 void user_warning_fn(png_structp png_ptr,
2582 png_const_charp warning_msg);
2584 The motivation behind using setjmp() and longjmp() is the C++ throw and
2585 catch exception handling methods. This makes the code much easier to write,
2586 as there is no need to check every return code of every function call.
2587 However, there are some uncertainties about the status of local variables
2588 after a longjmp, so the user may want to be careful about doing anything
2589 after setjmp returns non-zero besides returning itself. Consult your
2590 compiler documentation for more details. For an alternative approach, you
2591 may wish to use the "cexcept" facility (see http://cexcept.sourceforge.net).
2595 If you need to read or write custom chunks, you may need to get deeper
2596 into the libpng code. The library now has mechanisms for storing
2597 and writing chunks of unknown type; you can even declare callbacks
2598 for custom chunks. However, this may not be good enough if the
2599 library code itself needs to know about interactions between your
2600 chunk and existing `intrinsic' chunks.
2602 If you need to write a new intrinsic chunk, first read the PNG
2603 specification. Acquire a first level of understanding of how it works.
2604 Pay particular attention to the sections that describe chunk names,
2605 and look at how other chunks were designed, so you can do things
2606 similarly. Second, check out the sections of libpng that read and
2607 write chunks. Try to find a chunk that is similar to yours and use
2608 it as a template. More details can be found in the comments inside
2609 the code. It is best to handle unknown chunks in a generic method,
2610 via callback functions, instead of by modifying libpng functions.
2612 If you wish to write your own transformation for the data, look through
2613 the part of the code that does the transformations, and check out some of
2614 the simpler ones to get an idea of how they work. Try to find a similar
2615 transformation to the one you want to add and copy off of it. More details
2616 can be found in the comments inside the code itself.
2618 Configuring for 16 bit platforms
2620 You will want to look into zconf.h to tell zlib (and thus libpng) that
2621 it cannot allocate more then 64K at a time. Even if you can, the memory
2622 won't be accessible. So limit zlib and libpng to 64K by defining MAXSEG_64K.
2626 For DOS users who only have access to the lower 640K, you will
2627 have to limit zlib's memory usage via a png_set_compression_mem_level()
2628 call. See zlib.h or zconf.h in the zlib library for more information.
2630 Configuring for Medium Model
2632 Libpng's support for medium model has been tested on most of the popular
2633 compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
2634 defined, and FAR gets defined to far in pngconf.h, and you should be
2635 all set. Everything in the library (except for zlib's structure) is
2636 expecting far data. You must use the typedefs with the p or pp on
2637 the end for pointers (or at least look at them and be careful). Make
2638 note that the rows of data are defined as png_bytepp, which is an
2639 unsigned char far * far *.
2641 Configuring for gui/windowing platforms:
2643 You will need to write new error and warning functions that use the GUI
2644 interface, as described previously, and set them to be the error and
2645 warning functions at the time that png_create_*_struct() is called,
2646 in order to have them available during the structure initialization.
2647 They can be changed later via png_set_error_fn(). On some compilers,
2648 you may also have to change the memory allocators (png_malloc, etc.).
2650 Configuring for compiler xxx:
2652 All includes for libpng are in pngconf.h. If you need to add, change
2653 or delete an include, this is the place to do it.
2654 The includes that are not needed outside libpng are placed in pngpriv.h,
2655 which is only used by the routines inside libpng itself.
2656 The files in libpng proper only include pngpriv.h and png.h, which
2657 in turn includes pngconf.h.
2661 There are special functions to configure the compression. Perhaps the
2662 most useful one changes the compression level, which currently uses
2663 input compression values in the range 0 - 9. The library normally
2664 uses the default compression level (Z_DEFAULT_COMPRESSION = 6). Tests
2665 have shown that for a large majority of images, compression values in
2666 the range 3-6 compress nearly as well as higher levels, and do so much
2667 faster. For online applications it may be desirable to have maximum speed
2668 (Z_BEST_SPEED = 1). With versions of zlib after v0.99, you can also
2669 specify no compression (Z_NO_COMPRESSION = 0), but this would create
2670 files larger than just storing the raw bitmap. You can specify the
2671 compression level by calling:
2673 png_set_compression_level(png_ptr, level);
2675 Another useful one is to reduce the memory level used by the library.
2676 The memory level defaults to 8, but it can be lowered if you are
2677 short on memory (running DOS, for example, where you only have 640K).
2678 Note that the memory level does have an effect on compression; among
2679 other things, lower levels will result in sections of incompressible
2680 data being emitted in smaller stored blocks, with a correspondingly
2681 larger relative overhead of up to 15% in the worst case.
2683 png_set_compression_mem_level(png_ptr, level);
2685 The other functions are for configuring zlib. They are not recommended
2686 for normal use and may result in writing an invalid PNG file. See
2687 zlib.h for more information on what these mean.
2689 png_set_compression_strategy(png_ptr,
2691 png_set_compression_window_bits(png_ptr,
2693 png_set_compression_method(png_ptr, method);
2694 png_set_compression_buffer_size(png_ptr, size);
2696 Controlling row filtering
2698 If you want to control whether libpng uses filtering or not, which
2699 filters are used, and how it goes about picking row filters, you
2700 can call one of these functions. The selection and configuration
2701 of row filters can have a significant impact on the size and
2702 encoding speed and a somewhat lesser impact on the decoding speed
2703 of an image. Filtering is enabled by default for RGB and grayscale
2704 images (with and without alpha), but not for paletted images nor
2705 for any images with bit depths less than 8 bits/pixel.
2707 The 'method' parameter sets the main filtering method, which is
2708 currently only '0' in the PNG 1.2 specification. The 'filters'
2709 parameter sets which filter(s), if any, should be used for each
2710 scanline. Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
2711 to turn filtering on and off, respectively.
2713 Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
2714 PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
2715 ORed together with '|' to specify one or more filters to use.
2716 These filters are described in more detail in the PNG specification.
2717 If you intend to change the filter type during the course of writing
2718 the image, you should start with flags set for all of the filters
2719 you intend to use so that libpng can initialize its internal
2720 structures appropriately for all of the filter types. (Note that this
2721 means the first row must always be adaptively filtered, because libpng
2722 currently does not allocate the filter buffers until png_write_row()
2723 is called for the first time.)
2725 filters = PNG_FILTER_NONE | PNG_FILTER_SUB
2726 PNG_FILTER_UP | PNG_FILTER_AVG |
2727 PNG_FILTER_PAETH | PNG_ALL_FILTERS;
2729 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
2731 The second parameter can also be
2732 PNG_INTRAPIXEL_DIFFERENCING if you are
2733 writing a PNG to be embedded in a MNG
2734 datastream. This parameter must be the
2735 same as the value of filter_method used
2738 It is also possible to influence how libpng chooses from among the
2739 available filters. This is done in one or both of two ways - by
2740 telling it how important it is to keep the same filter for successive
2741 rows, and by telling it the relative computational costs of the filters.
2743 double weights[3] = {1.5, 1.3, 1.1},
2744 costs[PNG_FILTER_VALUE_LAST] =
2745 {1.0, 1.3, 1.3, 1.5, 1.7};
2747 png_set_filter_heuristics(png_ptr,
2748 PNG_FILTER_HEURISTIC_WEIGHTED, 3,
2751 The weights are multiplying factors that indicate to libpng that the
2752 row filter should be the same for successive rows unless another row filter
2753 is that many times better than the previous filter. In the above example,
2754 if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
2755 "sum of absolute differences" 1.5 x 1.3 times higher than other filters
2756 and still be chosen, while the NONE filter could have a sum 1.1 times
2757 higher than other filters and still be chosen. Unspecified weights are
2758 taken to be 1.0, and the specified weights should probably be declining
2759 like those above in order to emphasize recent filters over older filters.
2761 The filter costs specify for each filter type a relative decoding cost
2762 to be considered when selecting row filters. This means that filters
2763 with higher costs are less likely to be chosen over filters with lower
2764 costs, unless their "sum of absolute differences" is that much smaller.
2765 The costs do not necessarily reflect the exact computational speeds of
2766 the various filters, since this would unduly influence the final image
2769 Note that the numbers above were invented purely for this example and
2770 are given only to help explain the function usage. Little testing has
2771 been done to find optimum values for either the costs or the weights.
2773 Removing unwanted object code
2775 There are a bunch of #define's in pngconf.h that control what parts of
2776 libpng are compiled. All the defines end in _SUPPORTED. If you are
2777 never going to use a capability, you can change the #define to #undef
2778 before recompiling libpng and save yourself code and data space, or
2779 you can turn off individual capabilities with defines that begin with
2782 You can also turn all of the transforms and ancillary chunk capabilities
2783 off en masse with compiler directives that define
2784 PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS,
2786 along with directives to turn on any of the capabilities that you do
2787 want. The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable the extra
2788 transformations but still leave the library fully capable of reading
2789 and writing PNG files with all known public chunks. Use of the
2790 PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive produces a library
2791 that is incapable of reading or writing ancillary chunks. If you are
2792 not using the progressive reading capability, you can turn that off
2793 with PNG_NO_PROGRESSIVE_READ (don't confuse this with the INTERLACING
2794 capability, which you'll still have).
2796 All the reading and writing specific code are in separate files, so the
2797 linker should only grab the files it needs. However, if you want to
2798 make sure, or if you are building a stand alone library, all the
2799 reading files start with pngr and all the writing files start with
2800 pngw. The files that don't match either (like png.c, pngtrans.c, etc.)
2801 are used for both reading and writing, and always need to be included.
2802 The progressive reader is in pngpread.c
2804 If you are creating or distributing a dynamically linked library (a .so
2805 or DLL file), you should not remove or disable any parts of the library,
2806 as this will cause applications linked with different versions of the
2807 library to fail if they call functions not available in your library.
2808 The size of the library itself should not be an issue, because only
2809 those sections that are actually used will be loaded into memory.
2811 Requesting debug printout
2813 The macro definition PNG_DEBUG can be used to request debugging
2814 printout. Set it to an integer value in the range 0 to 3. Higher
2815 numbers result in increasing amounts of debugging information. The
2816 information is printed to the "stderr" file, unless another file
2817 name is specified in the PNG_DEBUG_FILE macro definition.
2819 When PNG_DEBUG > 0, the following functions (macros) become available:
2821 png_debug(level, message)
2822 png_debug1(level, message, p1)
2823 png_debug2(level, message, p1, p2)
2825 in which "level" is compared to PNG_DEBUG to decide whether to print
2826 the message, "message" is the formatted string to be printed,
2827 and p1 and p2 are parameters that are to be embedded in the string
2828 according to printf-style formatting directives. For example,
2830 png_debug1(2, "foo=%d\n", foo);
2835 fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
2837 When PNG_DEBUG is defined but is zero, the macros aren't defined, but you
2838 can still use PNG_DEBUG to control your own debugging:
2844 When PNG_DEBUG = 1, the macros are defined, but only png_debug statements
2845 having level = 0 will be printed. There aren't any such statements in
2846 this version of libpng, but if you insert some they will be printed.
2850 The MNG specification (available at http://www.libpng.org/pub/mng) allows
2851 certain extensions to PNG for PNG images that are embedded in MNG datastreams.
2852 Libpng can support some of these extensions. To enable them, use the
2853 png_permit_mng_features() function:
2855 feature_set = png_permit_mng_features(png_ptr, mask)
2856 mask is a png_uint_32 containing the bitwise OR of the
2857 features you want to enable. These include
2858 PNG_FLAG_MNG_EMPTY_PLTE
2859 PNG_FLAG_MNG_FILTER_64
2860 PNG_ALL_MNG_FEATURES
2861 feature_set is a png_uint_32 that is the bitwise AND of
2862 your mask with the set of MNG features that is
2863 supported by the version of libpng that you are using.
2865 It is an error to use this function when reading or writing a standalone
2866 PNG file with the PNG 8-byte signature. The PNG datastream must be wrapped
2867 in a MNG datastream. As a minimum, it must have the MNG 8-byte signature
2868 and the MHDR and MEND chunks. Libpng does not provide support for these
2869 or any other MNG chunks; your application must provide its own support for
2870 them. You may wish to consider using libmng (available at
2871 http://www.libmng.com) instead.
2873 VII. Changes to Libpng from version 0.88
2875 It should be noted that versions of libpng later than 0.96 are not
2876 distributed by the original libpng author, Guy Schalnat, nor by
2877 Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
2878 distributed versions 0.89 through 0.96, but rather by another member
2879 of the original PNG Group, Glenn Randers-Pehrson. Guy and Andreas are
2880 still alive and well, but they have moved on to other things.
2882 The old libpng functions png_read_init(), png_write_init(),
2883 png_info_init(), png_read_destroy(), and png_write_destroy() have been
2884 moved to PNG_INTERNAL in version 0.95 to discourage their use. These
2885 functions will be removed from libpng version 2.0.0.
2887 The preferred method of creating and initializing the libpng structures is
2888 via the png_create_read_struct(), png_create_write_struct(), and
2889 png_create_info_struct() because they isolate the size of the structures
2890 from the application, allow version error checking, and also allow the
2891 use of custom error handling routines during the initialization, which
2892 the old functions do not. The functions png_read_destroy() and
2893 png_write_destroy() do not actually free the memory that libpng
2894 allocated for these structs, but just reset the data structures, so they
2895 can be used instead of png_destroy_read_struct() and
2896 png_destroy_write_struct() if you feel there is too much system overhead
2897 allocating and freeing the png_struct for each image read.
2899 Setting the error callbacks via png_set_message_fn() before
2900 png_read_init() as was suggested in libpng-0.88 is no longer supported
2901 because this caused applications that do not use custom error functions
2902 to fail if the png_ptr was not initialized to zero. It is still possible
2903 to set the error callbacks AFTER png_read_init(), or to change them with
2904 png_set_error_fn(), which is essentially the same function, but with a new
2905 name to force compilation errors with applications that try to use the old
2908 Starting with version 1.0.7, you can find out which version of the library
2909 you are using at run-time:
2911 png_uint_32 libpng_vn = png_access_version_number();
2913 The number libpng_vn is constructed from the major version, minor
2914 version with leading zero, and release number with leading zero,
2915 (e.g., libpng_vn for version 1.0.7 is 10007).
2917 You can also check which version of png.h you used when compiling your
2920 png_uint_32 application_vn = PNG_LIBPNG_VER;
2922 VIII. Changes to Libpng from version 1.0.x to 1.2.x
2924 Support for user memory management was enabled by default. To
2925 accomplish this, the functions png_create_read_struct_2(),
2926 png_create_write_struct_2(), png_set_mem_fn(), png_get_mem_ptr(),
2927 png_malloc_default(), and png_free_default() were added.
2929 Support for the iTXt chunk has been enabled by default as of
2932 Support for certain MNG features was enabled.
2934 Support for numbered error messages was added. However, we never got
2935 around to actually numbering the error messages. The function
2936 png_set_strip_error_numbers() was added (Note: the prototype for this
2937 function was inadvertently removed from png.h in PNG_NO_ASSEMBLER_CODE
2938 builds of libpng-1.2.15. It was restored in libpng-1.2.36).
2940 The png_malloc_warn() function was added at libpng-1.2.3. This issues
2941 a png_warning and returns NULL instead of aborting when it fails to
2942 acquire the requested memory allocation.
2944 Support for setting user limits on image width and height was enabled
2945 by default. The functions png_set_user_limits(), png_get_user_width_max(),
2946 and png_get_user_height_max() were added at libpng-1.2.6.
2948 The png_set_add_alpha() function was added at libpng-1.2.7.
2950 The function png_set_expand_gray_1_2_4_to_8() was added at libpng-1.2.9.
2951 Unlike png_set_gray_1_2_4_to_8(), the new function does not expand the
2952 tRNS chunk to alpha. The png_set_gray_1_2_4_to_8() function is
2955 A number of macro definitions in support of runtime selection of
2956 assembler code features (especially Intel MMX code support) were
2957 added at libpng-1.2.0:
2959 PNG_ASM_FLAG_MMX_SUPPORT_COMPILED
2960 PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU
2961 PNG_ASM_FLAG_MMX_READ_COMBINE_ROW
2962 PNG_ASM_FLAG_MMX_READ_INTERLACE
2963 PNG_ASM_FLAG_MMX_READ_FILTER_SUB
2964 PNG_ASM_FLAG_MMX_READ_FILTER_UP
2965 PNG_ASM_FLAG_MMX_READ_FILTER_AVG
2966 PNG_ASM_FLAG_MMX_READ_FILTER_PAETH
2967 PNG_ASM_FLAGS_INITIALIZED
2973 We added the following functions in support of runtime
2974 selection of assembler code features:
2976 png_get_mmx_flagmask()
2977 png_set_mmx_thresholds()
2979 png_get_mmx_bitdepth_threshold()
2980 png_get_mmx_rowbytes_threshold()
2983 We replaced all of these functions with simple stubs in libpng-1.2.20,
2984 when the Intel assembler code was removed due to a licensing issue.
2986 These macros are deprecated:
2988 PNG_READ_TRANSFORMS_NOT_SUPPORTED
2989 PNG_PROGRESSIVE_READ_NOT_SUPPORTED
2990 PNG_NO_SEQUENTIAL_READ_SUPPORTED
2991 PNG_WRITE_TRANSFORMS_NOT_SUPPORTED
2992 PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED
2993 PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED
2995 They have been replaced, respectively, by:
2997 PNG_NO_READ_TRANSFORMS
2998 PNG_NO_PROGRESSIVE_READ
2999 PNG_NO_SEQUENTIAL_READ
3000 PNG_NO_WRITE_TRANSFORMS
3001 PNG_NO_READ_ANCILLARY_CHUNKS
3002 PNG_NO_WRITE_ANCILLARY_CHUNKS
3004 PNG_MAX_UINT was replaced with PNG_UINT_31_MAX. It has been
3005 deprecated since libpng-1.0.16 and libpng-1.2.6.
3008 png_check_sig(sig, num)
3010 !png_sig_cmp(sig, 0, num)
3011 It has been deprecated since libpng-0.90.
3014 png_set_gray_1_2_4_to_8()
3015 which also expands tRNS to alpha was replaced with
3016 png_set_expand_gray_1_2_4_to_8()
3017 which does not. It has been deprecated since libpng-1.0.18 and 1.2.9.
3019 IX. Changes to Libpng from version 1.0.x/1.2.x to 1.4.x
3021 Private libpng prototypes and macro definitions were moved from
3022 png.h and pngconf.h into a new pngpriv.h header file.
3024 Functions png_set_benign_errors(), png_benign_error(), and
3025 png_chunk_benign_error() were added.
3027 Support for setting the maximum amount of memory that the application
3028 will allocate for reading chunks was added, as a security measure.
3029 The functions png_set_chunk_cache_max() and png_get_chunk_cache_max()
3030 were added to the library.
3032 We implemented support for I/O states by adding png_ptr member io_state
3033 and functions png_get_io_chunk_name() and png_get_io_state() in pngget.c
3035 We added PNG_TRANSFORM_GRAY_TO_RGB to the available high-level
3038 Checking for and reporting of errors in the IHDR chunk is more thorough.
3040 Support for global arrays was removed, to improve thread safety.
3042 Some obsolete/deprecated macros and functions have been removed.
3044 Typecasted NULL definitions such as
3045 #define png_voidp_NULL (png_voidp)NULL
3046 were eliminated. If you used these in your application, just use
3049 The png_struct and info_struct members "trans" and "trans_values" were
3050 changed to "trans_alpha" and "trans_color", respectively.
3052 The obsolete, unused pnggccrd.c and pngvcrd.c files and related makefiles
3055 The PNG_1_0_X and PNG_1_2_X macros were eliminated.
3057 The PNG_LEGACY_SUPPORTED macro was eliminated.
3059 Many WIN32_WCE #ifdefs were removed.
3061 The functions png_read_init(info_ptr), png_write_init(info_ptr),
3062 png_info_init(info_ptr), png_read_destroy(), and png_write_destroy()
3063 have been removed. They have been deprecated since libpng-0.95.
3065 The png_permit_empty_plte() was removed. It has been deprecated
3066 since libpng-1.0.9. Use png_permit_mng_features() instead.
3068 We removed the obsolete stub functions png_get_mmx_flagmask(),
3069 png_set_mmx_thresholds(), png_get_asm_flags(),
3070 png_get_mmx_bitdepth_threshold(), png_get_mmx_rowbytes_threshold(),
3071 png_set_asm_flags(), and png_mmx_supported()
3073 We removed the obsolete png_check_sig(), png_memcpy_check(), and
3074 png_memset_check() functions. Instead use !png_sig_cmp(), png_memcpy(),
3075 and png_memset(), respectively.
3077 The function png_set_gray_1_2_4_to_8() was removed. It has been
3078 deprecated since libpng-1.0.18 and 1.2.9, when it was replaced with
3079 png_set_expand_gray_1_2_4_to_8() because the former function also
3080 expanded palette images.
3082 We changed the prototype for png_malloc() from
3083 png_malloc(png_structp png_ptr, png_uint_32 size)
3085 png_malloc(png_structp png_ptr, png_alloc_size_t size)
3087 This also applies to the prototype for the user replacement malloc_fn().
3089 The png_calloc() function was added and is used in place of
3090 of "png_malloc(); png_memset();" except in the case in png_read_png()
3091 where the array consists of pointers; in this case a "for" loop is used
3092 after the png_malloc() to set the pointers to NULL, to give robust.
3093 behavior in case the application runs out of memory part-way through
3096 We changed the prototypes of png_get_compression_buffer_size() and
3097 png_set_compression_buffer_size() to work with png_size_t instead of
3100 Support for numbered error messages was removed by default, since we
3101 never got around to actually numbering the error messages. The function
3102 png_set_strip_error_numbers() was removed from the library by default.
3104 The png_zalloc() and png_zfree() functions are no longer exported.
3105 The png_zalloc() function no longer zeroes out the memory that it
3108 We removed the trailing '.' from the warning and error messages.
3112 The png_get_io_ptr() function has been present since libpng-0.88, has never
3113 changed, and is unaffected by conditional compilation macros. It is the
3114 best choice for use in configure scripts for detecting the presence of any
3115 libpng version since 0.88. In an autoconf "configure.in" you could use
3117 AC_CHECK_LIB(png, png_get_io_ptr, ...
3119 XI. Source code repository
3121 Since about February 2009, version 1.2.34, libpng has been under "git" source
3122 control. The git repository was built from old libpng-x.y.z.tar.gz files
3123 going back to version 0.70. You can access the git repository (read only)
3126 git://libpng.git.sourceforge.net/gitroot/libpng
3128 or you can browse it via "gitweb" at
3130 http://libpng.git.sourceforge.net/git/gitweb.cgi?p=libpng
3132 Patches can be sent to glennrp at users.sourceforge.net or to
3133 png-mng-implement at lists.sourceforge.net or you can upload them to
3134 the libpng bug tracker at
3136 http://libpng.sourceforge.net
3140 Our coding style is similar to the "Allman" style, with curly
3141 braces on separate lines:
3148 else if (another condition)
3153 The braces can be omitted from simple one-line actions:
3158 We use 3-space indentation, except for continued statements which
3159 are usually indented the same as the first line of the statement
3160 plus four more spaces.
3162 For macro definitions we use 2-space indentation, always leaving the "#"
3163 in the first column.
3165 #ifndef PNG_NO_FEATURE
3166 # ifndef PNG_FEATURE_SUPPORTED
3167 # define PNG_FEATURE_SUPPORTED
3171 Comments appear with the leading "/*" at the same indentation as
3172 the statement that follows the comment:
3174 /* Single-line comment */
3182 Very short comments can be placed at the end of the statement
3183 to which they pertain:
3185 statement; /* comment */
3187 We don't use C++ style ("//") comments. We have, however,
3188 used them in the past in some now-abandoned MMX assembler
3191 Functions and their curly braces are not indented, and
3192 exported functions are marked with PNGAPI:
3194 /* This is a public function that is visible to
3195 * application programers. It does thus-and-so.
3198 png_exported_function(png_ptr, png_info, foo)
3203 The prototypes for all exported functions appear in png.h,
3204 above the comment that says
3206 /* Maintainer: Put new public prototypes here ... */
3208 We mark all non-exported functions with "/* PRIVATE */"":
3211 png_non_exported_function(png_ptr, png_info, foo)
3216 The prototypes for non-exported functions (except for those in
3219 above the comment that says
3221 /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
3223 The names of all exported functions and variables begin
3224 with "png_", and all publicly visible C preprocessor
3225 macros begin with "PNG_".
3227 We put a space after each comma and after each semicolon
3228 in "for" statments, and we put spaces before and after each
3229 C binary operator and after "for" or "while". We don't
3230 put a space between a typecast and the expression being
3231 cast, nor do we put one between a function name and the
3232 left parenthesis that follows it:
3234 for (i = 2; i > 0; --i)
3235 y[i] = a(x) + (int)b;
3237 We prefer #ifdef and #ifndef to #if defined() and if !defined()
3238 when there is only one macro being tested.
3240 We do not use the TAB character for indentation in the C sources.
3242 Lines do not exceed 80 characters.
3244 Other rules can be inferred by inspecting the libpng source.
3246 XIII. Y2K Compliance in libpng
3250 Since the PNG Development group is an ad-hoc body, we can't make
3251 an official declaration.
3253 This is your unofficial assurance that libpng from version 0.71 and
3254 upward through 1.4.1 are Y2K compliant. It is my belief that earlier
3255 versions were also Y2K compliant.
3257 Libpng only has three year fields. One is a 2-byte unsigned integer that
3258 will hold years up to 65535. The other two hold the date in text
3259 format, and will hold years up to 9999.
3262 "png_uint_16 year" in png_time_struct.
3265 "png_charp time_buffer" in png_struct and
3266 "near_time_buffer", which is a local character string in png.c.
3268 There are seven time-related functions:
3270 png_convert_to_rfc_1123() in png.c
3271 (formerly png_convert_to_rfc_1152() in error)
3272 png_convert_from_struct_tm() in pngwrite.c, called
3274 png_convert_from_time_t() in pngwrite.c
3275 png_get_tIME() in pngget.c
3276 png_handle_tIME() in pngrutil.c, called in pngread.c
3277 png_set_tIME() in pngset.c
3278 png_write_tIME() in pngwutil.c, called in pngwrite.c
3280 All appear to handle dates properly in a Y2K environment. The
3281 png_convert_from_time_t() function calls gmtime() to convert from system
3282 clock time, which returns (year - 1900), which we properly convert to
3283 the full 4-digit year. There is a possibility that applications using
3284 libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
3285 function, or that they are incorrectly passing only a 2-digit year
3286 instead of "year - 1900" into the png_convert_from_struct_tm() function,
3287 but this is not under our control. The libpng documentation has always
3288 stated that it works with 4-digit years, and the APIs have been
3291 The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
3292 integer to hold the year, and can hold years as large as 65535.
3294 zlib, upon which libpng depends, is also Y2K compliant. It contains
3295 no date-related code.
3298 Glenn Randers-Pehrson
3300 PNG Development Group