blob: ff5d16dbd31a92b77e0aa63d56fdb05b8815bd9b [file] [log] [blame]
Glenn Randers-Pehrson48854ae2010-10-17 12:52:29 -05001libpng-manual.txt - A description on how to use and modify libpng
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002
Glenn Randers-Pehrsonf3c51e42011-01-15 10:25:25 -06003 libpng version 1.5.1beta04 - January 15, 2011
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05004 Updated and distributed by Glenn Randers-Pehrson
5 <glennrp at users.sourceforge.net>
Glenn Randers-Pehrsonc182d552010-07-22 07:42:39 -05006 Copyright (c) 1998-2010 Glenn Randers-Pehrson
Glenn Randers-Pehrson037023b2009-06-24 10:27:36 -05007
Glenn Randers-Pehrsonbfbf8652009-06-26 21:46:52 -05008 This document is released under the libpng license.
Glenn Randers-Pehrsonc332bbc2009-06-25 13:43:50 -05009 For conditions of distribution and use, see the disclaimer
Glenn Randers-Pehrson037023b2009-06-24 10:27:36 -050010 and license in png.h
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -050011
12 Based on:
13
Glenn Randers-Pehrsonf3c51e42011-01-15 10:25:25 -060014 libpng versions 0.97, January 1998, through 1.5.1beta04 - January 15, 2011
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -050015 Updated and distributed by Glenn Randers-Pehrson
Glenn Randers-Pehrsonc182d552010-07-22 07:42:39 -050016 Copyright (c) 1998-2010 Glenn Randers-Pehrson
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -050017
18 libpng 1.0 beta 6 version 0.96 May 28, 1997
19 Updated and distributed by Andreas Dilger
20 Copyright (c) 1996, 1997 Andreas Dilger
21
22 libpng 1.0 beta 2 - version 0.88 January 26, 1996
23 For conditions of distribution and use, see copyright
24 notice in png.h. Copyright (c) 1995, 1996 Guy Eric
25 Schalnat, Group 42, Inc.
26
27 Updated/rewritten per request in the libpng FAQ
28 Copyright (c) 1995, 1996 Frank J. T. Wojcik
29 December 18, 1995 & January 20, 1996
30
31I. Introduction
32
33This file describes how to use and modify the PNG reference library
34(known as libpng) for your own use. There are five sections to this
35file: introduction, structures, reading, writing, and modification and
36configuration notes for various special platforms. In addition to this
37file, example.c is a good starting point for using the library, as
38it is heavily commented and should include everything most people
39will need. We assume that libpng is already installed; see the
40INSTALL file for instructions on how to install libpng.
41
42For examples of libpng usage, see the files "example.c", "pngtest.c",
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -060043and the files in the "contrib" directory, all of which are included in
44the libpng distribution.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -050045
46Libpng was written as a companion to the PNG specification, as a way
47of reducing the amount of time and effort it takes to support the PNG
48file format in application programs.
49
50The PNG specification (second edition), November 2003, is available as
51a W3C Recommendation and as an ISO Standard (ISO/IEC 15948:2003 (E)) at
52<http://www.w3.org/TR/2003/REC-PNG-20031110/
53The W3C and ISO documents have identical technical content.
54
55The PNG-1.2 specification is available at
56<http://www.libpng.org/pub/png/documents/>. It is technically equivalent
57to the PNG specification (second edition) but has some additional material.
58
59The PNG-1.0 specification is available
60as RFC 2083 <http://www.libpng.org/pub/png/documents/> and as a
61W3C Recommendation <http://www.w3.org/TR/REC.png.html>.
62
63Some additional chunks are described in the special-purpose public chunks
64documents at <http://www.libpng.org/pub/png/documents/>.
65
66Other information
67about PNG, and the latest version of libpng, can be found at the PNG home
68page, <http://www.libpng.org/pub/png/>.
69
70Most users will not have to modify the library significantly; advanced
71users may want to modify it more. All attempts were made to make it as
72complete as possible, while keeping the code easy to understand.
73Currently, this library only supports C. Support for other languages
74is being considered.
75
76Libpng has been designed to handle multiple sessions at one time,
77to be easily modifiable, to be portable to the vast majority of
78machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
79to use. The ultimate goal of libpng is to promote the acceptance of
80the PNG file format in whatever way possible. While there is still
81work to be done (see the TODO file), libpng should cover the
82majority of the needs of its users.
83
84Libpng uses zlib for its compression and decompression of PNG files.
85Further information about zlib, and the latest version of zlib, can
86be found at the zlib home page, <http://www.info-zip.org/pub/infozip/zlib/>.
87The zlib compression utility is a general purpose utility that is
88useful for more than PNG files, and can be used without libpng.
89See the documentation delivered with zlib for more details.
90You can usually find the source files for the zlib utility wherever you
91find the libpng source files.
92
93Libpng is thread safe, provided the threads are using different
94instances of the structures. Each thread should have its own
95png_struct and png_info instances, and thus its own image.
96Libpng does not protect itself against two threads using the
97same instance of a structure.
98
99II. Structures
100
101There are two main structures that are important to libpng, png_struct
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -0500102and png_info. Both are internal structures that are no longer exposed
103in the libpng interface (as of libpng 1.5.0).
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500104
105The png_info structure is designed to provide information about the
106PNG file. At one time, the fields of png_info were intended to be
107directly accessible to the user. However, this tended to cause problems
108with applications using dynamically loaded libraries, and as a result
109a set of interface functions for png_info (the png_get_*() and png_set_*()
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -0500110functions) was developed.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500111
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -0500112The png_struct structure is the object used by the library to decode a
113single image. As of 1.5.0 this structure is also not exposed.
114
115Almost all libpng APIs require a pointer to a png_struct as the first argument.
116Many (in particular the png_set and png_get APIs) also require a pointer
117to png_info as the second argument. Some application visible macros
118defined in png.h designed for basic data access (reading and writing
119integers in the PNG format) break this rule, but it's almost always safe
120to assume that a (png_struct*) has to be passed to call an API function.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500121
122The png.h header file is an invaluable reference for programming with libpng.
123And while I'm on the topic, make sure you include the libpng header file:
124
125#include <png.h>
126
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -0500127Types
128
129The png.h header file defines a number of integral types used by the
130APIs. Most of these are fairly obvious; for example types corresponding
131to integers of particular sizes and types for passing color values.
132
133One exception is how non-integral numbers are handled. For application
134convenience most APIs that take such numbers have C (double) arguments,
135however internally PNG, and libpng, use 32 bit signed integers and encode
136the value by multiplying by 100,000. As of libpng 1.5.0 a convenience
137macro PNG_FP_1 is defined in png.h along with a type (png_fixed_point)
138which is simply (png_int_32).
139
140All APIs that take (double) arguments also have an matching API that
141takes the corresponding fixed point integer arguments. The fixed point
142API has the same name as the floating point one with _fixed appended.
143The actual range of values permitted in the APIs is frequently less than
144the full range of (png_fixed_point) (-21474 to +21474). When APIs require
145a non-negative argument the type is recorded as png_uint_32 above. Consult
146the header file and the text below for more information.
147
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -0600148Special care must be take with sCAL chunk handling because the chunk itself
149uses non-integral values encoded as strings containing decimal floating point
150numbers. See the comments in the header file.
151
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -0500152Configuration
153
154The main header file function declarations are frequently protected by C
155preprocessing directives of the form:
156
157 #ifdef PNG_feature_SUPPORTED
158 declare-function
159 #endif
160
161The library can be built without support for these APIs, although a
162standard build will have all implemented APIs. Application programs
163should check the feature macros before using an API for maximum
164portability. From libpng 1.5.0 the feature macros set during the build
165of libpng are recorded in the header file "pnglibconf.h" and this file
166is always included by png.h.
167
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -0600168If you don't need to change the library configuration from the default skip to
169the next section ("Reading").
170
171Notice that some of the makefiles in the 'scripts' directory and (in 1.5.0) all
172of the build project files in the 'projects' directory simply copy
173scripts/pnglibconf.h.prebuilt to pnglibconf.h. This means that these build
174systems do not permit easy auto-configuration of the library - they only
175support the default configuration.
176
177The easiest way to make minor changes to the libpng configuration when
178auto-configuration is supported is to add definitions to the command line
179using (typically) CPPFLAGS. For example:
180
181CPPFLAGS=-DPNG_NO_FLOATING_ARITHMETIC
182
183will change the internal libpng math implementation for gamma correction and
184other arithmetic calculations to fixed point, avoiding the need for fast
185floating point support. The result can be seen in the generated pnglibconf.h -
186make sure it contains the changed feature macro setting.
187
188If you need to make more extensive configuration changes - more than one or two
189feature macro settings - you can either add -DPNG_USER_CONFIG to the build
190command line and put a list of feature macro settings in pngusr.h or you can set
191DFA_XTRA (a makefile variable) to a file containing the same information in the
192form of 'option' settings.
193
194A. Changing pnglibconf.h
195
196A variety of methods exist to build libpng. Not all of these support
197reconfiguration of pnglibconf.h. To reconfigure pnglibconf.h it must either be
198rebuilt from scripts/pnglibconf.dfa using awk or it must be edited by hand.
199
200Hand editing is achieved by copying scripts/pnglibconf.h.prebuilt and changing
201the lines defining the supported features, paying very close attention to the
202'option' information in scripts/pnglibconf.dfa that describes those features and
203their requirements. This is easy to get wrong.
204
205B. Configuration using DFA_XTRA
206
207Rebuilding from pnglibconf.dfa is easy if a functioning 'awk', or a later
208variant such as 'nawk' or 'gawk', is available. The configure build will
209automatically find an appropriate awk and build pnglibconf.h.
210scripts/pnglibconf.mak contains a set of make rules for doing the same thing if
211configure is not used, and many of the makefiles in the scripts directory use
212this approach.
213
214When rebuilding simply write new file containing changed options and set
215DFA_XTRA to the name of this file. This causes the build to append the new file
216to the end of scripts/pnglibconf.dfa. pngusr.dfa should contain lines of the
217following forms:
218
219everything = off
220
221This turns all optional features off. Include it at the start of pngusr.dfa to
222make it easier to build a minimal configuration. You will need to turn at least
223some features on afterward to enable either reading or writing code, or both.
224
225option feature on
226option feature off
227
228Enable or disable a single feature. This will automatically enable other
229features required by a feature that is turned on or disable other features that
230require a feature which is turned off. Conflicting settings will cause an error
231message to be emitted by awk.
232
233setting feature default value
234
235Changes the default value of setting 'feature' to 'value'. There are a small
236number of settings listed at the top of pnglibconf.h, they are documented in the
237source code. Most of these values have performance implications for the library
238but most of them have no visible effect on the API. Some can also be overridden
239from the API.
240
241C. Configuration using PNG_USR_CONFIG
242
243If -DPNG_USR_CONFIG is added to the CFLAGS when pnglibconf.h is built the file
244pngusr.h will automatically be included before the options in
245scripts/pnglibconf.dfa are processed. pngusr.h should contain only macro
246definitions turning features on or off or setting settings.
247
248Apart from the global setting "everything = off" all the options listed above
249can be set using macros in pngusr.h:
250
251#define PNG_feature_SUPPORTED
252
253is equivalent to:
254
255option feature on
256
257#define PNG_NO_feature
258
259is equivalent to:
260
261option feature off
262
263#define PNG_feature value
264
265is equivalent to:
266
267setting feature default value
268
269Notice that in both cases, pngusr.dfa and pngusr.h, the contents of the
270pngusr file you supply override the contents of scripts/pnglibconf.dfa
271
272If confusing or incomprehensible behavior results it is possible to
273examine the intermediate file pnglibconf.dfn to find the full set of
274dependency information for each setting and option. Simply locate the
275feature in the file and read the C comments that precede it.
276
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500277III. Reading
278
279We'll now walk you through the possible functions to call when reading
280in a PNG file sequentially, briefly explaining the syntax and purpose
281of each one. See example.c and png.h for more detail. While
282progressive reading is covered in the next section, you will still
283need some of the functions discussed in this section to read a PNG
284file.
285
286Setup
287
288You will want to do the I/O initialization(*) before you get into libpng,
289so if it doesn't work, you don't have much to undo. Of course, you
290will also want to insure that you are, in fact, dealing with a PNG
291file. Libpng provides a simple check to see if a file is a PNG file.
292To use it, pass in the first 1 to 8 bytes of the file to the function
293png_sig_cmp(), and it will return 0 (false) if the bytes match the
294corresponding bytes of the PNG signature, or nonzero (true) otherwise.
295Of course, the more bytes you pass in, the greater the accuracy of the
296prediction.
297
298If you are intending to keep the file pointer open for use in libpng,
299you must ensure you don't read more than 8 bytes from the beginning
300of the file, and you also have to make a call to png_set_sig_bytes_read()
301with the number of bytes you read from the beginning. Libpng will
302then only check the bytes (if any) that your program didn't read.
303
304(*): If you are not using the standard I/O functions, you will need
305to replace them with custom functions. See the discussion under
306Customizing libpng.
307
308
309 FILE *fp = fopen(file_name, "rb");
310 if (!fp)
311 {
312 return (ERROR);
313 }
314 fread(header, 1, number, fp);
315 is_png = !png_sig_cmp(header, 0, number);
316 if (!is_png)
317 {
318 return (NOT_PNG);
319 }
320
321
322Next, png_struct and png_info need to be allocated and initialized. In
323order to ensure that the size of these structures is correct even with a
324dynamically linked libpng, there are functions to initialize and
325allocate the structures. We also pass the library version, optional
326pointers to error handling functions, and a pointer to a data struct for
327use by the error functions, if necessary (the pointer and functions can
328be NULL if the default error handlers are to be used). See the section
329on Changes to Libpng below regarding the old initialization functions.
330The structure allocation functions quietly return NULL if they fail to
331create the structure, so your application should check for that.
332
333 png_structp png_ptr = png_create_read_struct
334 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
335 user_error_fn, user_warning_fn);
336 if (!png_ptr)
337 return (ERROR);
338
339 png_infop info_ptr = png_create_info_struct(png_ptr);
340 if (!info_ptr)
341 {
342 png_destroy_read_struct(&png_ptr,
343 (png_infopp)NULL, (png_infopp)NULL);
344 return (ERROR);
345 }
346
347 png_infop end_info = png_create_info_struct(png_ptr);
348 if (!end_info)
349 {
350 png_destroy_read_struct(&png_ptr, &info_ptr,
351 (png_infopp)NULL);
352 return (ERROR);
353 }
354
355If you want to use your own memory allocation routines,
356define PNG_USER_MEM_SUPPORTED and use
357png_create_read_struct_2() instead of png_create_read_struct():
358
359 png_structp png_ptr = png_create_read_struct_2
360 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
361 user_error_fn, user_warning_fn, (png_voidp)
362 user_mem_ptr, user_malloc_fn, user_free_fn);
363
364The error handling routines passed to png_create_read_struct()
365and the memory alloc/free routines passed to png_create_struct_2()
366are only necessary if you are not using the libpng supplied error
367handling and memory alloc/free functions.
368
369When libpng encounters an error, it expects to longjmp back
370to your routine. Therefore, you will need to call setjmp and pass
371your png_jmpbuf(png_ptr). If you read the file from different
372routines, you will need to update the jmpbuf field every time you enter
373a new routine that will call a png_*() function.
374
375See your documentation of setjmp/longjmp for your compiler for more
376information on setjmp/longjmp. See the discussion on libpng error
377handling in the Customizing Libpng section below for more information
378on the libpng error handling. If an error occurs, and libpng longjmp's
379back to your setjmp, you will want to call png_destroy_read_struct() to
380free any memory.
381
382 if (setjmp(png_jmpbuf(png_ptr)))
383 {
384 png_destroy_read_struct(&png_ptr, &info_ptr,
385 &end_info);
386 fclose(fp);
387 return (ERROR);
388 }
389
390If you would rather avoid the complexity of setjmp/longjmp issues,
Glenn Randers-Pehrson54ac9a92010-04-02 17:06:22 -0500391you can compile libpng with PNG_NO_SETJMP, in which case
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500392errors will result in a call to PNG_ABORT() which defaults to abort().
393
Glenn Randers-Pehrson54ac9a92010-04-02 17:06:22 -0500394You can #define PNG_ABORT() to a function that does something
395more useful than abort(), as long as your function does not
396return.
397
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500398Now you need to set up the input code. The default for libpng is to
399use the C function fread(). If you use this, you will need to pass a
400valid FILE * in the function png_init_io(). Be sure that the file is
401opened in binary mode. If you wish to handle reading data in another
402way, you need not call the png_init_io() function, but you must then
403implement the libpng I/O methods discussed in the Customizing Libpng
404section below.
405
406 png_init_io(png_ptr, fp);
407
408If you had previously opened the file and read any of the signature from
409the beginning in order to see if this was a PNG file, you need to let
410libpng know that there are some bytes missing from the start of the file.
411
412 png_set_sig_bytes(png_ptr, number);
413
Glenn Randers-Pehrsone3f3c4e2010-02-07 18:08:50 -0600414You can change the zlib compression buffer size to be used while
415reading compressed data with
416
417 png_set_compression_buffer_size(png_ptr, buffer_size);
418
419where the default size is 8192 bytes. Note that the buffer size
420is changed immediately and the buffer is reallocated immediately,
421instead of setting a flag to be acted upon later.
422
Glenn Randers-Pehrson9dd1cdf2011-01-06 21:42:36 -0600423If you want CRC errors to be handled in a different manner than
424the default, use
425
426 png_set_crc_action(png_ptr, crit_action, ancil_action);
427
428The values for png_set_crc_action() say how libpng is to handle CRC errors in
429ancillary and critical chunks, and whether to use the data contained
430therein. Note that it is impossible to "discard" data in a critical
431chunk.
432
433Choices for (int) crit_action are
434 PNG_CRC_DEFAULT 0 error/quit
435 PNG_CRC_ERROR_QUIT 1 error/quit
436 PNG_CRC_WARN_USE 3 warn/use data
437 PNG_CRC_QUIET_USE 4 quiet/use data
438 PNG_CRC_NO_CHANGE 5 use the current value
439
440Choices for (int) ancil_action are
441 PNG_CRC_DEFAULT 0 error/quit
442 PNG_CRC_ERROR_QUIT 1 error/quit
443 PNG_CRC_WARN_DISCARD 2 warn/discard data
444 PNG_CRC_WARN_USE 3 warn/use data
445 PNG_CRC_QUIET_USE 4 quiet/use data
446 PNG_CRC_NO_CHANGE 5 use the current value
447
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500448Setting up callback code
449
450You can set up a callback function to handle any unknown chunks in the
451input stream. You must supply the function
452
453 read_chunk_callback(png_ptr ptr,
454 png_unknown_chunkp chunk);
455 {
456 /* The unknown chunk structure contains your
457 chunk data, along with similar data for any other
458 unknown chunks: */
459
460 png_byte name[5];
461 png_byte *data;
462 png_size_t size;
463
464 /* Note that libpng has already taken care of
465 the CRC handling */
466
467 /* put your code here. Search for your chunk in the
468 unknown chunk structure, process it, and return one
469 of the following: */
470
471 return (-n); /* chunk had an error */
472 return (0); /* did not recognize */
473 return (n); /* success */
474 }
475
476(You can give your function another name that you like instead of
477"read_chunk_callback")
478
479To inform libpng about your function, use
480
481 png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr,
482 read_chunk_callback);
483
484This names not only the callback function, but also a user pointer that
485you can retrieve with
486
487 png_get_user_chunk_ptr(png_ptr);
488
489If you call the png_set_read_user_chunk_fn() function, then all unknown
490chunks will be saved when read, in case your callback function will need
491one or more of them. This behavior can be changed with the
492png_set_keep_unknown_chunks() function, described below.
493
494At this point, you can set up a callback function that will be
495called after each row has been read, which you can use to control
496a progress meter or the like. It's demonstrated in pngtest.c.
497You must supply a function
498
499 void read_row_callback(png_ptr ptr, png_uint_32 row,
500 int pass);
501 {
502 /* put your code here */
503 }
504
505(You can give it another name that you like instead of "read_row_callback")
506
507To inform libpng about your function, use
508
509 png_set_read_status_fn(png_ptr, read_row_callback);
510
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500511Unknown-chunk handling
512
513Now you get to set the way the library processes unknown chunks in the
514input PNG stream. Both known and unknown chunks will be read. Normal
515behavior is that known chunks will be parsed into information in
516various info_ptr members while unknown chunks will be discarded. This
517behavior can be wasteful if your application will never use some known
518chunk types. To change this, you can call:
519
520 png_set_keep_unknown_chunks(png_ptr, keep,
521 chunk_list, num_chunks);
522 keep - 0: default unknown chunk handling
523 1: ignore; do not keep
524 2: keep only if safe-to-copy
525 3: keep even if unsafe-to-copy
526 You can use these definitions:
527 PNG_HANDLE_CHUNK_AS_DEFAULT 0
528 PNG_HANDLE_CHUNK_NEVER 1
529 PNG_HANDLE_CHUNK_IF_SAFE 2
530 PNG_HANDLE_CHUNK_ALWAYS 3
531 chunk_list - list of chunks affected (a byte string,
532 five bytes per chunk, NULL or '\0' if
533 num_chunks is 0)
534 num_chunks - number of chunks affected; if 0, all
535 unknown chunks are affected. If nonzero,
536 only the chunks in the list are affected
537
538Unknown chunks declared in this way will be saved as raw data onto a
539list of png_unknown_chunk structures. If a chunk that is normally
540known to libpng is named in the list, it will be handled as unknown,
541according to the "keep" directive. If a chunk is named in successive
542instances of png_set_keep_unknown_chunks(), the final instance will
543take precedence. The IHDR and IEND chunks should not be named in
544chunk_list; if they are, libpng will process them normally anyway.
545
546Here is an example of the usage of png_set_keep_unknown_chunks(),
547where the private "vpAg" chunk will later be processed by a user chunk
548callback function:
549
550 png_byte vpAg[5]={118, 112, 65, 103, (png_byte) '\0'};
551
552 #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
553 png_byte unused_chunks[]=
554 {
555 104, 73, 83, 84, (png_byte) '\0', /* hIST */
556 105, 84, 88, 116, (png_byte) '\0', /* iTXt */
557 112, 67, 65, 76, (png_byte) '\0', /* pCAL */
558 115, 67, 65, 76, (png_byte) '\0', /* sCAL */
559 115, 80, 76, 84, (png_byte) '\0', /* sPLT */
560 116, 73, 77, 69, (png_byte) '\0', /* tIME */
561 };
562 #endif
563
564 ...
565
566 #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
567 /* ignore all unknown chunks: */
568 png_set_keep_unknown_chunks(read_ptr, 1, NULL, 0);
569 /* except for vpAg: */
570 png_set_keep_unknown_chunks(read_ptr, 2, vpAg, 1);
571 /* also ignore unused known chunks: */
572 png_set_keep_unknown_chunks(read_ptr, 1, unused_chunks,
573 (int)sizeof(unused_chunks)/5);
574 #endif
575
576User limits
577
578The PNG specification allows the width and height of an image to be as
579large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.
580Since very few applications really need to process such large images,
581we have imposed an arbitrary 1-million limit on rows and columns.
582Larger images will be rejected immediately with a png_error() call. If
583you wish to override this limit, you can use
584
585 png_set_user_limits(png_ptr, width_max, height_max);
586
587to set your own limits, or use width_max = height_max = 0x7fffffffL
588to allow all valid dimensions (libpng may reject some very large images
589anyway because of potential buffer overflow conditions).
590
591You should put this statement after you create the PNG structure and
592before calling png_read_info(), png_read_png(), or png_process_data().
593If you need to retrieve the limits that are being applied, use
594
595 width_max = png_get_user_width_max(png_ptr);
596 height_max = png_get_user_height_max(png_ptr);
597
598The PNG specification sets no limit on the number of ancillary chunks
599allowed in a PNG datastream. You can impose a limit on the total number
600of sPLT, tEXt, iTXt, zTXt, and unknown chunks that will be stored, with
601
602 png_set_chunk_cache_max(png_ptr, user_chunk_cache_max);
603
604where 0x7fffffffL means unlimited. You can retrieve this limit with
605
606 chunk_cache_max = png_get_chunk_cache_max(png_ptr);
607
Glenn Randers-Pehrsonef29a5e2009-10-31 19:37:05 -0500608This limit also applies to the number of buffers that can be allocated
Glenn Randers-Pehrson8f5846f2009-10-31 21:31:08 -0500609by png_decompress_chunk() while decompressing iTXt, zTXt, and iCCP chunks.
Glenn Randers-Pehrsonef29a5e2009-10-31 19:37:05 -0500610
Glenn Randers-Pehrsone3f3c4e2010-02-07 18:08:50 -0600611You can also set a limit on the amount of memory that a compressed chunk
612other than IDAT can occupy, with
613
614 png_set_chunk_malloc_max(png_ptr, user_chunk_malloc_max);
615
616and you can retrieve the limit with
617
618 chunk_malloc_max = png_get_chunk_malloc_max(png_ptr);
619
620Any chunks that would cause either of these limits to be exceeded will
621be ignored.
622
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500623The high-level read interface
624
625At this point there are two ways to proceed; through the high-level
626read interface, or through a sequence of low-level read operations.
627You can use the high-level interface if (a) you are willing to read
628the entire image into memory, and (b) the input transformations
629you want to do are limited to the following set:
630
631 PNG_TRANSFORM_IDENTITY No transformation
632 PNG_TRANSFORM_STRIP_16 Strip 16-bit samples to
633 8 bits
634 PNG_TRANSFORM_STRIP_ALPHA Discard the alpha channel
635 PNG_TRANSFORM_PACKING Expand 1, 2 and 4-bit
636 samples to bytes
637 PNG_TRANSFORM_PACKSWAP Change order of packed
638 pixels to LSB first
639 PNG_TRANSFORM_EXPAND Perform set_expand()
640 PNG_TRANSFORM_INVERT_MONO Invert monochrome images
641 PNG_TRANSFORM_SHIFT Normalize pixels to the
642 sBIT depth
643 PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
644 to BGRA
645 PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
646 to AG
647 PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
648 to transparency
649 PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
Glenn Randers-Pehrson99708d52009-06-29 17:30:00 -0500650 PNG_TRANSFORM_GRAY_TO_RGB Expand grayscale samples
651 to RGB (or GA to RGBA)
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500652
653(This excludes setting a background color, doing gamma transformation,
Glenn Randers-Pehrson3cd7cff2010-04-16 19:27:08 -0500654quantizing, and setting filler.) If this is the case, simply do this:
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500655
656 png_read_png(png_ptr, info_ptr, png_transforms, NULL)
657
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -0600658where png_transforms is an integer containing the bitwise OR of some
659set of transformation flags. This call is equivalent to png_read_info(),
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500660followed the set of transformations indicated by the transform mask,
661then png_read_image(), and finally png_read_end().
662
663(The final parameter of this call is not yet used. Someday it might point
664to transformation parameters required by some future input transform.)
665
666You must use png_transforms and not call any png_set_transform() functions
667when you use png_read_png().
668
669After you have called png_read_png(), you can retrieve the image data
670with
671
672 row_pointers = png_get_rows(png_ptr, info_ptr);
673
674where row_pointers is an array of pointers to the pixel data for each row:
675
676 png_bytep row_pointers[height];
677
678If you know your image size and pixel size ahead of time, you can allocate
679row_pointers prior to calling png_read_png() with
680
681 if (height > PNG_UINT_32_MAX/png_sizeof(png_byte))
682 png_error (png_ptr,
683 "Image is too tall to process in memory");
684 if (width > PNG_UINT_32_MAX/pixel_size)
685 png_error (png_ptr,
686 "Image is too wide to process in memory");
687 row_pointers = png_malloc(png_ptr,
688 height*png_sizeof(png_bytep));
689 for (int i=0; i<height, i++)
690 row_pointers[i]=NULL; /* security precaution */
691 for (int i=0; i<height, i++)
692 row_pointers[i]=png_malloc(png_ptr,
693 width*pixel_size);
694 png_set_rows(png_ptr, info_ptr, &row_pointers);
695
696Alternatively you could allocate your image in one big block and define
697row_pointers[i] to point into the proper places in your block.
698
699If you use png_set_rows(), the application is responsible for freeing
700row_pointers (and row_pointers[i], if they were separately allocated).
701
702If you don't allocate row_pointers ahead of time, png_read_png() will
703do it, and it'll be free'ed when you call png_destroy_*().
704
705The low-level read interface
706
707If you are going the low-level route, you are now ready to read all
708the file information up to the actual image data. You do this with a
709call to png_read_info().
710
711 png_read_info(png_ptr, info_ptr);
712
713This will process all chunks up to but not including the image data.
714
715Querying the info structure
716
717Functions are used to get the information from the info_ptr once it
718has been read. Note that these fields may not be completely filled
719in until png_read_end() has read the chunk data following the image.
720
721 png_get_IHDR(png_ptr, info_ptr, &width, &height,
722 &bit_depth, &color_type, &interlace_type,
723 &compression_type, &filter_method);
724
725 width - holds the width of the image
726 in pixels (up to 2^31).
727 height - holds the height of the image
728 in pixels (up to 2^31).
729 bit_depth - holds the bit depth of one of the
730 image channels. (valid values are
731 1, 2, 4, 8, 16 and depend also on
732 the color_type. See also
733 significant bits (sBIT) below).
734 color_type - describes which color/alpha channels
735 are present.
736 PNG_COLOR_TYPE_GRAY
737 (bit depths 1, 2, 4, 8, 16)
738 PNG_COLOR_TYPE_GRAY_ALPHA
739 (bit depths 8, 16)
740 PNG_COLOR_TYPE_PALETTE
741 (bit depths 1, 2, 4, 8)
742 PNG_COLOR_TYPE_RGB
743 (bit_depths 8, 16)
744 PNG_COLOR_TYPE_RGB_ALPHA
745 (bit_depths 8, 16)
746
747 PNG_COLOR_MASK_PALETTE
748 PNG_COLOR_MASK_COLOR
749 PNG_COLOR_MASK_ALPHA
750
751 filter_method - (must be PNG_FILTER_TYPE_BASE
752 for PNG 1.0, and can also be
753 PNG_INTRAPIXEL_DIFFERENCING if
754 the PNG datastream is embedded in
755 a MNG-1.0 datastream)
756 compression_type - (must be PNG_COMPRESSION_TYPE_BASE
757 for PNG 1.0)
758 interlace_type - (PNG_INTERLACE_NONE or
759 PNG_INTERLACE_ADAM7)
Glenn Randers-Pehrsonb35a7452009-09-30 23:12:13 -0500760
761 Any or all of interlace_type, compression_type, or
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500762 filter_method can be NULL if you are
763 not interested in their values.
764
Glenn Randers-Pehrsonb35a7452009-09-30 23:12:13 -0500765 Note that png_get_IHDR() returns 32-bit data into
766 the application's width and height variables.
767 This is an unsafe situation if these are 16-bit
768 variables. In such situations, the
769 png_get_image_width() and png_get_image_height()
770 functions described below are safer.
771
772 width = png_get_image_width(png_ptr,
773 info_ptr);
774 height = png_get_image_height(png_ptr,
775 info_ptr);
776 bit_depth = png_get_bit_depth(png_ptr,
777 info_ptr);
778 color_type = png_get_color_type(png_ptr,
779 info_ptr);
780 filter_method = png_get_filter_type(png_ptr,
781 info_ptr);
782 compression_type = png_get_compression_type(png_ptr,
783 info_ptr);
784 interlace_type = png_get_interlace_type(png_ptr,
785 info_ptr);
786
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500787 channels = png_get_channels(png_ptr, info_ptr);
788 channels - number of channels of info for the
789 color type (valid values are 1 (GRAY,
790 PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
791 4 (RGB_ALPHA or RGB + filler byte))
792 rowbytes = png_get_rowbytes(png_ptr, info_ptr);
793 rowbytes - number of bytes needed to hold a row
794
795 signature = png_get_signature(png_ptr, info_ptr);
796 signature - holds the signature read from the
797 file (if any). The data is kept in
798 the same offset it would be if the
799 whole signature were read (i.e. if an
800 application had already read in 4
801 bytes of signature before starting
802 libpng, the remaining 4 bytes would
803 be in signature[4] through signature[7]
804 (see png_set_sig_bytes())).
805
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500806These are also important, but their validity depends on whether the chunk
807has been read. The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
808png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
809data has been read, or zero if it is missing. The parameters to the
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -0600810png_get_<chunk> are set directly if they are simple data types, or a
811pointer into the info_ptr is returned for any complex types.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500812
813 png_get_PLTE(png_ptr, info_ptr, &palette,
814 &num_palette);
815 palette - the palette for the file
816 (array of png_color)
817 num_palette - number of entries in the palette
818
819 png_get_gAMA(png_ptr, info_ptr, &gamma);
820 gamma - the gamma the file is written
821 at (PNG_INFO_gAMA)
822
823 png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
824 srgb_intent - the rendering intent (PNG_INFO_sRGB)
825 The presence of the sRGB chunk
826 means that the pixel data is in the
827 sRGB color space. This chunk also
828 implies specific values of gAMA and
829 cHRM.
830
831 png_get_iCCP(png_ptr, info_ptr, &name,
832 &compression_type, &profile, &proflen);
Glenn Randers-Pehrson4a5a1ec2011-01-15 11:43:28 -0600833 name - The profile name.
834 compression_type - The compression type; always
835 PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
836 You may give NULL to this argument to
837 ignore it.
838 profile - International Color Consortium color
839 profile data. May contain NULs.
840 proflen - length of profile data in bytes.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500841
842 png_get_sBIT(png_ptr, info_ptr, &sig_bit);
843 sig_bit - the number of significant bits for
844 (PNG_INFO_sBIT) each of the gray,
845 red, green, and blue channels,
846 whichever are appropriate for the
847 given color type (png_color_16)
848
Glenn Randers-Pehrson866b62a2009-08-08 16:33:14 -0500849 png_get_tRNS(png_ptr, info_ptr, &trans_alpha,
850 &num_trans, &trans_color);
851 trans_alpha - array of alpha (transparency)
852 entries for palette (PNG_INFO_tRNS)
Glenn Randers-Pehrsonf3c51e42011-01-15 10:25:25 -0600853 num_trans - number of transparent entries
854 (PNG_INFO_tRNS)
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500855 trans_color - graylevel or color sample values of
856 the single transparent color for
857 non-paletted images (PNG_INFO_tRNS)
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500858
859 png_get_hIST(png_ptr, info_ptr, &hist);
860 (PNG_INFO_hIST)
861 hist - histogram of palette (array of
862 png_uint_16)
863
864 png_get_tIME(png_ptr, info_ptr, &mod_time);
865 mod_time - time image was last modified
866 (PNG_VALID_tIME)
867
868 png_get_bKGD(png_ptr, info_ptr, &background);
869 background - background color (PNG_VALID_bKGD)
870 valid 16-bit red, green and blue
871 values, regardless of color_type
872
873 num_comments = png_get_text(png_ptr, info_ptr,
874 &text_ptr, &num_text);
875 num_comments - number of comments
876 text_ptr - array of png_text holding image
877 comments
878 text_ptr[i].compression - type of compression used
879 on "text" PNG_TEXT_COMPRESSION_NONE
880 PNG_TEXT_COMPRESSION_zTXt
881 PNG_ITXT_COMPRESSION_NONE
882 PNG_ITXT_COMPRESSION_zTXt
883 text_ptr[i].key - keyword for comment. Must contain
884 1-79 characters.
885 text_ptr[i].text - text comments for current
886 keyword. Can be empty.
887 text_ptr[i].text_length - length of text string,
888 after decompression, 0 for iTXt
889 text_ptr[i].itxt_length - length of itxt string,
890 after decompression, 0 for tEXt/zTXt
891 text_ptr[i].lang - language of comment (empty
892 string for unknown).
893 text_ptr[i].lang_key - keyword in UTF-8
894 (empty string for unknown).
Glenn Randers-Pehrsonef29a5e2009-10-31 19:37:05 -0500895 Note that the itxt_length, lang, and lang_key
896 members of the text_ptr structure only exist
897 when the library is built with iTXt chunk support.
898
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -0500899 num_text - number of comments (same as
900 num_comments; you can put NULL here
901 to avoid the duplication)
902 Note while png_set_text() will accept text, language,
903 and translated keywords that can be NULL pointers, the
904 structure returned by png_get_text will always contain
905 regular zero-terminated C strings. They might be
906 empty strings but they will never be NULL pointers.
907
908 num_spalettes = png_get_sPLT(png_ptr, info_ptr,
909 &palette_ptr);
910 palette_ptr - array of palette structures holding
911 contents of one or more sPLT chunks
912 read.
913 num_spalettes - number of sPLT chunks read.
914
915 png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
916 &unit_type);
917 offset_x - positive offset from the left edge
918 of the screen
919 offset_y - positive offset from the top edge
920 of the screen
921 unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
922
923 png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
924 &unit_type);
925 res_x - pixels/unit physical resolution in
926 x direction
927 res_y - pixels/unit physical resolution in
928 x direction
929 unit_type - PNG_RESOLUTION_UNKNOWN,
930 PNG_RESOLUTION_METER
931
932 png_get_sCAL(png_ptr, info_ptr, &unit, &width,
933 &height)
934 unit - physical scale units (an integer)
935 width - width of a pixel in physical scale units
936 height - height of a pixel in physical scale units
937 (width and height are doubles)
938
939 png_get_sCAL_s(png_ptr, info_ptr, &unit, &width,
940 &height)
941 unit - physical scale units (an integer)
942 width - width of a pixel in physical scale units
943 height - height of a pixel in physical scale units
944 (width and height are strings like "2.54")
945
946 num_unknown_chunks = png_get_unknown_chunks(png_ptr,
947 info_ptr, &unknowns)
948 unknowns - array of png_unknown_chunk
949 structures holding unknown chunks
950 unknowns[i].name - name of unknown chunk
951 unknowns[i].data - data of unknown chunk
952 unknowns[i].size - size of unknown chunk's data
953 unknowns[i].location - position of chunk in file
954
955 The value of "i" corresponds to the order in which the
956 chunks were read from the PNG file or inserted with the
957 png_set_unknown_chunks() function.
958
959The data from the pHYs chunk can be retrieved in several convenient
960forms:
961
962 res_x = png_get_x_pixels_per_meter(png_ptr,
963 info_ptr)
964 res_y = png_get_y_pixels_per_meter(png_ptr,
965 info_ptr)
966 res_x_and_y = png_get_pixels_per_meter(png_ptr,
967 info_ptr)
968 res_x = png_get_x_pixels_per_inch(png_ptr,
969 info_ptr)
970 res_y = png_get_y_pixels_per_inch(png_ptr,
971 info_ptr)
972 res_x_and_y = png_get_pixels_per_inch(png_ptr,
973 info_ptr)
974 aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
975 info_ptr)
976
977 (Each of these returns 0 [signifying "unknown"] if
978 the data is not present or if res_x is 0;
979 res_x_and_y is 0 if res_x != res_y)
980
981The data from the oFFs chunk can be retrieved in several convenient
982forms:
983
984 x_offset = png_get_x_offset_microns(png_ptr, info_ptr);
985 y_offset = png_get_y_offset_microns(png_ptr, info_ptr);
986 x_offset = png_get_x_offset_inches(png_ptr, info_ptr);
987 y_offset = png_get_y_offset_inches(png_ptr, info_ptr);
988
989 (Each of these returns 0 [signifying "unknown" if both
990 x and y are 0] if the data is not present or if the
991 chunk is present but the unit is the pixel)
992
993For more information, see the png_info definition in png.h and the
994PNG specification for chunk contents. Be careful with trusting
995rowbytes, as some of the transformations could increase the space
996needed to hold a row (expand, filler, gray_to_rgb, etc.).
997See png_read_update_info(), below.
998
999A quick word about text_ptr and num_text. PNG stores comments in
1000keyword/text pairs, one pair per chunk, with no limit on the number
1001of text chunks, and a 2^31 byte limit on their size. While there are
1002suggested keywords, there is no requirement to restrict the use to these
1003strings. It is strongly suggested that keywords and text be sensible
1004to humans (that's the point), so don't use abbreviations. Non-printing
1005symbols are not allowed. See the PNG specification for more details.
1006There is also no requirement to have text after the keyword.
1007
1008Keywords should be limited to 79 Latin-1 characters without leading or
1009trailing spaces, but non-consecutive spaces are allowed within the
1010keyword. It is possible to have the same keyword any number of times.
1011The text_ptr is an array of png_text structures, each holding a
1012pointer to a language string, a pointer to a keyword and a pointer to
1013a text string. The text string, language code, and translated
1014keyword may be empty or NULL pointers. The keyword/text
1015pairs are put into the array in the order that they are received.
1016However, some or all of the text chunks may be after the image, so, to
1017make sure you have read all the text chunks, don't mess with these
1018until after you read the stuff after the image. This will be
1019mentioned again below in the discussion that goes with png_read_end().
1020
1021Input transformations
1022
1023After you've read the header information, you can set up the library
1024to handle any special transformations of the image data. The various
1025ways to transform the data will be described in the order that they
1026should occur. This is important, as some of these change the color
1027type and/or bit depth of the data, and some others only work on
1028certain color types and bit depths. Even though each transformation
1029checks to see if it has data that it can do something with, you should
1030make sure to only enable a transformation if it will be valid for the
1031data. For example, don't swap red and blue on grayscale data.
1032
1033The colors used for the background and transparency values should be
1034supplied in the same format/depth as the current image data. They
1035are stored in the same format/depth as the image data in a bKGD or tRNS
1036chunk, so this is what libpng expects for this data. The colors are
1037transformed to keep in sync with the image data when an application
1038calls the png_read_update_info() routine (see below).
1039
1040Data will be decoded into the supplied row buffers packed into bytes
1041unless the library has been told to transform it into another format.
1042For example, 4 bit/pixel paletted or grayscale data will be returned
10432 pixels/byte with the leftmost pixel in the high-order bits of the
1044byte, unless png_set_packing() is called. 8-bit RGB data will be stored
1045in RGB RGB RGB format unless png_set_filler() or png_set_add_alpha()
1046is called to insert filler bytes, either before or after each RGB triplet.
104716-bit RGB data will be returned RRGGBB RRGGBB, with the most significant
1048byte of the color value first, unless png_set_strip_16() is called to
1049transform it to regular RGB RGB triplets, or png_set_filler() or
1050png_set_add alpha() is called to insert filler bytes, either before or
1051after each RRGGBB triplet. Similarly, 8-bit or 16-bit grayscale data can
1052be modified with
1053png_set_filler(), png_set_add_alpha(), or png_set_strip_16().
1054
1055The following code transforms grayscale images of less than 8 to 8 bits,
1056changes paletted images to RGB, and adds a full alpha channel if there is
1057transparency information in a tRNS chunk. This is most useful on
1058grayscale images with bit depths of 2 or 4 or if there is a multiple-image
1059viewing application that wishes to treat all images in the same way.
1060
1061 if (color_type == PNG_COLOR_TYPE_PALETTE)
1062 png_set_palette_to_rgb(png_ptr);
1063
1064 if (color_type == PNG_COLOR_TYPE_GRAY &&
1065 bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png_ptr);
1066
1067 if (png_get_valid(png_ptr, info_ptr,
1068 PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
1069
1070These three functions are actually aliases for png_set_expand(), added
1071in libpng version 1.0.4, with the function names expanded to improve code
1072readability. In some future version they may actually do different
1073things.
1074
1075As of libpng version 1.2.9, png_set_expand_gray_1_2_4_to_8() was
1076added. It expands the sample depth without changing tRNS to alpha.
1077
Glenn Randers-Pehrsonf3c51e42011-01-15 10:25:25 -06001078As of libpng version 1.5.1beta04, not all possible expansions are supported.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001079
1080In the following table, the 01 means grayscale with depth<8, 31 means
1081indexed with depth<8, other numerals represent the color type, "T" means
1082the tRNS chunk is present, A means an alpha channel is present, and O
1083means tRNS or alpha is present but all pixels in the image are opaque.
1084
1085 FROM 01 31 0 0T 0O 2 2T 2O 3 3T 3O 4A 4O 6A 6O
1086 TO
1087 01 -
1088 31 -
1089 0 1 -
1090 0T -
1091 0O -
1092 2 GX -
1093 2T -
1094 2O -
1095 3 1 -
1096 3T -
1097 3O -
1098 4A T -
1099 4O -
1100 6A GX TX TX -
1101 6O GX TX -
1102
1103Within the matrix,
1104 "-" means the transformation is not supported.
1105 "X" means the transformation is obtained by png_set_expand().
1106 "1" means the transformation is obtained by
1107 png_set_expand_gray_1_2_4_to_8
1108 "G" means the transformation is obtained by
1109 png_set_gray_to_rgb().
1110 "P" means the transformation is obtained by
1111 png_set_expand_palette_to_rgb().
1112 "T" means the transformation is obtained by
1113 png_set_tRNS_to_alpha().
1114
1115PNG can have files with 16 bits per channel. If you only can handle
11168 bits per channel, this will strip the pixels down to 8 bit.
1117
1118 if (bit_depth == 16)
1119 png_set_strip_16(png_ptr);
1120
1121If, for some reason, you don't need the alpha channel on an image,
1122and you want to remove it rather than combining it with the background
1123(but the image author certainly had in mind that you *would* combine
1124it with the background, so that's what you should probably do):
1125
1126 if (color_type & PNG_COLOR_MASK_ALPHA)
1127 png_set_strip_alpha(png_ptr);
1128
1129In PNG files, the alpha channel in an image
1130is the level of opacity. If you need the alpha channel in an image to
1131be the level of transparency instead of opacity, you can invert the
1132alpha channel (or the tRNS chunk data) after it's read, so that 0 is
1133fully opaque and 255 (in 8-bit or paletted images) or 65535 (in 16-bit
1134images) is fully transparent, with
1135
1136 png_set_invert_alpha(png_ptr);
1137
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001138PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
1139they can, resulting in, for example, 8 pixels per byte for 1 bit
1140files. This code expands to 1 pixel per byte without changing the
1141values of the pixels:
1142
1143 if (bit_depth < 8)
1144 png_set_packing(png_ptr);
1145
1146PNG files have possible bit depths of 1, 2, 4, 8, and 16. All pixels
1147stored in a PNG image have been "scaled" or "shifted" up to the next
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06001148higher possible bit depth (e.g. from 5 bits/sample in the range [0,31]
1149to 8 bits/sample in the range [0, 255]). However, it is also possible
1150to convert the PNG pixel data back to the original bit depth of the
1151image. This call reduces the pixels back down to the original bit depth:
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001152
1153 png_color_8p sig_bit;
1154
1155 if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
1156 png_set_shift(png_ptr, sig_bit);
1157
1158PNG files store 3-color pixels in red, green, blue order. This code
1159changes the storage of the pixels to blue, green, red:
1160
1161 if (color_type == PNG_COLOR_TYPE_RGB ||
1162 color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1163 png_set_bgr(png_ptr);
1164
1165PNG files store RGB pixels packed into 3 or 6 bytes. This code expands them
1166into 4 or 8 bytes for windowing systems that need them in this format:
1167
1168 if (color_type == PNG_COLOR_TYPE_RGB)
1169 png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
1170
1171where "filler" is the 8 or 16-bit number to fill with, and the location is
1172either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
1173you want the filler before the RGB or after. This transformation
1174does not affect images that already have full alpha channels. To add an
1175opaque alpha channel, use filler=0xff or 0xffff and PNG_FILLER_AFTER which
1176will generate RGBA pixels.
1177
1178Note that png_set_filler() does not change the color type. If you want
1179to do that, you can add a true alpha channel with
1180
1181 if (color_type == PNG_COLOR_TYPE_RGB ||
1182 color_type == PNG_COLOR_TYPE_GRAY)
1183 png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER);
1184
1185where "filler" contains the alpha value to assign to each pixel.
1186This function was added in libpng-1.2.7.
1187
1188If you are reading an image with an alpha channel, and you need the
1189data as ARGB instead of the normal PNG format RGBA:
1190
1191 if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1192 png_set_swap_alpha(png_ptr);
1193
1194For some uses, you may want a grayscale image to be represented as
1195RGB. This code will do that conversion:
1196
1197 if (color_type == PNG_COLOR_TYPE_GRAY ||
1198 color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
1199 png_set_gray_to_rgb(png_ptr);
1200
1201Conversely, you can convert an RGB or RGBA image to grayscale or grayscale
1202with alpha.
1203
1204 if (color_type == PNG_COLOR_TYPE_RGB ||
1205 color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1206 png_set_rgb_to_gray_fixed(png_ptr, error_action,
1207 int red_weight, int green_weight);
1208
1209 error_action = 1: silently do the conversion
1210 error_action = 2: issue a warning if the original
1211 image has any pixel where
1212 red != green or red != blue
1213 error_action = 3: issue an error and abort the
1214 conversion if the original
1215 image has any pixel where
1216 red != green or red != blue
1217
1218 red_weight: weight of red component times 100000
1219 green_weight: weight of green component times 100000
1220 If either weight is negative, default
1221 weights (21268, 71514) are used.
1222
1223If you have set error_action = 1 or 2, you can
1224later check whether the image really was gray, after processing
1225the image rows, with the png_get_rgb_to_gray_status(png_ptr) function.
1226It will return a png_byte that is zero if the image was gray or
12271 if there were any non-gray pixels. bKGD and sBIT data
1228will be silently converted to grayscale, using the green channel
1229data, regardless of the error_action setting.
1230
1231With red_weight+green_weight<=100000,
1232the normalized graylevel is computed:
1233
1234 int rw = red_weight * 65536;
1235 int gw = green_weight * 65536;
1236 int bw = 65536 - (rw + gw);
1237 gray = (rw*red + gw*green + bw*blue)/65536;
1238
1239The default values approximate those recommended in the Charles
1240Poynton's Color FAQ, <http://www.inforamp.net/~poynton/>
1241Copyright (c) 1998-01-04 Charles Poynton <poynton at inforamp.net>
1242
1243 Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
1244
1245Libpng approximates this with
1246
1247 Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
1248
1249which can be expressed with integers as
1250
1251 Y = (6969 * R + 23434 * G + 2365 * B)/32768
1252
1253The calculation is done in a linear colorspace, if the image gamma
1254is known.
1255
1256If you have a grayscale and you are using png_set_expand_depth(),
1257png_set_expand(), or png_set_gray_to_rgb to change to truecolor or to
1258a higher bit-depth, you must either supply the background color as a gray
1259value at the original file bit-depth (need_expand = 1) or else supply the
1260background color as an RGB triplet at the final, expanded bit depth
1261(need_expand = 0). Similarly, if you are reading a paletted image, you
1262must either supply the background color as a palette index (need_expand = 1)
1263or as an RGB triplet that may or may not be in the palette (need_expand = 0).
1264
1265 png_color_16 my_background;
1266 png_color_16p image_background;
1267
1268 if (png_get_bKGD(png_ptr, info_ptr, &image_background))
1269 png_set_background(png_ptr, image_background,
1270 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
1271 else
1272 png_set_background(png_ptr, &my_background,
1273 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
1274
1275The png_set_background() function tells libpng to composite images
1276with alpha or simple transparency against the supplied background
1277color. If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
1278you may use this color, or supply another color more suitable for
1279the current display (e.g., the background color from a web page). You
1280need to tell libpng whether the color is in the gamma space of the
1281display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
1282(PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
1283that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
1284know why anyone would use this, but it's here).
1285
1286To properly display PNG images on any kind of system, the application needs
1287to know what the display gamma is. Ideally, the user will know this, and
1288the application will allow them to set it. One method of allowing the user
1289to set the display gamma separately for each system is to check for a
1290SCREEN_GAMMA or DISPLAY_GAMMA environment variable, which will hopefully be
1291correctly set.
1292
1293Note that display_gamma is the overall gamma correction required to produce
1294pleasing results, which depends on the lighting conditions in the surrounding
1295environment. In a dim or brightly lit room, no compensation other than
1296the physical gamma exponent of the monitor is needed, while in a dark room
1297a slightly smaller exponent is better.
1298
1299 double gamma, screen_gamma;
1300
1301 if (/* We have a user-defined screen
1302 gamma value */)
1303 {
1304 screen_gamma = user_defined_screen_gamma;
1305 }
1306 /* One way that applications can share the same
1307 screen gamma value */
1308 else if ((gamma_str = getenv("SCREEN_GAMMA"))
1309 != NULL)
1310 {
1311 screen_gamma = (double)atof(gamma_str);
1312 }
1313 /* If we don't have another value */
1314 else
1315 {
1316 screen_gamma = 2.2; /* A good guess for a
1317 PC monitor in a bright office or a dim room */
1318 screen_gamma = 2.0; /* A good guess for a
1319 PC monitor in a dark room */
1320 screen_gamma = 1.7 or 1.0; /* A good
1321 guess for Mac systems */
1322 }
1323
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -05001324The functions png_set_gamma() and its fixed point equivalent
1325png_set_gamma_fixed() handle gamma transformations of the data.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001326Pass both the file gamma and the current screen_gamma. If the file does
1327not have a gamma value, you can pass one anyway if you have an idea what
1328it is (usually 0.45455 is a good guess for GIF images on PCs). Note
1329that file gammas are inverted from screen gammas. See the discussions
1330on gamma in the PNG specification for an excellent description of what
1331gamma is, and why all applications should support it. It is strongly
1332recommended that PNG viewers support gamma correction.
1333
1334 if (png_get_gAMA(png_ptr, info_ptr, &gamma))
1335 png_set_gamma(png_ptr, screen_gamma, gamma);
1336 else
1337 png_set_gamma(png_ptr, screen_gamma, 0.45455);
1338
Glenn Randers-Pehrson3cd7cff2010-04-16 19:27:08 -05001339If you need to reduce an RGB file to a paletted file, or if a paletted
1340file has more entries then will fit on your screen, png_set_quantize()
Glenn Randers-Pehrson862cb202010-04-16 22:12:51 -05001341will do that. Note that this is a simple match quantization that merely
Glenn Randers-Pehrson3cd7cff2010-04-16 19:27:08 -05001342finds the closest color available. This should work fairly well with
1343optimized palettes, and fairly badly with linear color cubes. If you
1344pass a palette that is larger then maximum_colors, the file will
1345reduce the number of colors in the palette so it will fit into
1346maximum_colors. If there is a histogram, it will use it to make
1347more intelligent choices when reducing the palette. If there is no
1348histogram, it may not do as good a job.
1349
1350 if (color_type & PNG_COLOR_MASK_COLOR)
1351 {
1352 if (png_get_valid(png_ptr, info_ptr,
1353 PNG_INFO_PLTE))
1354 {
1355 png_uint_16p histogram = NULL;
1356
1357 png_get_hIST(png_ptr, info_ptr,
1358 &histogram);
1359 png_set_quantize(png_ptr, palette, num_palette,
1360 max_screen_colors, histogram, 1);
1361 }
1362 else
1363 {
1364 png_color std_color_cube[MAX_SCREEN_COLORS] =
1365 { ... colors ... };
1366
1367 png_set_quantize(png_ptr, std_color_cube,
1368 MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
1369 NULL,0);
1370 }
1371 }
1372
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001373PNG files describe monochrome as black being zero and white being one.
1374The following code will reverse this (make black be one and white be
1375zero):
1376
1377 if (bit_depth == 1 && color_type == PNG_COLOR_TYPE_GRAY)
1378 png_set_invert_mono(png_ptr);
1379
1380This function can also be used to invert grayscale and gray-alpha images:
1381
1382 if (color_type == PNG_COLOR_TYPE_GRAY ||
1383 color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
1384 png_set_invert_mono(png_ptr);
1385
1386PNG files store 16 bit pixels in network byte order (big-endian,
1387ie. most significant bits first). This code changes the storage to the
1388other way (little-endian, i.e. least significant bits first, the
1389way PCs store them):
1390
1391 if (bit_depth == 16)
1392 png_set_swap(png_ptr);
1393
1394If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
1395need to change the order the pixels are packed into bytes, you can use:
1396
1397 if (bit_depth < 8)
1398 png_set_packswap(png_ptr);
1399
1400Finally, you can write your own transformation function if none of
1401the existing ones meets your needs. This is done by setting a callback
1402with
1403
1404 png_set_read_user_transform_fn(png_ptr,
1405 read_transform_fn);
1406
1407You must supply the function
1408
1409 void read_transform_fn(png_ptr ptr, row_info_ptr
1410 row_info, png_bytep data)
1411
1412See pngtest.c for a working example. Your function will be called
1413after all of the other transformations have been processed.
1414
1415You can also set up a pointer to a user structure for use by your
1416callback function, and you can inform libpng that your transform
1417function will change the number of channels or bit depth with the
1418function
1419
1420 png_set_user_transform_info(png_ptr, user_ptr,
1421 user_depth, user_channels);
1422
1423The user's application, not libpng, is responsible for allocating and
1424freeing any memory required for the user structure.
1425
1426You can retrieve the pointer via the function
1427png_get_user_transform_ptr(). For example:
1428
1429 voidp read_user_transform_ptr =
1430 png_get_user_transform_ptr(png_ptr);
1431
1432The last thing to handle is interlacing; this is covered in detail below,
1433but you must call the function here if you want libpng to handle expansion
1434of the interlaced image.
1435
1436 number_of_passes = png_set_interlace_handling(png_ptr);
1437
1438After setting the transformations, libpng can update your png_info
1439structure to reflect any transformations you've requested with this
1440call. This is most useful to update the info structure's rowbytes
1441field so you can use it to allocate your image memory. This function
1442will also update your palette with the correct screen_gamma and
1443background if these have been given with the calls above.
1444
1445 png_read_update_info(png_ptr, info_ptr);
1446
1447After you call png_read_update_info(), you can allocate any
1448memory you need to hold the image. The row data is simply
1449raw byte data for all forms of images. As the actual allocation
1450varies among applications, no example will be given. If you
1451are allocating one large chunk, you will need to build an
1452array of pointers to each row, as it will be needed for some
1453of the functions below.
1454
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06001455Remember: Before you call png_read_update_info the png_get_
1456functions return the values corresponding to the original PNG image.
1457After you call png_read_update_info the values refer to the image
1458that libpng will output. Consequently you must call all the png_set_
1459functions before you call png_read_update_info. This is particularly
1460important for png_set_interlace_handling - if you are going to call
1461png_read_update_info you must call png_set_interlace_handling before
1462it unless you want to receive interlaced output.
1463
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001464Reading image data
1465
1466After you've allocated memory, you can read the image data.
1467The simplest way to do this is in one function call. If you are
1468allocating enough memory to hold the whole image, you can just
1469call png_read_image() and libpng will read in all the image data
1470and put it in the memory area supplied. You will need to pass in
1471an array of pointers to each row.
1472
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06001473This function automatically handles interlacing, so you don't
1474need to call png_set_interlace_handling() (unless you call
1475png_read_update_info()) or call this function multiple times, or any
1476of that other stuff necessary with png_read_rows().
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001477
1478 png_read_image(png_ptr, row_pointers);
1479
1480where row_pointers is:
1481
1482 png_bytep row_pointers[height];
1483
1484You can point to void or char or whatever you use for pixels.
1485
1486If you don't want to read in the whole image at once, you can
1487use png_read_rows() instead. If there is no interlacing (check
1488interlace_type == PNG_INTERLACE_NONE), this is simple:
1489
1490 png_read_rows(png_ptr, row_pointers, NULL,
1491 number_of_rows);
1492
1493where row_pointers is the same as in the png_read_image() call.
1494
1495If you are doing this just one row at a time, you can do this with
1496a single row_pointer instead of an array of row_pointers:
1497
1498 png_bytep row_pointer = row;
1499 png_read_row(png_ptr, row_pointer, NULL);
1500
1501If the file is interlaced (interlace_type != 0 in the IHDR chunk), things
1502get somewhat harder. The only current (PNG Specification version 1.2)
John Bowler660c6e42010-12-19 06:22:23 -06001503interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7);
1504a somewhat complicated 2D interlace scheme, known as Adam7, that
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001505breaks down an image into seven smaller images of varying size, based
John Bowler660c6e42010-12-19 06:22:23 -06001506on an 8x8 grid. This number is defined (from libpng 1.5) as
1507PNG_INTERLACE_ADAM7_PASSES in png.h
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001508
1509libpng can fill out those images or it can give them to you "as is".
John Bowler660c6e42010-12-19 06:22:23 -06001510It is almost always better to have libpng handle the interlacing for you.
1511If you want the images filled out, there are two ways to do that. The one
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001512mentioned in the PNG specification is to expand each pixel to cover
1513those pixels that have not been read yet (the "rectangle" method).
1514This results in a blocky image for the first pass, which gradually
1515smooths out as more pixels are read. The other method is the "sparkle"
1516method, where pixels are drawn only in their final locations, with the
1517rest of the image remaining whatever colors they were initialized to
1518before the start of the read. The first method usually looks better,
1519but tends to be slower, as there are more pixels to put in the rows.
1520
John Bowler660c6e42010-12-19 06:22:23 -06001521If, as is likely, you want libpng to expand the images, call this before
1522calling png_start_read_image() or png_read_update_info():
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001523
1524 if (interlace_type == PNG_INTERLACE_ADAM7)
1525 number_of_passes
1526 = png_set_interlace_handling(png_ptr);
1527
John Bowler660c6e42010-12-19 06:22:23 -06001528This will return the number of passes needed. Currently, this is seven,
1529but may change if another interlace type is added. This function can be
1530called even if the file is not interlaced, where it will return one pass.
1531You then need to read the whole image 'number_of_passes' times. Each time
1532will distribute the pixels from the current pass to the correct place in
1533the output image, so you need to supply the same rows to png_read_rows in
1534each pass.
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -05001535
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001536If you are not going to display the image after each pass, but are
1537going to wait until the entire image is read in, use the sparkle
1538effect. This effect is faster and the end result of either method
1539is exactly the same. If you are planning on displaying the image
1540after each pass, the "rectangle" effect is generally considered the
1541better looking one.
1542
1543If you only want the "sparkle" effect, just call png_read_rows() as
1544normal, with the third parameter NULL. Make sure you make pass over
1545the image number_of_passes times, and you don't change the data in the
1546rows between calls. You can change the locations of the data, just
1547not the data. Each pass only writes the pixels appropriate for that
1548pass, and assumes the data from previous passes is still valid.
1549
1550 png_read_rows(png_ptr, row_pointers, NULL,
1551 number_of_rows);
1552
1553If you only want the first effect (the rectangles), do the same as
1554before except pass the row buffer in the third parameter, and leave
1555the second parameter NULL.
1556
1557 png_read_rows(png_ptr, NULL, row_pointers,
1558 number_of_rows);
1559
John Bowler660c6e42010-12-19 06:22:23 -06001560If you don't want libpng to handle the interlacing details, just call
1561png_read_rows() PNG_INTERLACE_ADAM7_PASSES times to read in all the images.
1562Each of the images is a valid image by itself, however you will almost
1563certainly need to distribute the pixels from each sub-image to the
1564correct place. This is where everything gets very tricky.
1565
1566If you want to retrieve the separate images you must pass the correct
1567number of rows to each successive call of png_read_rows(). The calculation
1568gets pretty complicated for small images, where some sub-images may
1569not even exist because either their width or height ends up zero.
1570libpng provides two macros to help you in 1.5 and later versions:
1571
1572 png_uint_32 width = PNG_PASS_COLS(image_width, pass_number);
1573 png_uint_32 height = PNG_PASS_ROWS(image_height, pass_number);
1574
1575Respectively these tell you the width and height of the sub-image
1576corresponding to the numbered pass. 'pass' is in in the range 0 to 6 -
1577this can be confusing because the specification refers to the same passes
1578as 1 to 7! Be careful, you must check both the width and height before
1579calling png_read_rows() and not call it for that pass if either is zero.
1580
1581You can, of course, read each sub-image row by row. If you want to
1582produce optimal code to make a pixel-by-pixel transformation of an
1583interlaced image this is the best approach; read each row of each pass,
1584transform it, and write it out to a new interlaced image.
1585
1586If you want to de-interlace the image yourself libpng provides further
1587macros to help that tell you where to place the pixels in the output image.
1588Because the interlacing scheme is rectangular - sub-image pixels are always
1589arranged on a rectangular grid - all you need to know for each pass is the
1590starting column and row in the output image of the first pixel plus the
1591spacing between each pixel. As of libpng 1.5 there are four macros to
1592retrieve this information:
1593
1594 png_uint_32 x = PNG_PASS_START_COL(pass);
1595 png_uint_32 y = PNG_PASS_START_ROW(pass);
1596 png_uint_32 xStep = 1U << PNG_PASS_COL_SHIFT(pass);
1597 png_uint_32 yStep = 1U << PNG_PASS_ROW_SHIFT(pass);
1598
1599These allow you to write the obvious loop:
1600
1601 png_uint_32 input_y = 0;
1602 png_uint_32 output_y = PNG_PASS_START_ROW(pass);
1603
1604 while (output_y < output_image_height)
1605 {
1606 png_uint_32 input_x = 0;
1607 png_uint_32 output_x = PNG_PASS_START_COL(pass);
1608
1609 while (output_x < output_image_width)
1610 {
1611 image[output_y][output_x] = subimage[pass][input_y][input_x++];
1612 output_x += xStep;
1613 }
1614
1615 ++input_y;
1616 ouput_y += yStep;
1617 }
1618
1619Notice that the steps between successive output rows and columns are
1620returned as shifts. This is possible because the pixels in the subimages
1621are always a power of 2 apart - 1, 2, 4 or 8 pixels - in the original
1622image. In practice you may need to directly calculate the output coordinate
1623given an input coordinate. libpng provides two further macros for this
1624purpose:
1625
1626 png_uint_32 output_x = PNG_COL_FROM_PASS_COL(input_x, pass);
1627 png_uint_32 output_y = PNG_ROW_FROM_PASS_ROW(input_y, pass);
1628
1629Finally a pair of macros are provided to tell you if a particular image
1630row or column appears in a given pass:
1631
1632 int col_in_pass = PNG_COL_IN_INTERLACE_PASS(output_x, pass);
1633 int row_in_pass = PNG_ROW_IN_INTERLACE_PASS(output_y, pass);
1634
1635Bear in mind that you will probably also need to check the width and height
1636of the pass in addition to the above to be sure the pass even exists!
1637
1638With any luck you are convinced by now that you don't want to do your own
1639interlace handling. In reality normally the only good reason for doing this
1640is if you are processing PNG files on a pixel-by-pixel basis and don't want
1641to load the whole file into memory when it is interlaced.
1642
1643libpng includes a test program, pngvalid, that illustrates reading and
1644writing of interlaced images. If you can't get interlacing to work in your
1645code and don't want to leave it to libpng (the recommended approach) see
1646how pngvalid.c does it.
1647
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001648Finishing a sequential read
1649
1650After you are finished reading the image through the
1651low-level interface, you can finish reading the file. If you are
1652interested in comments or time, which may be stored either before or
1653after the image data, you should pass the separate png_info struct if
1654you want to keep the comments from before and after the image
1655separate. If you are not interested, you can pass NULL.
1656
1657 png_read_end(png_ptr, end_info);
1658
1659When you are done, you can free all memory allocated by libpng like this:
1660
1661 png_destroy_read_struct(&png_ptr, &info_ptr,
1662 &end_info);
1663
1664It is also possible to individually free the info_ptr members that
1665point to libpng-allocated storage with the following function:
1666
1667 png_free_data(png_ptr, info_ptr, mask, seq)
1668 mask - identifies data to be freed, a mask
1669 containing the bitwise OR of one or
1670 more of
1671 PNG_FREE_PLTE, PNG_FREE_TRNS,
1672 PNG_FREE_HIST, PNG_FREE_ICCP,
1673 PNG_FREE_PCAL, PNG_FREE_ROWS,
1674 PNG_FREE_SCAL, PNG_FREE_SPLT,
1675 PNG_FREE_TEXT, PNG_FREE_UNKN,
1676 or simply PNG_FREE_ALL
1677 seq - sequence number of item to be freed
1678 (-1 for all items)
1679
1680This function may be safely called when the relevant storage has
1681already been freed, or has not yet been allocated, or was allocated
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06001682by the user and not by libpng, and will in those cases do nothing.
1683The "seq" parameter is ignored if only one item of the selected data
1684type, such as PLTE, is allowed. If "seq" is not -1, and multiple items
1685are allowed for the data type identified in the mask, such as text or
1686sPLT, only the n'th item in the structure is freed, where n is "seq".
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001687
1688The default behavior is only to free data that was allocated internally
1689by libpng. This can be changed, so that libpng will not free the data,
1690or so that it will free data that was allocated by the user with png_malloc()
1691or png_zalloc() and passed in via a png_set_*() function, with
1692
1693 png_data_freer(png_ptr, info_ptr, freer, mask)
1694 mask - which data elements are affected
1695 same choices as in png_free_data()
1696 freer - one of
1697 PNG_DESTROY_WILL_FREE_DATA
1698 PNG_SET_WILL_FREE_DATA
1699 PNG_USER_WILL_FREE_DATA
1700
1701This function only affects data that has already been allocated.
1702You can call this function after reading the PNG data but before calling
1703any png_set_*() functions, to control whether the user or the png_set_*()
1704function is responsible for freeing any existing data that might be present,
1705and again after the png_set_*() functions to control whether the user
1706or png_destroy_*() is supposed to free the data. When the user assumes
1707responsibility for libpng-allocated data, the application must use
1708png_free() to free it, and when the user transfers responsibility to libpng
1709for data that the user has allocated, the user must have used png_malloc()
1710or png_zalloc() to allocate it.
1711
1712If you allocated your row_pointers in a single block, as suggested above in
1713the description of the high level read interface, you must not transfer
1714responsibility for freeing it to the png_set_rows or png_read_destroy function,
1715because they would also try to free the individual row_pointers[i].
1716
1717If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
1718separately, do not transfer responsibility for freeing text_ptr to libpng,
1719because when libpng fills a png_text structure it combines these members with
1720the key member, and png_free_data() will free only text_ptr.key. Similarly,
1721if you transfer responsibility for free'ing text_ptr from libpng to your
1722application, your application must not separately free those members.
1723
1724The png_free_data() function will turn off the "valid" flag for anything
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06001725it frees. If you need to turn the flag off for a chunk that was freed by
1726your application instead of by libpng, you can use
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001727
1728 png_set_invalid(png_ptr, info_ptr, mask);
1729 mask - identifies the chunks to be made invalid,
1730 containing the bitwise OR of one or
1731 more of
1732 PNG_INFO_gAMA, PNG_INFO_sBIT,
1733 PNG_INFO_cHRM, PNG_INFO_PLTE,
1734 PNG_INFO_tRNS, PNG_INFO_bKGD,
1735 PNG_INFO_hIST, PNG_INFO_pHYs,
1736 PNG_INFO_oFFs, PNG_INFO_tIME,
1737 PNG_INFO_pCAL, PNG_INFO_sRGB,
1738 PNG_INFO_iCCP, PNG_INFO_sPLT,
1739 PNG_INFO_sCAL, PNG_INFO_IDAT
1740
1741For a more compact example of reading a PNG image, see the file example.c.
1742
1743Reading PNG files progressively
1744
1745The progressive reader is slightly different then the non-progressive
1746reader. Instead of calling png_read_info(), png_read_rows(), and
1747png_read_end(), you make one call to png_process_data(), which calls
1748callbacks when it has the info, a row, or the end of the image. You
1749set up these callbacks with png_set_progressive_read_fn(). You don't
1750have to worry about the input/output functions of libpng, as you are
1751giving the library the data directly in png_process_data(). I will
1752assume that you have read the section on reading PNG files above,
1753so I will only highlight the differences (although I will show
1754all of the code).
1755
1756png_structp png_ptr;
1757png_infop info_ptr;
1758
1759 /* An example code fragment of how you would
1760 initialize the progressive reader in your
1761 application. */
1762 int
1763 initialize_png_reader()
1764 {
1765 png_ptr = png_create_read_struct
1766 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1767 user_error_fn, user_warning_fn);
1768 if (!png_ptr)
1769 return (ERROR);
1770 info_ptr = png_create_info_struct(png_ptr);
1771 if (!info_ptr)
1772 {
1773 png_destroy_read_struct(&png_ptr, (png_infopp)NULL,
1774 (png_infopp)NULL);
1775 return (ERROR);
1776 }
1777
1778 if (setjmp(png_jmpbuf(png_ptr)))
1779 {
1780 png_destroy_read_struct(&png_ptr, &info_ptr,
1781 (png_infopp)NULL);
1782 return (ERROR);
1783 }
1784
1785 /* This one's new. You can provide functions
1786 to be called when the header info is valid,
1787 when each row is completed, and when the image
1788 is finished. If you aren't using all functions,
1789 you can specify NULL parameters. Even when all
1790 three functions are NULL, you need to call
1791 png_set_progressive_read_fn(). You can use
1792 any struct as the user_ptr (cast to a void pointer
1793 for the function call), and retrieve the pointer
1794 from inside the callbacks using the function
1795
1796 png_get_progressive_ptr(png_ptr);
1797
1798 which will return a void pointer, which you have
1799 to cast appropriately.
1800 */
1801 png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
1802 info_callback, row_callback, end_callback);
1803
1804 return 0;
1805 }
1806
1807 /* A code fragment that you call as you receive blocks
1808 of data */
1809 int
1810 process_data(png_bytep buffer, png_uint_32 length)
1811 {
1812 if (setjmp(png_jmpbuf(png_ptr)))
1813 {
1814 png_destroy_read_struct(&png_ptr, &info_ptr,
1815 (png_infopp)NULL);
1816 return (ERROR);
1817 }
1818
1819 /* This one's new also. Simply give it a chunk
1820 of data from the file stream (in order, of
1821 course). On machines with segmented memory
1822 models machines, don't give it any more than
1823 64K. The library seems to run fine with sizes
1824 of 4K. Although you can give it much less if
1825 necessary (I assume you can give it chunks of
1826 1 byte, I haven't tried less then 256 bytes
1827 yet). When this function returns, you may
1828 want to display any rows that were generated
1829 in the row callback if you don't already do
1830 so there.
1831 */
1832 png_process_data(png_ptr, info_ptr, buffer, length);
1833 return 0;
1834 }
1835
1836 /* This function is called (as set by
1837 png_set_progressive_read_fn() above) when enough data
1838 has been supplied so all of the header has been
1839 read.
1840 */
1841 void
1842 info_callback(png_structp png_ptr, png_infop info)
1843 {
1844 /* Do any setup here, including setting any of
1845 the transformations mentioned in the Reading
1846 PNG files section. For now, you _must_ call
1847 either png_start_read_image() or
1848 png_read_update_info() after all the
1849 transformations are set (even if you don't set
1850 any). You may start getting rows before
1851 png_process_data() returns, so this is your
1852 last chance to prepare for that.
John Bowler660c6e42010-12-19 06:22:23 -06001853
1854 This is where you turn on interlace handling,
1855 assuming you don't want to do it yourself.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001856 */
1857 }
1858
1859 /* This function is called when each row of image
1860 data is complete */
1861 void
1862 row_callback(png_structp png_ptr, png_bytep new_row,
1863 png_uint_32 row_num, int pass)
1864 {
1865 /* If the image is interlaced, and you turned
1866 on the interlace handler, this function will
1867 be called for every row in every pass. Some
1868 of these rows will not be changed from the
1869 previous pass. When the row is not changed,
1870 the new_row variable will be NULL. The rows
1871 and passes are called in order, so you don't
1872 really need the row_num and pass, but I'm
1873 supplying them because it may make your life
1874 easier.
1875
John Bowler660c6e42010-12-19 06:22:23 -06001876 If you did not turn on interlace handling then
1877 the callback is called for each row of each
1878 sub-image when the image is interlaced. In this
1879 case 'row_num' is the row in the sub-image, not
1880 the row in the output image as it is in all other
1881 cases.
1882
1883 For the non-NULL rows of interlaced images when
1884 you have switched on libpng interlace handling,
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001885 you must call png_progressive_combine_row()
1886 passing in the row and the old row. You can
1887 call this function for NULL rows (it will just
1888 return) and for non-interlaced images (it just
1889 does the memcpy for you) if it will make the
1890 code easier. Thus, you can just do this for
John Bowler660c6e42010-12-19 06:22:23 -06001891 all cases if you switch on interlace handling;
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001892 */
1893
1894 png_progressive_combine_row(png_ptr, old_row,
1895 new_row);
1896
1897 /* where old_row is what was displayed for
1898 previously for the row. Note that the first
1899 pass (pass == 0, really) will completely cover
1900 the old row, so the rows do not have to be
1901 initialized. After the first pass (and only
1902 for interlaced images), you will have to pass
1903 the current row, and the function will combine
1904 the old row and the new row.
1905 */
1906 }
1907
1908 void
1909 end_callback(png_structp png_ptr, png_infop info)
1910 {
1911 /* This function is called after the whole image
1912 has been read, including any chunks after the
1913 image (up to and including the IEND). You
1914 will usually have the same info chunk as you
1915 had in the header, although some data may have
1916 been added to the comments and time fields.
1917
1918 Most people won't do much here, perhaps setting
1919 a flag that marks the image as finished.
1920 */
1921 }
1922
1923
1924
1925IV. Writing
1926
1927Much of this is very similar to reading. However, everything of
1928importance is repeated here, so you won't have to constantly look
1929back up in the reading section to understand writing.
1930
1931Setup
1932
1933You will want to do the I/O initialization before you get into libpng,
1934so if it doesn't work, you don't have anything to undo. If you are not
1935using the standard I/O functions, you will need to replace them with
1936custom writing functions. See the discussion under Customizing libpng.
1937
1938 FILE *fp = fopen(file_name, "wb");
1939 if (!fp)
1940 {
1941 return (ERROR);
1942 }
1943
1944Next, png_struct and png_info need to be allocated and initialized.
1945As these can be both relatively large, you may not want to store these
1946on the stack, unless you have stack space to spare. Of course, you
1947will want to check if they return NULL. If you are also reading,
1948you won't want to name your read structure and your write structure
1949both "png_ptr"; you can call them anything you like, such as
1950"read_ptr" and "write_ptr". Look at pngtest.c, for example.
1951
1952 png_structp png_ptr = png_create_write_struct
1953 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1954 user_error_fn, user_warning_fn);
1955 if (!png_ptr)
1956 return (ERROR);
1957
1958 png_infop info_ptr = png_create_info_struct(png_ptr);
1959 if (!info_ptr)
1960 {
1961 png_destroy_write_struct(&png_ptr,
1962 (png_infopp)NULL);
1963 return (ERROR);
1964 }
1965
1966If you want to use your own memory allocation routines,
1967define PNG_USER_MEM_SUPPORTED and use
1968png_create_write_struct_2() instead of png_create_write_struct():
1969
1970 png_structp png_ptr = png_create_write_struct_2
1971 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1972 user_error_fn, user_warning_fn, (png_voidp)
1973 user_mem_ptr, user_malloc_fn, user_free_fn);
1974
1975After you have these structures, you will need to set up the
1976error handling. When libpng encounters an error, it expects to
1977longjmp() back to your routine. Therefore, you will need to call
1978setjmp() and pass the png_jmpbuf(png_ptr). If you
1979write the file from different routines, you will need to update
1980the png_jmpbuf(png_ptr) every time you enter a new routine that will
1981call a png_*() function. See your documentation of setjmp/longjmp
1982for your compiler for more information on setjmp/longjmp. See
1983the discussion on libpng error handling in the Customizing Libpng
1984section below for more information on the libpng error handling.
1985
1986 if (setjmp(png_jmpbuf(png_ptr)))
1987 {
1988 png_destroy_write_struct(&png_ptr, &info_ptr);
1989 fclose(fp);
1990 return (ERROR);
1991 }
1992 ...
1993 return;
1994
1995If you would rather avoid the complexity of setjmp/longjmp issues,
Glenn Randers-Pehrson54ac9a92010-04-02 17:06:22 -05001996you can compile libpng with PNG_NO_SETJMP, in which case
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05001997errors will result in a call to PNG_ABORT() which defaults to abort().
1998
Glenn Randers-Pehrson54ac9a92010-04-02 17:06:22 -05001999You can #define PNG_ABORT() to a function that does something
2000more useful than abort(), as long as your function does not
2001return.
2002
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002003Now you need to set up the output code. The default for libpng is to
2004use the C function fwrite(). If you use this, you will need to pass a
2005valid FILE * in the function png_init_io(). Be sure that the file is
2006opened in binary mode. Again, if you wish to handle writing data in
2007another way, see the discussion on libpng I/O handling in the Customizing
2008Libpng section below.
2009
2010 png_init_io(png_ptr, fp);
2011
2012If you are embedding your PNG into a datastream such as MNG, and don't
2013want libpng to write the 8-byte signature, or if you have already
2014written the signature in your application, use
2015
2016 png_set_sig_bytes(png_ptr, 8);
2017
2018to inform libpng that it should not write a signature.
2019
2020Write callbacks
2021
2022At this point, you can set up a callback function that will be
2023called after each row has been written, which you can use to control
2024a progress meter or the like. It's demonstrated in pngtest.c.
2025You must supply a function
2026
2027 void write_row_callback(png_ptr, png_uint_32 row,
2028 int pass);
2029 {
2030 /* put your code here */
2031 }
2032
2033(You can give it another name that you like instead of "write_row_callback")
2034
2035To inform libpng about your function, use
2036
2037 png_set_write_status_fn(png_ptr, write_row_callback);
2038
2039You now have the option of modifying how the compression library will
2040run. The following functions are mainly for testing, but may be useful
2041in some cases, like if you need to write PNG files extremely fast and
2042are willing to give up some compression, or if you want to get the
2043maximum possible compression at the expense of slower writing. If you
2044have no special needs in this area, let the library do what it wants by
2045not calling this function at all, as it has been tuned to deliver a good
2046speed/compression ratio. The second parameter to png_set_filter() is
2047the filter method, for which the only valid values are 0 (as of the
2048July 1999 PNG specification, version 1.2) or 64 (if you are writing
2049a PNG datastream that is to be embedded in a MNG datastream). The third
2050parameter is a flag that indicates which filter type(s) are to be tested
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002051for each scanline. See the PNG specification for details on the specific
2052filter types.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002053
2054
2055 /* turn on or off filtering, and/or choose
2056 specific filters. You can use either a single
2057 PNG_FILTER_VALUE_NAME or the bitwise OR of one
2058 or more PNG_FILTER_NAME masks. */
2059 png_set_filter(png_ptr, 0,
2060 PNG_FILTER_NONE | PNG_FILTER_VALUE_NONE |
2061 PNG_FILTER_SUB | PNG_FILTER_VALUE_SUB |
2062 PNG_FILTER_UP | PNG_FILTER_VALUE_UP |
2063 PNG_FILTER_AVG | PNG_FILTER_VALUE_AVG |
2064 PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH|
2065 PNG_ALL_FILTERS);
2066
John Bowler660c6e42010-12-19 06:22:23 -06002067If an application wants to start and stop using particular filters during
2068compression, it should start out with all of the filters (to ensure that
2069the previous row of pixels will be stored in case it's needed later),
2070and then add and remove them after the start of compression.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002071
2072If you are writing a PNG datastream that is to be embedded in a MNG
2073datastream, the second parameter can be either 0 or 64.
2074
2075The png_set_compression_*() functions interface to the zlib compression
2076library, and should mostly be ignored unless you really know what you are
2077doing. The only generally useful call is png_set_compression_level()
2078which changes how much time zlib spends on trying to compress the image
2079data. See the Compression Library (zlib.h and algorithm.txt, distributed
2080with zlib) for details on the compression levels.
2081
2082 /* set the zlib compression level */
2083 png_set_compression_level(png_ptr,
2084 Z_BEST_COMPRESSION);
2085
2086 /* set other zlib parameters */
2087 png_set_compression_mem_level(png_ptr, 8);
2088 png_set_compression_strategy(png_ptr,
2089 Z_DEFAULT_STRATEGY);
2090 png_set_compression_window_bits(png_ptr, 15);
2091 png_set_compression_method(png_ptr, 8);
2092 png_set_compression_buffer_size(png_ptr, 8192)
2093
2094extern PNG_EXPORT(void,png_set_zbuf_size)
2095
2096Setting the contents of info for output
2097
2098You now need to fill in the png_info structure with all the data you
2099wish to write before the actual image. Note that the only thing you
2100are allowed to write after the image is the text chunks and the time
2101chunk (as of PNG Specification 1.2, anyway). See png_write_end() and
2102the latest PNG specification for more information on that. If you
2103wish to write them before the image, fill them in now, and flag that
2104data as being valid. If you want to wait until after the data, don't
2105fill them until png_write_end(). For all the fields in png_info and
2106their data types, see png.h. For explanations of what the fields
2107contain, see the PNG specification.
2108
2109Some of the more important parts of the png_info are:
2110
2111 png_set_IHDR(png_ptr, info_ptr, width, height,
2112 bit_depth, color_type, interlace_type,
2113 compression_type, filter_method)
2114 width - holds the width of the image
2115 in pixels (up to 2^31).
2116 height - holds the height of the image
2117 in pixels (up to 2^31).
2118 bit_depth - holds the bit depth of one of the
2119 image channels.
2120 (valid values are 1, 2, 4, 8, 16
2121 and depend also on the
2122 color_type. See also significant
2123 bits (sBIT) below).
2124 color_type - describes which color/alpha
2125 channels are present.
2126 PNG_COLOR_TYPE_GRAY
2127 (bit depths 1, 2, 4, 8, 16)
2128 PNG_COLOR_TYPE_GRAY_ALPHA
2129 (bit depths 8, 16)
2130 PNG_COLOR_TYPE_PALETTE
2131 (bit depths 1, 2, 4, 8)
2132 PNG_COLOR_TYPE_RGB
2133 (bit_depths 8, 16)
2134 PNG_COLOR_TYPE_RGB_ALPHA
2135 (bit_depths 8, 16)
2136
2137 PNG_COLOR_MASK_PALETTE
2138 PNG_COLOR_MASK_COLOR
2139 PNG_COLOR_MASK_ALPHA
2140
2141 interlace_type - PNG_INTERLACE_NONE or
2142 PNG_INTERLACE_ADAM7
2143 compression_type - (must be
2144 PNG_COMPRESSION_TYPE_DEFAULT)
2145 filter_method - (must be PNG_FILTER_TYPE_DEFAULT
2146 or, if you are writing a PNG to
2147 be embedded in a MNG datastream,
2148 can also be
2149 PNG_INTRAPIXEL_DIFFERENCING)
2150
2151If you call png_set_IHDR(), the call must appear before any of the
Glenn Randers-Pehrsond60c8862009-06-15 21:56:14 -05002152other png_set_*() functions, because they might require access to some of
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002153the IHDR settings. The remaining png_set_*() functions can be called
2154in any order.
2155
Glenn Randers-Pehrson9dcde092009-06-08 08:31:59 -05002156If you wish, you can reset the compression_type, interlace_type, or
2157filter_method later by calling png_set_IHDR() again; if you do this, the
2158width, height, bit_depth, and color_type must be the same in each call.
Glenn Randers-Pehrson37e7e0b2009-06-02 13:46:41 -05002159
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002160 png_set_PLTE(png_ptr, info_ptr, palette,
2161 num_palette);
2162 palette - the palette for the file
2163 (array of png_color)
2164 num_palette - number of entries in the palette
2165
2166 png_set_gAMA(png_ptr, info_ptr, gamma);
2167 gamma - the gamma the image was created
2168 at (PNG_INFO_gAMA)
2169
2170 png_set_sRGB(png_ptr, info_ptr, srgb_intent);
2171 srgb_intent - the rendering intent
2172 (PNG_INFO_sRGB) The presence of
2173 the sRGB chunk means that the pixel
2174 data is in the sRGB color space.
2175 This chunk also implies specific
2176 values of gAMA and cHRM. Rendering
2177 intent is the CSS-1 property that
2178 has been defined by the International
2179 Color Consortium
2180 (http://www.color.org).
2181 It can be one of
2182 PNG_sRGB_INTENT_SATURATION,
2183 PNG_sRGB_INTENT_PERCEPTUAL,
2184 PNG_sRGB_INTENT_ABSOLUTE, or
2185 PNG_sRGB_INTENT_RELATIVE.
2186
2187
2188 png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
2189 srgb_intent);
2190 srgb_intent - the rendering intent
2191 (PNG_INFO_sRGB) The presence of the
2192 sRGB chunk means that the pixel
2193 data is in the sRGB color space.
2194 This function also causes gAMA and
2195 cHRM chunks with the specific values
2196 that are consistent with sRGB to be
2197 written.
2198
2199 png_set_iCCP(png_ptr, info_ptr, name, compression_type,
Glenn Randers-Pehrson4a5a1ec2011-01-15 11:43:28 -06002200 profile, proflen);
2201 name - The profile name.
2202 compression_type - The compression type; always
2203 PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
2204 You may give NULL to this argument to
2205 ignore it.
2206 profile - International Color Consortium color
2207 profile data. May contain NULs.
2208 proflen - length of profile data in bytes.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002209
2210 png_set_sBIT(png_ptr, info_ptr, sig_bit);
2211 sig_bit - the number of significant bits for
2212 (PNG_INFO_sBIT) each of the gray, red,
2213 green, and blue channels, whichever are
2214 appropriate for the given color type
2215 (png_color_16)
2216
Glenn Randers-Pehrson866b62a2009-08-08 16:33:14 -05002217 png_set_tRNS(png_ptr, info_ptr, trans_alpha,
2218 num_trans, trans_color);
Glenn Randers-Pehrson866b62a2009-08-08 16:33:14 -05002219 trans_alpha - array of alpha (transparency)
2220 entries for palette (PNG_INFO_tRNS)
Glenn Randers-Pehrson9dcde092009-06-08 08:31:59 -05002221 trans_color - graylevel or color sample values
2222 (in order red, green, blue) of the
2223 single transparent color for
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002224 non-paletted images (PNG_INFO_tRNS)
2225 num_trans - number of transparent entries
2226 (PNG_INFO_tRNS)
2227
2228 png_set_hIST(png_ptr, info_ptr, hist);
2229 (PNG_INFO_hIST)
2230 hist - histogram of palette (array of
2231 png_uint_16)
2232
2233 png_set_tIME(png_ptr, info_ptr, mod_time);
2234 mod_time - time image was last modified
2235 (PNG_VALID_tIME)
2236
2237 png_set_bKGD(png_ptr, info_ptr, background);
2238 background - background color (PNG_VALID_bKGD)
2239
2240 png_set_text(png_ptr, info_ptr, text_ptr, num_text);
2241 text_ptr - array of png_text holding image
2242 comments
2243 text_ptr[i].compression - type of compression used
2244 on "text" PNG_TEXT_COMPRESSION_NONE
2245 PNG_TEXT_COMPRESSION_zTXt
2246 PNG_ITXT_COMPRESSION_NONE
2247 PNG_ITXT_COMPRESSION_zTXt
2248 text_ptr[i].key - keyword for comment. Must contain
2249 1-79 characters.
2250 text_ptr[i].text - text comments for current
2251 keyword. Can be NULL or empty.
2252 text_ptr[i].text_length - length of text string,
2253 after decompression, 0 for iTXt
2254 text_ptr[i].itxt_length - length of itxt string,
2255 after decompression, 0 for tEXt/zTXt
2256 text_ptr[i].lang - language of comment (NULL or
2257 empty for unknown).
2258 text_ptr[i].translated_keyword - keyword in UTF-8 (NULL
2259 or empty for unknown).
Glenn Randers-Pehrsonef29a5e2009-10-31 19:37:05 -05002260 Note that the itxt_length, lang, and lang_key
2261 members of the text_ptr structure only exist
2262 when the library is built with iTXt chunk support.
2263
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002264 num_text - number of comments
2265
2266 png_set_sPLT(png_ptr, info_ptr, &palette_ptr,
2267 num_spalettes);
2268 palette_ptr - array of png_sPLT_struct structures
2269 to be added to the list of palettes
2270 in the info structure.
2271 num_spalettes - number of palette structures to be
2272 added.
2273
2274 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
2275 unit_type);
2276 offset_x - positive offset from the left
2277 edge of the screen
2278 offset_y - positive offset from the top
2279 edge of the screen
2280 unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
2281
2282 png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
2283 unit_type);
2284 res_x - pixels/unit physical resolution
2285 in x direction
2286 res_y - pixels/unit physical resolution
2287 in y direction
2288 unit_type - PNG_RESOLUTION_UNKNOWN,
2289 PNG_RESOLUTION_METER
2290
2291 png_set_sCAL(png_ptr, info_ptr, unit, width, height)
2292 unit - physical scale units (an integer)
2293 width - width of a pixel in physical scale units
2294 height - height of a pixel in physical scale units
2295 (width and height are doubles)
2296
2297 png_set_sCAL_s(png_ptr, info_ptr, unit, width, height)
2298 unit - physical scale units (an integer)
2299 width - width of a pixel in physical scale units
2300 height - height of a pixel in physical scale units
2301 (width and height are strings like "2.54")
2302
2303 png_set_unknown_chunks(png_ptr, info_ptr, &unknowns,
2304 num_unknowns)
2305 unknowns - array of png_unknown_chunk
2306 structures holding unknown chunks
2307 unknowns[i].name - name of unknown chunk
2308 unknowns[i].data - data of unknown chunk
2309 unknowns[i].size - size of unknown chunk's data
2310 unknowns[i].location - position to write chunk in file
2311 0: do not write chunk
2312 PNG_HAVE_IHDR: before PLTE
2313 PNG_HAVE_PLTE: before IDAT
2314 PNG_AFTER_IDAT: after IDAT
2315
2316The "location" member is set automatically according to
2317what part of the output file has already been written.
2318You can change its value after calling png_set_unknown_chunks()
2319as demonstrated in pngtest.c. Within each of the "locations",
2320the chunks are sequenced according to their position in the
2321structure (that is, the value of "i", which is the order in which
2322the chunk was either read from the input file or defined with
2323png_set_unknown_chunks).
2324
2325A quick word about text and num_text. text is an array of png_text
2326structures. num_text is the number of valid structures in the array.
2327Each png_text structure holds a language code, a keyword, a text value,
2328and a compression type.
2329
2330The compression types have the same valid numbers as the compression
2331types of the image data. Currently, the only valid number is zero.
2332However, you can store text either compressed or uncompressed, unlike
2333images, which always have to be compressed. So if you don't want the
2334text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
2335Because tEXt and zTXt chunks don't have a language field, if you
2336specify PNG_TEXT_COMPRESSION_NONE or PNG_TEXT_COMPRESSION_zTXt
2337any language code or translated keyword will not be written out.
2338
2339Until text gets around 1000 bytes, it is not worth compressing it.
2340After the text has been written out to the file, the compression type
2341is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
2342so that it isn't written out again at the end (in case you are calling
2343png_write_end() with the same struct.
2344
2345The keywords that are given in the PNG Specification are:
2346
2347 Title Short (one line) title or
2348 caption for image
2349 Author Name of image's creator
2350 Description Description of image (possibly long)
2351 Copyright Copyright notice
2352 Creation Time Time of original image creation
2353 (usually RFC 1123 format, see below)
2354 Software Software used to create the image
2355 Disclaimer Legal disclaimer
2356 Warning Warning of nature of content
2357 Source Device used to create the image
2358 Comment Miscellaneous comment; conversion
2359 from other image format
2360
2361The keyword-text pairs work like this. Keywords should be short
2362simple descriptions of what the comment is about. Some typical
2363keywords are found in the PNG specification, as is some recommendations
2364on keywords. You can repeat keywords in a file. You can even write
2365some text before the image and some after. For example, you may want
2366to put a description of the image before the image, but leave the
2367disclaimer until after, so viewers working over modem connections
2368don't have to wait for the disclaimer to go over the modem before
2369they start seeing the image. Finally, keywords should be full
2370words, not abbreviations. Keywords and text are in the ISO 8859-1
2371(Latin-1) character set (a superset of regular ASCII) and can not
2372contain NUL characters, and should not contain control or other
2373unprintable characters. To make the comments widely readable, stick
2374with basic ASCII, and avoid machine specific character set extensions
2375like the IBM-PC character set. The keyword must be present, but
2376you can leave off the text string on non-compressed pairs.
2377Compressed pairs must have a text string, as only the text string
2378is compressed anyway, so the compression would be meaningless.
2379
2380PNG supports modification time via the png_time structure. Two
2381conversion routines are provided, png_convert_from_time_t() for
2382time_t and png_convert_from_struct_tm() for struct tm. The
2383time_t routine uses gmtime(). You don't have to use either of
2384these, but if you wish to fill in the png_time structure directly,
2385you should provide the time in universal time (GMT) if possible
2386instead of your local time. Note that the year number is the full
2387year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and
2388that months start with 1.
2389
2390If you want to store the time of the original image creation, you should
2391use a plain tEXt chunk with the "Creation Time" keyword. This is
2392necessary because the "creation time" of a PNG image is somewhat vague,
2393depending on whether you mean the PNG file, the time the image was
2394created in a non-PNG format, a still photo from which the image was
2395scanned, or possibly the subject matter itself. In order to facilitate
2396machine-readable dates, it is recommended that the "Creation Time"
2397tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"),
2398although this isn't a requirement. Unlike the tIME chunk, the
2399"Creation Time" tEXt chunk is not expected to be automatically changed
2400by the software. To facilitate the use of RFC 1123 dates, a function
2401png_convert_to_rfc1123(png_timep) is provided to convert from PNG
2402time to an RFC 1123 format string.
2403
2404Writing unknown chunks
2405
2406You can use the png_set_unknown_chunks function to queue up chunks
2407for writing. You give it a chunk name, raw data, and a size; that's
2408all there is to it. The chunks will be written by the next following
2409png_write_info_before_PLTE, png_write_info, or png_write_end function.
2410Any chunks previously read into the info structure's unknown-chunk
2411list will also be written out in a sequence that satisfies the PNG
2412specification's ordering rules.
2413
2414The high-level write interface
2415
2416At this point there are two ways to proceed; through the high-level
2417write interface, or through a sequence of low-level write operations.
2418You can use the high-level interface if your image data is present
2419in the info structure. All defined output
2420transformations are permitted, enabled by the following masks.
2421
2422 PNG_TRANSFORM_IDENTITY No transformation
2423 PNG_TRANSFORM_PACKING Pack 1, 2 and 4-bit samples
2424 PNG_TRANSFORM_PACKSWAP Change order of packed
2425 pixels to LSB first
2426 PNG_TRANSFORM_INVERT_MONO Invert monochrome images
2427 PNG_TRANSFORM_SHIFT Normalize pixels to the
2428 sBIT depth
2429 PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
2430 to BGRA
2431 PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
2432 to AG
2433 PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
2434 to transparency
2435 PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
2436 PNG_TRANSFORM_STRIP_FILLER Strip out filler
2437 bytes (deprecated).
2438 PNG_TRANSFORM_STRIP_FILLER_BEFORE Strip out leading
2439 filler bytes
2440 PNG_TRANSFORM_STRIP_FILLER_AFTER Strip out trailing
2441 filler bytes
2442
2443If you have valid image data in the info structure (you can use
2444png_set_rows() to put image data in the info structure), simply do this:
2445
2446 png_write_png(png_ptr, info_ptr, png_transforms, NULL)
2447
2448where png_transforms is an integer containing the bitwise OR of some set of
2449transformation flags. This call is equivalent to png_write_info(),
2450followed the set of transformations indicated by the transform mask,
2451then png_write_image(), and finally png_write_end().
2452
2453(The final parameter of this call is not yet used. Someday it might point
2454to transformation parameters required by some future output transform.)
2455
2456You must use png_transforms and not call any png_set_transform() functions
2457when you use png_write_png().
2458
2459The low-level write interface
2460
2461If you are going the low-level route instead, you are now ready to
2462write all the file information up to the actual image data. You do
2463this with a call to png_write_info().
2464
2465 png_write_info(png_ptr, info_ptr);
2466
2467Note that there is one transformation you may need to do before
2468png_write_info(). In PNG files, the alpha channel in an image is the
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002469level of opacity. If your data is supplied as a level of transparency,
2470you can invert the alpha channel before you write it, so that 0 is
2471fully transparent and 255 (in 8-bit or paletted images) or 65535
2472(in 16-bit images) is fully opaque, with
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002473
2474 png_set_invert_alpha(png_ptr);
2475
2476This must appear before png_write_info() instead of later with the
2477other transformations because in the case of paletted images the tRNS
2478chunk data has to be inverted before the tRNS chunk is written. If
2479your image is not a paletted image, the tRNS data (which in such cases
2480represents a single color to be rendered as transparent) won't need to
2481be changed, and you can safely do this transformation after your
2482png_write_info() call.
2483
2484If you need to write a private chunk that you want to appear before
2485the PLTE chunk when PLTE is present, you can write the PNG info in
2486two steps, and insert code to write your own chunk between them:
2487
2488 png_write_info_before_PLTE(png_ptr, info_ptr);
2489 png_set_unknown_chunks(png_ptr, info_ptr, ...);
2490 png_write_info(png_ptr, info_ptr);
2491
2492After you've written the file information, you can set up the library
2493to handle any special transformations of the image data. The various
2494ways to transform the data will be described in the order that they
2495should occur. This is important, as some of these change the color
2496type and/or bit depth of the data, and some others only work on
2497certain color types and bit depths. Even though each transformation
2498checks to see if it has data that it can do something with, you should
2499make sure to only enable a transformation if it will be valid for the
2500data. For example, don't swap red and blue on grayscale data.
2501
2502PNG files store RGB pixels packed into 3 or 6 bytes. This code tells
2503the library to strip input data that has 4 or 8 bytes per pixel down
2504to 3 or 6 bytes (or strip 2 or 4-byte grayscale+filler data to 1 or 2
2505bytes per pixel).
2506
2507 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
2508
2509where the 0 is unused, and the location is either PNG_FILLER_BEFORE or
2510PNG_FILLER_AFTER, depending upon whether the filler byte in the pixel
2511is stored XRGB or RGBX.
2512
2513PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
2514they can, resulting in, for example, 8 pixels per byte for 1 bit files.
2515If the data is supplied at 1 pixel per byte, use this code, which will
2516correctly pack the pixels into a single byte:
2517
2518 png_set_packing(png_ptr);
2519
2520PNG files reduce possible bit depths to 1, 2, 4, 8, and 16. If your
2521data is of another bit depth, you can write an sBIT chunk into the
2522file so that decoders can recover the original data if desired.
2523
2524 /* Set the true bit depth of the image data */
2525 if (color_type & PNG_COLOR_MASK_COLOR)
2526 {
2527 sig_bit.red = true_bit_depth;
2528 sig_bit.green = true_bit_depth;
2529 sig_bit.blue = true_bit_depth;
2530 }
2531 else
2532 {
2533 sig_bit.gray = true_bit_depth;
2534 }
2535 if (color_type & PNG_COLOR_MASK_ALPHA)
2536 {
2537 sig_bit.alpha = true_bit_depth;
2538 }
2539
2540 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
2541
2542If the data is stored in the row buffer in a bit depth other than
2543one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG),
2544this will scale the values to appear to be the correct bit depth as
2545is required by PNG.
2546
2547 png_set_shift(png_ptr, &sig_bit);
2548
2549PNG files store 16 bit pixels in network byte order (big-endian,
2550ie. most significant bits first). This code would be used if they are
2551supplied the other way (little-endian, i.e. least significant bits
2552first, the way PCs store them):
2553
2554 if (bit_depth > 8)
2555 png_set_swap(png_ptr);
2556
2557If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
2558need to change the order the pixels are packed into bytes, you can use:
2559
2560 if (bit_depth < 8)
2561 png_set_packswap(png_ptr);
2562
2563PNG files store 3 color pixels in red, green, blue order. This code
2564would be used if they are supplied as blue, green, red:
2565
2566 png_set_bgr(png_ptr);
2567
2568PNG files describe monochrome as black being zero and white being
2569one. This code would be used if the pixels are supplied with this reversed
2570(black being one and white being zero):
2571
2572 png_set_invert_mono(png_ptr);
2573
2574Finally, you can write your own transformation function if none of
2575the existing ones meets your needs. This is done by setting a callback
2576with
2577
2578 png_set_write_user_transform_fn(png_ptr,
2579 write_transform_fn);
2580
2581You must supply the function
2582
2583 void write_transform_fn(png_ptr ptr, row_info_ptr
2584 row_info, png_bytep data)
2585
2586See pngtest.c for a working example. Your function will be called
2587before any of the other transformations are processed.
2588
2589You can also set up a pointer to a user structure for use by your
2590callback function.
2591
2592 png_set_user_transform_info(png_ptr, user_ptr, 0, 0);
2593
2594The user_channels and user_depth parameters of this function are ignored
2595when writing; you can set them to zero as shown.
2596
2597You can retrieve the pointer via the function png_get_user_transform_ptr().
2598For example:
2599
2600 voidp write_user_transform_ptr =
2601 png_get_user_transform_ptr(png_ptr);
2602
2603It is possible to have libpng flush any pending output, either manually,
2604or automatically after a certain number of lines have been written. To
2605flush the output stream a single time call:
2606
2607 png_write_flush(png_ptr);
2608
2609and to have libpng flush the output stream periodically after a certain
2610number of scanlines have been written, call:
2611
2612 png_set_flush(png_ptr, nrows);
2613
2614Note that the distance between rows is from the last time png_write_flush()
2615was called, or the first row of the image if it has never been called.
2616So if you write 50 lines, and then png_set_flush 25, it will flush the
2617output on the next scanline, and every 25 lines thereafter, unless
2618png_write_flush() is called before 25 more lines have been written.
2619If nrows is too small (less than about 10 lines for a 640 pixel wide
2620RGB image) the image compression may decrease noticeably (although this
2621may be acceptable for real-time applications). Infrequent flushing will
2622only degrade the compression performance by a few percent over images
2623that do not use flushing.
2624
2625Writing the image data
2626
2627That's it for the transformations. Now you can write the image data.
2628The simplest way to do this is in one function call. If you have the
2629whole image in memory, you can just call png_write_image() and libpng
2630will write the image. You will need to pass in an array of pointers to
2631each row. This function automatically handles interlacing, so you don't
2632need to call png_set_interlace_handling() or call this function multiple
2633times, or any of that other stuff necessary with png_write_rows().
2634
2635 png_write_image(png_ptr, row_pointers);
2636
2637where row_pointers is:
2638
2639 png_byte *row_pointers[height];
2640
2641You can point to void or char or whatever you use for pixels.
2642
2643If you don't want to write the whole image at once, you can
2644use png_write_rows() instead. If the file is not interlaced,
2645this is simple:
2646
2647 png_write_rows(png_ptr, row_pointers,
2648 number_of_rows);
2649
2650row_pointers is the same as in the png_write_image() call.
2651
2652If you are just writing one row at a time, you can do this with
2653a single row_pointer instead of an array of row_pointers:
2654
2655 png_bytep row_pointer = row;
2656
2657 png_write_row(png_ptr, row_pointer);
2658
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002659When the file is interlaced, things can get a good deal more complicated.
2660The only currently (as of the PNG Specification version 1.2, dated July
26611999) defined interlacing scheme for PNG files is the "Adam7" interlace
2662scheme, that breaks down an image into seven smaller images of varying
2663size. libpng will build these images for you, or you can do them
2664yourself. If you want to build them yourself, see the PNG specification
2665for details of which pixels to write when.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002666
2667If you don't want libpng to handle the interlacing details, just
2668use png_set_interlace_handling() and call png_write_rows() the
John Bowler660c6e42010-12-19 06:22:23 -06002669correct number of times to write all the sub-images
2670(png_set_interlace_handling() returns the number of sub-images.)
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002671
2672If you want libpng to build the sub-images, call this before you start
2673writing any rows:
2674
John Bowler660c6e42010-12-19 06:22:23 -06002675 number_of_passes = png_set_interlace_handling(png_ptr);
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002676
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002677This will return the number of passes needed. Currently, this is seven,
2678but may change if another interlace type is added.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002679
2680Then write the complete image number_of_passes times.
2681
John Bowler660c6e42010-12-19 06:22:23 -06002682 png_write_rows(png_ptr, row_pointers, number_of_rows);
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002683
John Bowler660c6e42010-12-19 06:22:23 -06002684Think carefully before you write an interlaced image. Typically code that
2685reads such images reads all the image data into memory, uncompressed, before
2686doing any processing. Only code that can display an image on the fly can
2687take advantage of the interlacing and even then the image has to be exactly
2688the correct size for the output device, because scaling an image requires
2689adjacent pixels and these are not available until all the passes have been
2690read.
2691
2692If you do write an interlaced image you will hardly ever need to handle
2693the interlacing yourself. Call png_set_interlace_handling() and use the
2694approach described above.
2695
2696The only time it is conceivable that you will really need to write an
2697interlaced image pass-by-pass is when you have read one pass by pass and
2698made some pixel-by-pixel transformation to it, as described in the read
2699code above. In this case use the PNG_PASS_ROWS and PNG_PASS_COLS macros
2700to determine the size of each sub-image in turn and simply write the rows
2701you obtained from the read code.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002702
2703Finishing a sequential write
2704
2705After you are finished writing the image, you should finish writing
2706the file. If you are interested in writing comments or time, you should
2707pass an appropriately filled png_info pointer. If you are not interested,
2708you can pass NULL.
2709
2710 png_write_end(png_ptr, info_ptr);
2711
2712When you are done, you can free all memory used by libpng like this:
2713
2714 png_destroy_write_struct(&png_ptr, &info_ptr);
2715
2716It is also possible to individually free the info_ptr members that
2717point to libpng-allocated storage with the following function:
2718
2719 png_free_data(png_ptr, info_ptr, mask, seq)
2720 mask - identifies data to be freed, a mask
2721 containing the bitwise OR of one or
2722 more of
2723 PNG_FREE_PLTE, PNG_FREE_TRNS,
2724 PNG_FREE_HIST, PNG_FREE_ICCP,
2725 PNG_FREE_PCAL, PNG_FREE_ROWS,
2726 PNG_FREE_SCAL, PNG_FREE_SPLT,
2727 PNG_FREE_TEXT, PNG_FREE_UNKN,
2728 or simply PNG_FREE_ALL
2729 seq - sequence number of item to be freed
2730 (-1 for all items)
2731
2732This function may be safely called when the relevant storage has
2733already been freed, or has not yet been allocated, or was allocated
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002734by the user and not by libpng, and will in those cases do nothing.
2735The "seq" parameter is ignored if only one item of the selected data
2736type, such as PLTE, is allowed. If "seq" is not -1, and multiple items
2737are allowed for the data type identified in the mask, such as text or
2738sPLT, only the n'th item in the structure is freed, where n is "seq".
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002739
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002740If you allocated data such as a palette that you passed in to libpng
2741with png_set_*, you must not free it until just before the call to
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002742png_destroy_write_struct().
2743
2744The default behavior is only to free data that was allocated internally
2745by libpng. This can be changed, so that libpng will not free the data,
2746or so that it will free data that was allocated by the user with png_malloc()
2747or png_zalloc() and passed in via a png_set_*() function, with
2748
2749 png_data_freer(png_ptr, info_ptr, freer, mask)
2750 mask - which data elements are affected
2751 same choices as in png_free_data()
2752 freer - one of
2753 PNG_DESTROY_WILL_FREE_DATA
2754 PNG_SET_WILL_FREE_DATA
2755 PNG_USER_WILL_FREE_DATA
2756
2757For example, to transfer responsibility for some data from a read structure
2758to a write structure, you could use
2759
2760 png_data_freer(read_ptr, read_info_ptr,
2761 PNG_USER_WILL_FREE_DATA,
2762 PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
2763 png_data_freer(write_ptr, write_info_ptr,
2764 PNG_DESTROY_WILL_FREE_DATA,
2765 PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
2766
2767thereby briefly reassigning responsibility for freeing to the user but
2768immediately afterwards reassigning it once more to the write_destroy
2769function. Having done this, it would then be safe to destroy the read
2770structure and continue to use the PLTE, tRNS, and hIST data in the write
2771structure.
2772
2773This function only affects data that has already been allocated.
2774You can call this function before calling after the png_set_*() functions
2775to control whether the user or png_destroy_*() is supposed to free the data.
2776When the user assumes responsibility for libpng-allocated data, the
2777application must use
2778png_free() to free it, and when the user transfers responsibility to libpng
2779for data that the user has allocated, the user must have used png_malloc()
2780or png_zalloc() to allocate it.
2781
2782If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
2783separately, do not transfer responsibility for freeing text_ptr to libpng,
2784because when libpng fills a png_text structure it combines these members with
2785the key member, and png_free_data() will free only text_ptr.key. Similarly,
2786if you transfer responsibility for free'ing text_ptr from libpng to your
2787application, your application must not separately free those members.
2788For a more compact example of writing a PNG image, see the file example.c.
2789
2790V. Modifying/Customizing libpng:
2791
2792There are two issues here. The first is changing how libpng does
2793standard things like memory allocation, input/output, and error handling.
2794The second deals with more complicated things like adding new chunks,
2795adding new transformations, and generally changing how libpng works.
2796Both of those are compile-time issues; that is, they are generally
2797determined at the time the code is written, and there is rarely a need
2798to provide the user with a means of changing them.
2799
2800Memory allocation, input/output, and error handling
2801
2802All of the memory allocation, input/output, and error handling in libpng
2803goes through callbacks that are user-settable. The default routines are
2804in pngmem.c, pngrio.c, pngwio.c, and pngerror.c, respectively. To change
2805these functions, call the appropriate png_set_*_fn() function.
2806
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002807Memory allocation is done through the functions png_malloc(), png_calloc(),
2808and png_free(). These currently just call the standard C functions.
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -05002809png_calloc() calls png_malloc() and then clears the newly
2810allocated memory to zero. There is limited support for certain systems
2811with segmented memory architectures and the types of pointers declared by
2812png.h match this; you will have to use appropriate pointers in your
2813application. Since it is
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002814unlikely that the method of handling memory allocation on a platform
2815will change between applications, these functions must be modified in
2816the library at compile time. If you prefer to use a different method
2817of allocating and freeing data, you can use png_create_read_struct_2() or
2818png_create_write_struct_2() to register your own functions as described
2819above. These functions also provide a void pointer that can be retrieved
2820via
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002821
2822 mem_ptr=png_get_mem_ptr(png_ptr);
2823
2824Your replacement memory functions must have prototypes as follows:
2825
2826 png_voidp malloc_fn(png_structp png_ptr,
Glenn Randers-Pehrsone3f3c4e2010-02-07 18:08:50 -06002827 png_alloc_size_t size);
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002828 void free_fn(png_structp png_ptr, png_voidp ptr);
2829
2830Your malloc_fn() must return NULL in case of failure. The png_malloc()
2831function will normally call png_error() if it receives a NULL from the
2832system memory allocator or from your replacement malloc_fn().
2833
2834Your free_fn() will never be called with a NULL ptr, since libpng's
2835png_free() checks for NULL before calling free_fn().
2836
2837Input/Output in libpng is done through png_read() and png_write(),
2838which currently just call fread() and fwrite(). The FILE * is stored in
2839png_struct and is initialized via png_init_io(). If you wish to change
2840the method of I/O, the library supplies callbacks that you can set
2841through the function png_set_read_fn() and png_set_write_fn() at run
2842time, instead of calling the png_init_io() function. These functions
2843also provide a void pointer that can be retrieved via the function
2844png_get_io_ptr(). For example:
2845
2846 png_set_read_fn(png_structp read_ptr,
2847 voidp read_io_ptr, png_rw_ptr read_data_fn)
2848
2849 png_set_write_fn(png_structp write_ptr,
2850 voidp write_io_ptr, png_rw_ptr write_data_fn,
2851 png_flush_ptr output_flush_fn);
2852
2853 voidp read_io_ptr = png_get_io_ptr(read_ptr);
2854 voidp write_io_ptr = png_get_io_ptr(write_ptr);
2855
2856The replacement I/O functions must have prototypes as follows:
2857
2858 void user_read_data(png_structp png_ptr,
2859 png_bytep data, png_size_t length);
2860 void user_write_data(png_structp png_ptr,
2861 png_bytep data, png_size_t length);
2862 void user_flush_data(png_structp png_ptr);
2863
2864The user_read_data() function is responsible for detecting and
2865handling end-of-data errors.
2866
2867Supplying NULL for the read, write, or flush functions sets them back
2868to using the default C stream functions, which expect the io_ptr to
2869point to a standard *FILE structure. It is probably a mistake
2870to use NULL for one of write_data_fn and output_flush_fn but not both
2871of them, unless you have built libpng with PNG_NO_WRITE_FLUSH defined.
2872It is an error to read from a write stream, and vice versa.
2873
2874Error handling in libpng is done through png_error() and png_warning().
2875Errors handled through png_error() are fatal, meaning that png_error()
2876should never return to its caller. Currently, this is handled via
2877setjmp() and longjmp() (unless you have compiled libpng with
Glenn Randers-Pehrson54ac9a92010-04-02 17:06:22 -05002878PNG_NO_SETJMP, in which case it is handled via PNG_ABORT()),
Glenn Randers-Pehrson60988072010-04-13 22:11:06 -05002879but you could change this to do things like exit() if you should wish,
Glenn Randers-Pehrson54ac9a92010-04-02 17:06:22 -05002880as long as your function does not return.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002881
2882On non-fatal errors, png_warning() is called
2883to print a warning message, and then control returns to the calling code.
2884By default png_error() and png_warning() print a message on stderr via
2885fprintf() unless the library is compiled with PNG_NO_CONSOLE_IO defined
2886(because you don't want the messages) or PNG_NO_STDIO defined (because
2887fprintf() isn't available). If you wish to change the behavior of the error
2888functions, you will need to set up your own message callbacks. These
2889functions are normally supplied at the time that the png_struct is created.
2890It is also possible to redirect errors and warnings to your own replacement
2891functions after png_create_*_struct() has been called by calling:
2892
2893 png_set_error_fn(png_structp png_ptr,
2894 png_voidp error_ptr, png_error_ptr error_fn,
2895 png_error_ptr warning_fn);
2896
2897 png_voidp error_ptr = png_get_error_ptr(png_ptr);
2898
2899If NULL is supplied for either error_fn or warning_fn, then the libpng
2900default function will be used, calling fprintf() and/or longjmp() if a
2901problem is encountered. The replacement error functions should have
2902parameters as follows:
2903
2904 void user_error_fn(png_structp png_ptr,
2905 png_const_charp error_msg);
2906 void user_warning_fn(png_structp png_ptr,
2907 png_const_charp warning_msg);
2908
2909The motivation behind using setjmp() and longjmp() is the C++ throw and
2910catch exception handling methods. This makes the code much easier to write,
2911as there is no need to check every return code of every function call.
2912However, there are some uncertainties about the status of local variables
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002913after a longjmp, so the user may want to be careful about doing anything
2914after setjmp returns non-zero besides returning itself. Consult your
2915compiler documentation for more details. For an alternative approach, you
2916may wish to use the "cexcept" facility (see http://cexcept.sourceforge.net).
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002917
2918Custom chunks
2919
2920If you need to read or write custom chunks, you may need to get deeper
2921into the libpng code. The library now has mechanisms for storing
2922and writing chunks of unknown type; you can even declare callbacks
2923for custom chunks. However, this may not be good enough if the
2924library code itself needs to know about interactions between your
2925chunk and existing `intrinsic' chunks.
2926
2927If you need to write a new intrinsic chunk, first read the PNG
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06002928specification. Acquire a first level of understanding of how it works.
2929Pay particular attention to the sections that describe chunk names,
2930and look at how other chunks were designed, so you can do things
2931similarly. Second, check out the sections of libpng that read and
2932write chunks. Try to find a chunk that is similar to yours and use
2933it as a template. More details can be found in the comments inside
2934the code. It is best to handle unknown chunks in a generic method,
2935via callback functions, instead of by modifying libpng functions.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05002936
2937If you wish to write your own transformation for the data, look through
2938the part of the code that does the transformations, and check out some of
2939the simpler ones to get an idea of how they work. Try to find a similar
2940transformation to the one you want to add and copy off of it. More details
2941can be found in the comments inside the code itself.
2942
2943Configuring for 16 bit platforms
2944
2945You will want to look into zconf.h to tell zlib (and thus libpng) that
2946it cannot allocate more then 64K at a time. Even if you can, the memory
2947won't be accessible. So limit zlib and libpng to 64K by defining MAXSEG_64K.
2948
2949Configuring for DOS
2950
2951For DOS users who only have access to the lower 640K, you will
2952have to limit zlib's memory usage via a png_set_compression_mem_level()
2953call. See zlib.h or zconf.h in the zlib library for more information.
2954
2955Configuring for Medium Model
2956
2957Libpng's support for medium model has been tested on most of the popular
2958compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
2959defined, and FAR gets defined to far in pngconf.h, and you should be
2960all set. Everything in the library (except for zlib's structure) is
2961expecting far data. You must use the typedefs with the p or pp on
2962the end for pointers (or at least look at them and be careful). Make
2963note that the rows of data are defined as png_bytepp, which is an
2964unsigned char far * far *.
2965
2966Configuring for gui/windowing platforms:
2967
2968You will need to write new error and warning functions that use the GUI
2969interface, as described previously, and set them to be the error and
2970warning functions at the time that png_create_*_struct() is called,
2971in order to have them available during the structure initialization.
2972They can be changed later via png_set_error_fn(). On some compilers,
2973you may also have to change the memory allocators (png_malloc, etc.).
2974
2975Configuring for compiler xxx:
2976
2977All includes for libpng are in pngconf.h. If you need to add, change
2978or delete an include, this is the place to do it.
2979The includes that are not needed outside libpng are placed in pngpriv.h,
2980which is only used by the routines inside libpng itself.
2981The files in libpng proper only include pngpriv.h and png.h, which
2982in turn includes pngconf.h.
2983
2984Configuring zlib:
2985
2986There are special functions to configure the compression. Perhaps the
2987most useful one changes the compression level, which currently uses
2988input compression values in the range 0 - 9. The library normally
2989uses the default compression level (Z_DEFAULT_COMPRESSION = 6). Tests
2990have shown that for a large majority of images, compression values in
2991the range 3-6 compress nearly as well as higher levels, and do so much
2992faster. For online applications it may be desirable to have maximum speed
2993(Z_BEST_SPEED = 1). With versions of zlib after v0.99, you can also
2994specify no compression (Z_NO_COMPRESSION = 0), but this would create
2995files larger than just storing the raw bitmap. You can specify the
2996compression level by calling:
2997
2998 png_set_compression_level(png_ptr, level);
2999
3000Another useful one is to reduce the memory level used by the library.
3001The memory level defaults to 8, but it can be lowered if you are
3002short on memory (running DOS, for example, where you only have 640K).
3003Note that the memory level does have an effect on compression; among
3004other things, lower levels will result in sections of incompressible
3005data being emitted in smaller stored blocks, with a correspondingly
3006larger relative overhead of up to 15% in the worst case.
3007
3008 png_set_compression_mem_level(png_ptr, level);
3009
3010The other functions are for configuring zlib. They are not recommended
3011for normal use and may result in writing an invalid PNG file. See
3012zlib.h for more information on what these mean.
3013
3014 png_set_compression_strategy(png_ptr,
3015 strategy);
3016 png_set_compression_window_bits(png_ptr,
3017 window_bits);
3018 png_set_compression_method(png_ptr, method);
3019 png_set_compression_buffer_size(png_ptr, size);
3020
3021Controlling row filtering
3022
3023If you want to control whether libpng uses filtering or not, which
3024filters are used, and how it goes about picking row filters, you
3025can call one of these functions. The selection and configuration
3026of row filters can have a significant impact on the size and
3027encoding speed and a somewhat lesser impact on the decoding speed
3028of an image. Filtering is enabled by default for RGB and grayscale
3029images (with and without alpha), but not for paletted images nor
3030for any images with bit depths less than 8 bits/pixel.
3031
3032The 'method' parameter sets the main filtering method, which is
3033currently only '0' in the PNG 1.2 specification. The 'filters'
3034parameter sets which filter(s), if any, should be used for each
3035scanline. Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
3036to turn filtering on and off, respectively.
3037
3038Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
3039PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
3040ORed together with '|' to specify one or more filters to use.
3041These filters are described in more detail in the PNG specification.
3042If you intend to change the filter type during the course of writing
3043the image, you should start with flags set for all of the filters
3044you intend to use so that libpng can initialize its internal
3045structures appropriately for all of the filter types. (Note that this
3046means the first row must always be adaptively filtered, because libpng
3047currently does not allocate the filter buffers until png_write_row()
3048is called for the first time.)
3049
3050 filters = PNG_FILTER_NONE | PNG_FILTER_SUB
3051 PNG_FILTER_UP | PNG_FILTER_AVG |
3052 PNG_FILTER_PAETH | PNG_ALL_FILTERS;
3053
3054 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
3055 filters);
3056 The second parameter can also be
3057 PNG_INTRAPIXEL_DIFFERENCING if you are
3058 writing a PNG to be embedded in a MNG
3059 datastream. This parameter must be the
3060 same as the value of filter_method used
3061 in png_set_IHDR().
3062
3063It is also possible to influence how libpng chooses from among the
3064available filters. This is done in one or both of two ways - by
3065telling it how important it is to keep the same filter for successive
3066rows, and by telling it the relative computational costs of the filters.
3067
3068 double weights[3] = {1.5, 1.3, 1.1},
3069 costs[PNG_FILTER_VALUE_LAST] =
3070 {1.0, 1.3, 1.3, 1.5, 1.7};
3071
3072 png_set_filter_heuristics(png_ptr,
3073 PNG_FILTER_HEURISTIC_WEIGHTED, 3,
3074 weights, costs);
3075
3076The weights are multiplying factors that indicate to libpng that the
3077row filter should be the same for successive rows unless another row filter
3078is that many times better than the previous filter. In the above example,
3079if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
3080"sum of absolute differences" 1.5 x 1.3 times higher than other filters
3081and still be chosen, while the NONE filter could have a sum 1.1 times
3082higher than other filters and still be chosen. Unspecified weights are
3083taken to be 1.0, and the specified weights should probably be declining
3084like those above in order to emphasize recent filters over older filters.
3085
3086The filter costs specify for each filter type a relative decoding cost
3087to be considered when selecting row filters. This means that filters
3088with higher costs are less likely to be chosen over filters with lower
3089costs, unless their "sum of absolute differences" is that much smaller.
3090The costs do not necessarily reflect the exact computational speeds of
3091the various filters, since this would unduly influence the final image
3092size.
3093
3094Note that the numbers above were invented purely for this example and
3095are given only to help explain the function usage. Little testing has
3096been done to find optimum values for either the costs or the weights.
3097
3098Removing unwanted object code
3099
3100There are a bunch of #define's in pngconf.h that control what parts of
3101libpng are compiled. All the defines end in _SUPPORTED. If you are
3102never going to use a capability, you can change the #define to #undef
3103before recompiling libpng and save yourself code and data space, or
3104you can turn off individual capabilities with defines that begin with
3105PNG_NO_.
3106
3107You can also turn all of the transforms and ancillary chunk capabilities
3108off en masse with compiler directives that define
3109PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS,
3110or all four,
3111along with directives to turn on any of the capabilities that you do
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06003112want. The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable the extra
3113transformations but still leave the library fully capable of reading
3114and writing PNG files with all known public chunks. Use of the
3115PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive produces a library
3116that is incapable of reading or writing ancillary chunks. If you are
3117not using the progressive reading capability, you can turn that off
3118with PNG_NO_PROGRESSIVE_READ (don't confuse this with the INTERLACING
3119capability, which you'll still have).
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003120
3121All the reading and writing specific code are in separate files, so the
3122linker should only grab the files it needs. However, if you want to
3123make sure, or if you are building a stand alone library, all the
3124reading files start with pngr and all the writing files start with
3125pngw. The files that don't match either (like png.c, pngtrans.c, etc.)
3126are used for both reading and writing, and always need to be included.
3127The progressive reader is in pngpread.c
3128
3129If you are creating or distributing a dynamically linked library (a .so
3130or DLL file), you should not remove or disable any parts of the library,
3131as this will cause applications linked with different versions of the
3132library to fail if they call functions not available in your library.
3133The size of the library itself should not be an issue, because only
3134those sections that are actually used will be loaded into memory.
3135
3136Requesting debug printout
3137
3138The macro definition PNG_DEBUG can be used to request debugging
3139printout. Set it to an integer value in the range 0 to 3. Higher
3140numbers result in increasing amounts of debugging information. The
3141information is printed to the "stderr" file, unless another file
3142name is specified in the PNG_DEBUG_FILE macro definition.
3143
3144When PNG_DEBUG > 0, the following functions (macros) become available:
3145
3146 png_debug(level, message)
3147 png_debug1(level, message, p1)
3148 png_debug2(level, message, p1, p2)
3149
3150in which "level" is compared to PNG_DEBUG to decide whether to print
3151the message, "message" is the formatted string to be printed,
3152and p1 and p2 are parameters that are to be embedded in the string
3153according to printf-style formatting directives. For example,
3154
3155 png_debug1(2, "foo=%d\n", foo);
3156
3157is expanded to
3158
3159 if(PNG_DEBUG > 2)
3160 fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
3161
3162When PNG_DEBUG is defined but is zero, the macros aren't defined, but you
3163can still use PNG_DEBUG to control your own debugging:
3164
3165 #ifdef PNG_DEBUG
3166 fprintf(stderr, ...
3167 #endif
3168
3169When PNG_DEBUG = 1, the macros are defined, but only png_debug statements
3170having level = 0 will be printed. There aren't any such statements in
3171this version of libpng, but if you insert some they will be printed.
3172
3173VI. MNG support
3174
3175The MNG specification (available at http://www.libpng.org/pub/mng) allows
3176certain extensions to PNG for PNG images that are embedded in MNG datastreams.
3177Libpng can support some of these extensions. To enable them, use the
3178png_permit_mng_features() function:
3179
3180 feature_set = png_permit_mng_features(png_ptr, mask)
3181 mask is a png_uint_32 containing the bitwise OR of the
3182 features you want to enable. These include
3183 PNG_FLAG_MNG_EMPTY_PLTE
3184 PNG_FLAG_MNG_FILTER_64
3185 PNG_ALL_MNG_FEATURES
3186 feature_set is a png_uint_32 that is the bitwise AND of
3187 your mask with the set of MNG features that is
3188 supported by the version of libpng that you are using.
3189
3190It is an error to use this function when reading or writing a standalone
3191PNG file with the PNG 8-byte signature. The PNG datastream must be wrapped
3192in a MNG datastream. As a minimum, it must have the MNG 8-byte signature
3193and the MHDR and MEND chunks. Libpng does not provide support for these
3194or any other MNG chunks; your application must provide its own support for
3195them. You may wish to consider using libmng (available at
3196http://www.libmng.com) instead.
3197
3198VII. Changes to Libpng from version 0.88
3199
3200It should be noted that versions of libpng later than 0.96 are not
3201distributed by the original libpng author, Guy Schalnat, nor by
3202Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
3203distributed versions 0.89 through 0.96, but rather by another member
3204of the original PNG Group, Glenn Randers-Pehrson. Guy and Andreas are
3205still alive and well, but they have moved on to other things.
3206
3207The old libpng functions png_read_init(), png_write_init(),
3208png_info_init(), png_read_destroy(), and png_write_destroy() have been
3209moved to PNG_INTERNAL in version 0.95 to discourage their use. These
3210functions will be removed from libpng version 2.0.0.
3211
3212The preferred method of creating and initializing the libpng structures is
3213via the png_create_read_struct(), png_create_write_struct(), and
3214png_create_info_struct() because they isolate the size of the structures
3215from the application, allow version error checking, and also allow the
3216use of custom error handling routines during the initialization, which
3217the old functions do not. The functions png_read_destroy() and
3218png_write_destroy() do not actually free the memory that libpng
3219allocated for these structs, but just reset the data structures, so they
3220can be used instead of png_destroy_read_struct() and
3221png_destroy_write_struct() if you feel there is too much system overhead
3222allocating and freeing the png_struct for each image read.
3223
3224Setting the error callbacks via png_set_message_fn() before
3225png_read_init() as was suggested in libpng-0.88 is no longer supported
3226because this caused applications that do not use custom error functions
3227to fail if the png_ptr was not initialized to zero. It is still possible
3228to set the error callbacks AFTER png_read_init(), or to change them with
3229png_set_error_fn(), which is essentially the same function, but with a new
3230name to force compilation errors with applications that try to use the old
3231method.
3232
3233Starting with version 1.0.7, you can find out which version of the library
3234you are using at run-time:
3235
3236 png_uint_32 libpng_vn = png_access_version_number();
3237
3238The number libpng_vn is constructed from the major version, minor
3239version with leading zero, and release number with leading zero,
3240(e.g., libpng_vn for version 1.0.7 is 10007).
3241
3242You can also check which version of png.h you used when compiling your
3243application:
3244
3245 png_uint_32 application_vn = PNG_LIBPNG_VER;
3246
3247VIII. Changes to Libpng from version 1.0.x to 1.2.x
3248
3249Support for user memory management was enabled by default. To
3250accomplish this, the functions png_create_read_struct_2(),
3251png_create_write_struct_2(), png_set_mem_fn(), png_get_mem_ptr(),
3252png_malloc_default(), and png_free_default() were added.
3253
Glenn Randers-Pehrsond6ea40a2009-11-02 07:32:00 -06003254Support for the iTXt chunk has been enabled by default as of
3255version 1.2.41.
3256
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003257Support for certain MNG features was enabled.
3258
3259Support for numbered error messages was added. However, we never got
3260around to actually numbering the error messages. The function
3261png_set_strip_error_numbers() was added (Note: the prototype for this
3262function was inadvertently removed from png.h in PNG_NO_ASSEMBLER_CODE
3263builds of libpng-1.2.15. It was restored in libpng-1.2.36).
3264
3265The png_malloc_warn() function was added at libpng-1.2.3. This issues
3266a png_warning and returns NULL instead of aborting when it fails to
3267acquire the requested memory allocation.
3268
3269Support for setting user limits on image width and height was enabled
3270by default. The functions png_set_user_limits(), png_get_user_width_max(),
3271and png_get_user_height_max() were added at libpng-1.2.6.
3272
3273The png_set_add_alpha() function was added at libpng-1.2.7.
3274
3275The function png_set_expand_gray_1_2_4_to_8() was added at libpng-1.2.9.
3276Unlike png_set_gray_1_2_4_to_8(), the new function does not expand the
3277tRNS chunk to alpha. The png_set_gray_1_2_4_to_8() function is
3278deprecated.
3279
3280A number of macro definitions in support of runtime selection of
3281assembler code features (especially Intel MMX code support) were
3282added at libpng-1.2.0:
3283
3284 PNG_ASM_FLAG_MMX_SUPPORT_COMPILED
3285 PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU
3286 PNG_ASM_FLAG_MMX_READ_COMBINE_ROW
3287 PNG_ASM_FLAG_MMX_READ_INTERLACE
3288 PNG_ASM_FLAG_MMX_READ_FILTER_SUB
3289 PNG_ASM_FLAG_MMX_READ_FILTER_UP
3290 PNG_ASM_FLAG_MMX_READ_FILTER_AVG
3291 PNG_ASM_FLAG_MMX_READ_FILTER_PAETH
3292 PNG_ASM_FLAGS_INITIALIZED
3293 PNG_MMX_READ_FLAGS
3294 PNG_MMX_FLAGS
3295 PNG_MMX_WRITE_FLAGS
3296 PNG_MMX_FLAGS
3297
3298We added the following functions in support of runtime
3299selection of assembler code features:
3300
3301 png_get_mmx_flagmask()
3302 png_set_mmx_thresholds()
3303 png_get_asm_flags()
3304 png_get_mmx_bitdepth_threshold()
3305 png_get_mmx_rowbytes_threshold()
3306 png_set_asm_flags()
3307
3308We replaced all of these functions with simple stubs in libpng-1.2.20,
3309when the Intel assembler code was removed due to a licensing issue.
3310
Glenn Randers-Pehrson3d893a02009-08-31 13:32:46 -05003311These macros are deprecated:
3312
3313 PNG_READ_TRANSFORMS_NOT_SUPPORTED
3314 PNG_PROGRESSIVE_READ_NOT_SUPPORTED
3315 PNG_NO_SEQUENTIAL_READ_SUPPORTED
3316 PNG_WRITE_TRANSFORMS_NOT_SUPPORTED
3317 PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED
3318 PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED
3319
3320They have been replaced, respectively, by:
3321
3322 PNG_NO_READ_TRANSFORMS
3323 PNG_NO_PROGRESSIVE_READ
3324 PNG_NO_SEQUENTIAL_READ
3325 PNG_NO_WRITE_TRANSFORMS
3326 PNG_NO_READ_ANCILLARY_CHUNKS
3327 PNG_NO_WRITE_ANCILLARY_CHUNKS
3328
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003329PNG_MAX_UINT was replaced with PNG_UINT_31_MAX. It has been
3330deprecated since libpng-1.0.16 and libpng-1.2.6.
3331
3332The function
3333 png_check_sig(sig, num)
3334was replaced with
3335 !png_sig_cmp(sig, 0, num)
3336It has been deprecated since libpng-0.90.
3337
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003338The function
3339 png_set_gray_1_2_4_to_8()
3340which also expands tRNS to alpha was replaced with
3341 png_set_expand_gray_1_2_4_to_8()
3342which does not. It has been deprecated since libpng-1.0.18 and 1.2.9.
Glenn Randers-Pehrsone3f3c4e2010-02-07 18:08:50 -06003343
Glenn Randers-Pehrsond740c842009-11-04 19:01:54 -06003344IX. Changes to Libpng from version 1.0.x/1.2.x to 1.4.x
3345
3346Private libpng prototypes and macro definitions were moved from
3347png.h and pngconf.h into a new pngpriv.h header file.
3348
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003349Functions png_set_benign_errors(), png_benign_error(), and
3350png_chunk_benign_error() were added.
3351
3352Support for setting the maximum amount of memory that the application
3353will allocate for reading chunks was added, as a security measure.
3354The functions png_set_chunk_cache_max() and png_get_chunk_cache_max()
3355were added to the library.
3356
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06003357We implemented support for I/O states by adding png_ptr member io_state
3358and functions png_get_io_chunk_name() and png_get_io_state() in pngget.c
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003359
Glenn Randers-Pehrson4f25bf32009-10-29 23:34:44 -05003360We added PNG_TRANSFORM_GRAY_TO_RGB to the available high-level
3361input transforms.
3362
Glenn Randers-Pehrson4f25bf32009-10-29 23:34:44 -05003363Checking for and reporting of errors in the IHDR chunk is more thorough.
3364
Glenn Randers-Pehrson45af8192009-12-30 08:37:29 -06003365Support for global arrays was removed, to improve thread safety.
3366
3367Some obsolete/deprecated macros and functions have been removed.
3368
3369Typecasted NULL definitions such as
3370 #define png_voidp_NULL (png_voidp)NULL
3371were eliminated. If you used these in your application, just use
3372NULL instead.
3373
3374The png_struct and info_struct members "trans" and "trans_values" were
3375changed to "trans_alpha" and "trans_color", respectively.
3376
3377The obsolete, unused pnggccrd.c and pngvcrd.c files and related makefiles
Glenn Randers-Pehrsone3f3c4e2010-02-07 18:08:50 -06003378were removed.
Glenn Randers-Pehrson45af8192009-12-30 08:37:29 -06003379
3380The PNG_1_0_X and PNG_1_2_X macros were eliminated.
3381
Glenn Randers-Pehrson4f25bf32009-10-29 23:34:44 -05003382The PNG_LEGACY_SUPPORTED macro was eliminated.
3383
3384Many WIN32_WCE #ifdefs were removed.
3385
3386The functions png_read_init(info_ptr), png_write_init(info_ptr),
3387png_info_init(info_ptr), png_read_destroy(), and png_write_destroy()
3388have been removed. They have been deprecated since libpng-0.95.
3389
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003390The png_permit_empty_plte() was removed. It has been deprecated
3391since libpng-1.0.9. Use png_permit_mng_features() instead.
3392
3393We removed the obsolete stub functions png_get_mmx_flagmask(),
3394png_set_mmx_thresholds(), png_get_asm_flags(),
3395png_get_mmx_bitdepth_threshold(), png_get_mmx_rowbytes_threshold(),
3396png_set_asm_flags(), and png_mmx_supported()
3397
Glenn Randers-Pehrson45af8192009-12-30 08:37:29 -06003398We removed the obsolete png_check_sig(), png_memcpy_check(), and
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -05003399png_memset_check() functions. Instead use !png_sig_cmp(), memcpy(),
3400and memset(), respectively.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003401
Glenn Randers-Pehrsone3f3c4e2010-02-07 18:08:50 -06003402The function png_set_gray_1_2_4_to_8() was removed. It has been
3403deprecated since libpng-1.0.18 and 1.2.9, when it was replaced with
3404png_set_expand_gray_1_2_4_to_8() because the former function also
3405expanded palette images.
3406
Glenn Randers-Pehrson5b40b012010-11-25 07:16:29 -06003407Macros for png_get_uint_16, png_get_uint_32, and png_get_int_32
3408were added and are used by default instead of the corresponding
3409functions. Unfortunately,
3410from libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
3411function) incorrectly returned a value of type png_uint_32.
3412
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003413We changed the prototype for png_malloc() from
3414 png_malloc(png_structp png_ptr, png_uint_32 size)
3415to
3416 png_malloc(png_structp png_ptr, png_alloc_size_t size)
3417
Glenn Randers-Pehrsone3f3c4e2010-02-07 18:08:50 -06003418This also applies to the prototype for the user replacement malloc_fn().
3419
Glenn Randers-Pehrson45af8192009-12-30 08:37:29 -06003420The png_calloc() function was added and is used in place of
Glenn Randers-Pehrson2be8b642010-07-29 19:09:18 -05003421of "png_malloc(); memset();" except in the case in png_read_png()
Glenn Randers-Pehrson45af8192009-12-30 08:37:29 -06003422where the array consists of pointers; in this case a "for" loop is used
3423after the png_malloc() to set the pointers to NULL, to give robust.
3424behavior in case the application runs out of memory part-way through
3425the process.
3426
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003427We changed the prototypes of png_get_compression_buffer_size() and
3428png_set_compression_buffer_size() to work with png_size_t instead of
3429png_uint_32.
3430
Glenn Randers-Pehrson45af8192009-12-30 08:37:29 -06003431Support for numbered error messages was removed by default, since we
3432never got around to actually numbering the error messages. The function
3433png_set_strip_error_numbers() was removed from the library by default.
3434
3435The png_zalloc() and png_zfree() functions are no longer exported.
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003436The png_zalloc() function no longer zeroes out the memory that it
3437allocates.
3438
Glenn Randers-Pehrson3cd7cff2010-04-16 19:27:08 -05003439Support for dithering was disabled by default in libpng-1.4.0, because
3440been well tested and doesn't actually "dither". The code was not
3441removed, however, and could be enabled by building libpng with
3442PNG_READ_DITHER_SUPPORTED defined. In libpng-1.4.2, this support
3443was reenabled, but the function was renamed png_set_quantize() to
3444reflect more accurately what it actually does. At the same time,
3445the PNG_DITHER_[RED,GREEN_BLUE]_BITS macros were also renamed to
3446PNG_QUANTIZE_[RED,GREEN,BLUE]_BITS.
Glenn Randers-Pehrson60988072010-04-13 22:11:06 -05003447
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003448We removed the trailing '.' from the warning and error messages.
3449
Glenn Randers-Pehrson5b40b012010-11-25 07:16:29 -06003450X. Changes to Libpng from version 1.4.x to 1.5.x
3451
3452From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
3453function) incorrectly returned a value of type png_uint_32.
3454
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06003455A. Changes that affect users of libpng
3456
3457There are no substantial API changes between the non-deprecated parts of
3458the 1.4.5 API and the 1.5.0 API, however the ability to directly access
3459the main libpng control structures, png_struct and png_info, deprecated
3460in earlier versions of libpng, has been completely removed from
3461libpng 1.5.
3462
Glenn Randers-Pehrson9d23b402011-01-08 10:42:01 -06003463In png_get_iCCP, the type of "profile" was changed from png_charpp
Glenn Randers-Pehrson4a5a1ec2011-01-15 11:43:28 -06003464to png_bytepp, and in png_set_iCCP, from png_charp to png_const_bytepp.
Glenn Randers-Pehrson9d23b402011-01-08 10:42:01 -06003465
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06003466There are changes of form in png.h, including new and changed macros to
3467declare
Glenn Randers-Pehrsonf5ea1b72011-01-06 06:42:51 -06003468parts of the API. Some API functions with arguments that are pointers to
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06003469data not modified within the function have been corrected to declare
3470these arguments with PNG_CONST.
3471
3472Much of the internal use of C macros to control the library build has also
3473changed and some of this is visible in the exported header files, in
3474particular the use of macros to control data and API elements visible
3475during application compilation may require significant revision to
3476application code. (It is extremely rare for an application to do this.)
3477
3478Any program that compiled against libpng 1.4 and did not use deprecated
3479features or access internal library structures should compile and work
3480against libpng 1.5.
3481
John Bowler660c6e42010-12-19 06:22:23 -06003482libpng 1.5.0 adds PNG_ PASS macros to help in the reading and writing of
3483interlaced images. The macros return the number of rows and columns in
3484each pass and information that can be used to de-interlace and (if
3485absolutely necessary) interlace an image.
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06003486
3487libpng 1.5.0 adds an API png_longjmp(png_ptr, value). This API calls
3488the application provided png_longjmp_ptr on the internal, but application
3489initialized, jmpbuf. It is provided as a convenience to avoid the need
3490to use the png_jmpbuf macro, which had the unnecessary side effect of
3491resetting the internal png_longjmp_ptr value.
3492
3493libpng 1.5.0 includes a complete fixed point API. By default this is
3494present along with the corresponding floating point API. In general the
3495fixed point API is faster and smaller than the floating point one because
3496the PNG file format used fixed point, not floating point. This applies
3497even if the library uses floating point in internal calculations. A new
3498macro, PNG_FLOATING_ARITHMETIC_SUPPORTED, reveals whether the library
3499uses floating point arithmetic (the default) or fixed point arithmetic
3500internally for performance critical calculations such as gamma correction.
3501
3502Fixed point support for the sCAL chunk comes with an important caveat;
3503the sCAL specification uses a decimal encoding of floating point values
3504and the accuracy of PNG fixed point values is insufficient for
3505representation of these values. Consequently a "string" API
3506(png_get_sCAL_s and png_set_sCAL_s) is the only reliable way of reading
3507arbitrary sCAL chunks in the absence of either the floating point API or
3508internal floating point calculations.
3509
3510Applications no longer need to include the optional distribution header
3511file pngusr.h or define the corresponding macros during application
3512build in order to see the correct variant of the libpng API. From 1.5.0
3513application code can check for the corresponding _SUPPORTED macro:
3514
3515#ifdef PNG_INCH_CONVERSIONS_SUPPORTED
3516 /* code that uses the inch conversion APIs. */
3517#endif
3518
3519This macro will only be defined if the inch conversion functions have been
3520compiled into libpng. The full set of macros, and whether or not support
3521has been compiled in, are available in the header file pnglibconf.h.
3522This header file is specific to the libpng build. Notice that prior to
35231.5.0 the _SUPPORTED macros would always have the default definition unless
3524reset by pngusr.h or by explicit settings on the compiler command line.
3525These settings may produce compiler warnings or errors in 1.5.0 because
3526of macro redefinition.
3527
3528From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
3529function) incorrectly returned a value of type png_uint_32. libpng 1.5.0
3530is consistent with the implementation in 1.4.5 and 1.2.x (where the macro
3531did not exist.)
3532
3533Applications can now choose whether to use these macros or to call the
3534corresponding function by defining PNG_USE_READ_MACROS or
3535PNG_NO_USE_READ_MACROS before including png.h. Notice that this is
3536only supported from 1.5.0 -defining PNG_NO_USE_READ_MACROS prior to 1.5.0
3537 will lead to a link failure.
Glenn Randers-Pehrson59fa3e92011-01-06 07:07:06 -06003538
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06003539B. Changes to the build and configuration of libpng
3540
3541Details of internal changes to the library code can be found in the CHANGES
3542file. These will be of no concern to the vast majority of library users or
3543builders, however the few who configure libpng to a non-default feature
3544set may need to change how this is done.
3545
3546There should be no need for library builders to alter build scripts if
3547these use the distributed build support - configure or the makefiles -
3548however users of the makefiles may care to update their build scripts
3549to build pnglibconf.h where the corresponding makefile does not do so.
3550
3551Building libpng with a non-default configuration has changed completely.
3552The old method using pngusr.h should still work correctly even though the
3553way pngusr.h is used in the build has been changed, however library
3554builders will probably want to examine the changes to take advantage of
3555new capabilities and to simplify their build system.
3556
3557B.1 Specific changes to library configuration capabilities
3558
3559The library now supports a complete fixed point implementation and can
3560thus be used on systems which have no floating point support or very
3561limited or slow support. Previously gamma correction, an essential part
3562of complete PNG support, required reasonably fast floating point.
3563
3564As part of this the choice of internal implementation has been made
3565independent of the choice of fixed versus floating point APIs and all the
3566missing fixed point APIs have been implemented.
3567
3568The exact mechanism used to control attributes of API functions has
3569changed. A single set of operating system independent macro definitions
3570is used and operating system specific directives are defined in
3571pnglibconf.h
3572
3573As part of this the mechanism used to chose procedure call standards on those
3574systems that allow a choice has been changed. At present this only
3575affects certain Microsoft (DOS, Windows) and IBM (OS/2) operating systems
3576running on Intel processors. As before PNGAPI is defined where required
3577to control the exported API functions; however, two new macros, PNGCBAPI
3578and PNGCAPI, are used instead for callback functions (PNGCBAPI) and
3579(PNGCAPI) for functions that must match a C library prototype (currently
3580only png_longjmp_ptr, which must match the C longjmp function.) The new
3581approach is documented in pngconf.h
3582
3583Despite these changes libpng 1.5.0 only supports the native C function
3584calling standard on those platforms tested so far (__cdecl on Microsoft
3585Windows). This is because the support requirements for alternative
3586calling conventions seem to no longer exist. Developers who find it
3587necessary to set PNG_API_RULE to 1 should advise the mailing list
3588(png-mng-implement) of this and library builders who use Openwatcom and
3589therefore set PNG_API_RULE to 2 should also contact the mailing list.
3590
3591A new test program, pngvalid, is provided in addition to pngtest.
3592 pngvalid validates the arithmetic accuracy of the gamma correction
3593calculations and includes a number of validations of the file format.
3594A subset of the full range of tests is run when "make check" is done
3595(in the 'configure' build.) pngvalid also allows total allocated memory
3596usage to be evaluated and performs additional memory overwrite validation.
3597
3598Many changes to individual feature macros have been made. The following
3599are the changes most likely to be noticed by library builders who
3600configure libpng:
3601
36021) All feature macros now have consistent naming:
3603
3604#define PNG_NO_feature turns the feature off
3605#define PNG_feature_SUPPORTED turns the feature on
3606
3607pnglibconf.h contains one line for each feature macro which is either:
3608
3609#define PNG_feature_SUPPORTED
3610
3611if the feature is supported or:
3612
3613/*#undef PNG_feature_SUPPORTED*/
3614
3615if it is not. Library code consistently checks for the 'SUPPORTED' macro.
3616It does not, and should not, check for the 'NO' macro which will not
3617normally be defined even if the feature is not supported.
3618
3619Compatibility with the old names is provided as follows:
3620
3621PNG_INCH_CONVERSIONS turns on PNG_INCH_CONVERSIONS_SUPPORTED
3622
3623And the following definitions disable the corresponding feature:
3624
3625PNG_SETJMP_NOT_SUPPORTED disables SETJMP
3626PNG_READ_TRANSFORMS_NOT_SUPPORTED disables READ_TRANSFORMS
3627PNG_NO_READ_COMPOSITED_NODIV disables READ_COMPOSITE_NODIV
3628PNG_WRITE_TRANSFORMS_NOT_SUPPORTED disables WRITE_TRANSFORMS
3629PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED disables READ_ANCILLARY_CHUNKS
3630PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED disables WRITE_ANCILLARY_CHUNKS
3631
3632Library builders should remove use of the above, inconsistent, names.
3633
36342) Warning and error message formatting was previously conditional on
3635the STDIO feature. The library has been changed to use the
3636CONSOLE_IO feature instead. This means that if CONSOLE_IO is disabled
3637the library no longer uses the printf(3) functions, even though the
3638default read/write implementations use (FILE) style stdio.h functions.
3639
36403) Three feature macros now control the fixed/floating point decisions:
3641
3642PNG_FLOATING_POINT_SUPPORTED enables the floating point APIs
3643
3644PNG_FIXED_POINT_SUPPORTED enables the fixed point APIs; however, in
3645practice these are normally required internally anyway (because the PNG
3646file format is fixed point), therefore in most cases PNG_NO_FIXED_POINT
3647merely stops the function from being exported.
3648
3649PNG_FLOATING_ARITHMETIC_SUPPORTED chooses between the internal floating
3650point implementation or the fixed point one. Typically the fixed point
3651implementation is larger and slower than the floating point implementation
3652on a system that supports floating point, however it may be faster on a
3653system which lacks floating point hardware and therefore uses a software
3654emulation.
3655
36564) Added PNG_{READ,WRITE}_INT_FUNCTIONS_SUPPORTED. This allows the
3657functions to read and write ints to be disabled independently of
3658PNG_USE_READ_MACROS, which allows libpng to be built with the functions
3659even though the default is to use the macros - this allows applications
3660to choose at app buildtime whether or not to use macros (previously
3661impossible because the functions weren't in the default build.)
3662
3663B.2 Changes to the configuration mechanism
3664
3665Prior to libpng-1.5.0 library builders who needed to configure libpng
3666had either to modify the exported pngconf.h header file to add system
3667specific configuration or had to write feature selection macros into
3668pngusr.h and cause this to be included into pngconf.h by defining
3669PNG_USER_CONFIG. The latter mechanism had the disadvantage that an
3670application built without PNG_USER_CONFIG defined would see the
3671unmodified, default, libpng API and thus would probably fail to link.
3672
3673These mechanisms still work in the configure build and in any makefile
3674build that builds pnglibconf.h although the feature selection macros
3675have changed somewhat as described above. In 1.5.0, however, pngusr.h
3676is processed once when the exported header file pnglibconf.h is built.
3677pngconf.h no longer includes pngusr.h, therefore it is ignored after the
3678build of pnglibconf.h and it is never included in an application build.
3679
3680The rarely used alternative of adding a list of feature macros to the
3681CFLAGS setting in the build also still works, however the macros will be
3682copied to pnglibconf.h and this may produce macro redefinition warnings
3683when the individual C files are compiled.
3684
3685All configuration now only works if pnglibconf.h is built from
3686scripts/pnglibconf.dfa. This requires the program awk. Brian Kernighan
3687(the original author of awk) maintains C source code of that awk and this
3688and all known later implementations (often called by subtly different
3689names - nawk and gawk for example) are adequate to build pnglibconf.h.
3690The Sun Microsystems (now Oracle) program 'awk' is an earlier version
3691and does not work, this may also apply to other systems that have a
3692functioning awk called 'nawk'.
3693
3694Configuration options are now documented in scripts/pnglibconf.dfa. This
3695file also includes dependency information that ensures a configuration is
3696consistent; that is, if a feature is switched off dependent features are
3697also removed. As a recommended alternative to using feature macros in
3698pngusr.h a system builder may also define equivalent options in pngusr.dfa
3699(or, indeed, any file) and add that to the configuration by setting
3700DFA_XTRA to the file name. The makefiles in contrib/pngminim illustrate
3701how to do this, and a case where pngusr.h is still required.
3702
Glenn Randers-Pehrson5b40b012010-11-25 07:16:29 -06003703XI. Detecting libpng
Glenn Randers-Pehrson37e7e0b2009-06-02 13:46:41 -05003704
3705The png_get_io_ptr() function has been present since libpng-0.88, has never
3706changed, and is unaffected by conditional compilation macros. It is the
3707best choice for use in configure scripts for detecting the presence of any
Glenn Randers-Pehrson99708d52009-06-29 17:30:00 -05003708libpng version since 0.88. In an autoconf "configure.in" you could use
3709
3710 AC_CHECK_LIB(png, png_get_io_ptr, ...
Glenn Randers-Pehrson37e7e0b2009-06-02 13:46:41 -05003711
Glenn Randers-Pehrson5b40b012010-11-25 07:16:29 -06003712XII. Source code repository
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003713
3714Since about February 2009, version 1.2.34, libpng has been under "git" source
3715control. The git repository was built from old libpng-x.y.z.tar.gz files
3716going back to version 0.70. You can access the git repository (read only)
3717at
3718
3719 git://libpng.git.sourceforge.net/gitroot/libpng
3720
3721or you can browse it via "gitweb" at
3722
3723 http://libpng.git.sourceforge.net/git/gitweb.cgi?p=libpng
3724
3725Patches can be sent to glennrp at users.sourceforge.net or to
3726png-mng-implement at lists.sourceforge.net or you can upload them to
3727the libpng bug tracker at
3728
3729 http://libpng.sourceforge.net
3730
Glenn Randers-Pehrson5b40b012010-11-25 07:16:29 -06003731XIII. Coding style
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003732
3733Our coding style is similar to the "Allman" style, with curly
3734braces on separate lines:
3735
3736 if (condition)
3737 {
3738 action;
3739 }
3740
3741 else if (another condition)
3742 {
3743 another action;
3744 }
3745
3746The braces can be omitted from simple one-line actions:
3747
3748 if (condition)
3749 return (0);
3750
3751We use 3-space indentation, except for continued statements which
3752are usually indented the same as the first line of the statement
3753plus four more spaces.
3754
Glenn Randers-Pehrson6076da82009-09-30 12:28:07 -05003755For macro definitions we use 2-space indentation, always leaving the "#"
3756in the first column.
3757
3758 #ifndef PNG_NO_FEATURE
3759 # ifndef PNG_FEATURE_SUPPORTED
3760 # define PNG_FEATURE_SUPPORTED
3761 # endif
3762 #endif
3763
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003764Comments appear with the leading "/*" at the same indentation as
3765the statement that follows the comment:
3766
3767 /* Single-line comment */
3768 statement;
3769
Glenn Randers-Pehrsone4c706a2010-03-06 14:51:54 -06003770 /* This is a multiple-line
3771 * comment.
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003772 */
3773 statement;
3774
Glenn Randers-Pehrsone4c706a2010-03-06 14:51:54 -06003775Very short comments can be placed after the end of the statement
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003776to which they pertain:
3777
3778 statement; /* comment */
3779
3780We don't use C++ style ("//") comments. We have, however,
3781used them in the past in some now-abandoned MMX assembler
3782code.
3783
Glenn Randers-Pehrson9dcde092009-06-08 08:31:59 -05003784Functions and their curly braces are not indented, and
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003785exported functions are marked with PNGAPI:
3786
3787 /* This is a public function that is visible to
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06003788 * application programmers. It does thus-and-so.
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003789 */
3790 void PNGAPI
3791 png_exported_function(png_ptr, png_info, foo)
3792 {
3793 body;
3794 }
3795
Glenn Randers-Pehrson416976f2009-07-27 22:16:09 -05003796The prototypes for all exported functions appear in png.h,
3797above the comment that says
3798
3799 /* Maintainer: Put new public prototypes here ... */
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003800
3801We mark all non-exported functions with "/* PRIVATE */"":
3802
3803 void /* PRIVATE */
3804 png_non_exported_function(png_ptr, png_info, foo)
3805 {
3806 body;
3807 }
3808
Glenn Randers-Pehrson416976f2009-07-27 22:16:09 -05003809The prototypes for non-exported functions (except for those in
Glenn Randers-Pehrson4f25bf32009-10-29 23:34:44 -05003810pngtest) appear in
3811pngpriv.h
Glenn Randers-Pehrson416976f2009-07-27 22:16:09 -05003812above the comment that says
3813
3814 /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003815
3816The names of all exported functions and variables begin
3817with "png_", and all publicly visible C preprocessor
3818macros begin with "PNG_".
3819
3820We put a space after each comma and after each semicolon
Glenn Randers-Pehrson49a56e72010-12-06 20:06:01 -06003821in "for" statements, and we put spaces before and after each
Glenn Randers-Pehrsone4c706a2010-03-06 14:51:54 -06003822C binary operator and after "for" or "while", and before
3823"?". We don't put a space between a typecast and the expression
3824being cast, nor do we put one between a function name and the
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003825left parenthesis that follows it:
3826
3827 for (i = 2; i > 0; --i)
Glenn Randers-Pehrson4e6b5e92009-09-23 10:24:53 -05003828 y[i] = a(x) + (int)b;
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003829
Glenn Randers-Pehrsond60c8862009-06-15 21:56:14 -05003830We prefer #ifdef and #ifndef to #if defined() and if !defined()
3831when there is only one macro being tested.
3832
Glenn Randers-Pehrson4e6b5e92009-09-23 10:24:53 -05003833We do not use the TAB character for indentation in the C sources.
3834
Glenn Randers-Pehrson62ca98e2009-12-20 15:14:57 -06003835Lines do not exceed 80 characters.
3836
Glenn Randers-Pehrsonf210a052009-11-12 10:02:24 -06003837Other rules can be inferred by inspecting the libpng source.
Glenn Randers-Pehrson glennrp@comcast.netb1c0d332009-05-15 20:39:34 -05003838
Glenn Randers-Pehrson5b40b012010-11-25 07:16:29 -06003839XIV. Y2K Compliance in libpng
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003840
Glenn Randers-Pehrsonb764c602011-01-14 21:18:37 -06003841January 15, 2011
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003842
3843Since the PNG Development group is an ad-hoc body, we can't make
3844an official declaration.
3845
3846This is your unofficial assurance that libpng from version 0.71 and
Glenn Randers-Pehrsonf3c51e42011-01-15 10:25:25 -06003847upward through 1.5.1beta04 are Y2K compliant. It is my belief that earlier
Glenn Randers-Pehrson glennrp@comcast.net9a692c02009-05-15 20:38:11 -05003848versions were also Y2K compliant.
3849
3850Libpng only has three year fields. One is a 2-byte unsigned integer that
3851will hold years up to 65535. The other two hold the date in text
3852format, and will hold years up to 9999.
3853
3854The integer is
3855 "png_uint_16 year" in png_time_struct.
3856
3857The strings are
3858 "png_charp time_buffer" in png_struct and
3859 "near_time_buffer", which is a local character string in png.c.
3860
3861There are seven time-related functions:
3862
3863 png_convert_to_rfc_1123() in png.c
3864 (formerly png_convert_to_rfc_1152() in error)
3865 png_convert_from_struct_tm() in pngwrite.c, called
3866 in pngwrite.c
3867 png_convert_from_time_t() in pngwrite.c
3868 png_get_tIME() in pngget.c
3869 png_handle_tIME() in pngrutil.c, called in pngread.c
3870 png_set_tIME() in pngset.c
3871 png_write_tIME() in pngwutil.c, called in pngwrite.c
3872
3873All appear to handle dates properly in a Y2K environment. The
3874png_convert_from_time_t() function calls gmtime() to convert from system
3875clock time, which returns (year - 1900), which we properly convert to
3876the full 4-digit year. There is a possibility that applications using
3877libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
3878function, or that they are incorrectly passing only a 2-digit year
3879instead of "year - 1900" into the png_convert_from_struct_tm() function,
3880but this is not under our control. The libpng documentation has always
3881stated that it works with 4-digit years, and the APIs have been
3882documented as such.
3883
3884The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
3885integer to hold the year, and can hold years as large as 65535.
3886
3887zlib, upon which libpng depends, is also Y2K compliant. It contains
3888no date-related code.
3889
3890
3891 Glenn Randers-Pehrson
3892 libpng maintainer
3893 PNG Development Group