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