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