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