]> git.saurik.com Git - wxWidgets.git/blame - src/png/libpng.3
New wxEventType for event type enum, and corresponding alterations.
[wxWidgets.git] / src / png / libpng.3
CommitLineData
c801d85f
KB
1.TH LIBPNG 3 "March 15, 1998"
2.SH NAME
3libpng \- Portable Network Graphics (PNG) Reference Library
4.SH SYNOPSIS
5
6#include <png.h>
7
8int png_check_sig (png_bytep sig, int num);
9
10void png_chunk_error (png_structp png_ptr, png_const_charp
11error);
12
13void png_chunk_warning (png_structp png_ptr, png_const_charp
14message);
15
16void png_convert_from_struct_tm (png_timep ptime, struct tm FAR
17* ttime);
18
19void png_convert_from_time_t (png_timep ptime, time_t ttime);
20
21png_charp png_convert_to_rfc1123 (png_structp png_ptr,
22png_timep ptime);
23
24png_infop png_create_info_struct (png_structp png_ptr);
25
26png_structp png_create_read_struct (png_const_charp
27user_png_ver, voidp error_ptr, png_error_ptr error_fn,
28png_error_ptr warn_fn);
29
30png_structp png_create_write_struct (png_const_charp
31user_png_ver, voidp error_ptr, png_error_ptr error_fn,
32png_error_ptr warn_fn);
33
34void png_debug_free (png_structp png_ptr, png_voidp ptr);
35
36png_voidp png_debug_malloc (png_structp png_ptr, png_uint_32
37size);
38
39void png_destroy_info_struct (png_structp png_ptr, png_infopp
40info_ptr_ptr);
41
42void png_destroy_read_struct (png_structpp png_ptr_ptr,
43png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr);
44
45void png_destroy_write_struct (png_structpp png_ptr_ptr,
46png_infopp info_ptr_ptr);
47
48void png_error (png_structp png_ptr, png_const_charp error);
49
50void png_free (png_structp png_ptr, png_voidp ptr);
51
52png_byte png_get_bit_depth (png_structp png_ptr, png_infop
53info_ptr);
54
55png_uint_32 png_get_bKGD (png_structp png_ptr, png_infop
56info_ptr, png_color_16p *background);
57
58png_byte png_get_channels (png_structp png_ptr, png_infop
59info_ptr);
60
61png_uint_32 png_get_cHRM (png_structp png_ptr, png_infop
62info_ptr, double *white_x, double *white_y, double *red_x,
63double *red_y, double *green_x, double *green_y, double
64*blue_x, double *blue_y);
65
66png_byte png_get_color_type (png_structp png_ptr, png_infop
67info_ptr);
68
69png_byte png_get_compression_type (png_structp png_ptr,
70png_infop info_ptr);
71
72png_voidp png_get_error_ptr (png_structp png_ptr);
73
74png_byte png_get_filter_type (png_structp png_ptr, png_infop
75info_ptr);
76
77png_uint_32 png_get_gAMA (png_structp png_ptr, png_infop
78info_ptr, double *file_gamma);
79
80png_uint_32 png_get_hIST (png_structp png_ptr, png_infop
81info_ptr, png_uint_16p *hist);
82
83png_uint_32 png_get_image_height (png_structp png_ptr,
84png_infop info_ptr);
85
86png_uint_32 png_get_image_width (png_structp png_ptr, png_infop
87info_ptr);
88
89png_byte png_get_interlace_type (png_structp png_ptr, png_infop
90info_ptr);
91
92png_voidp png_get_io_ptr (png_structp png_ptr);
93
94png_uint_32 png_get_IHDR (png_structp png_ptr, png_infop
95info_ptr, png_uint_32 *width, png_uint_32 *height, int
96*bit_depth, int *color_type, int *interlace_type, int
97*compression_type, int *filter_type);
98
99png_uint_32 png_get_oFFs (png_structp png_ptr, png_infop
100info_ptr, png_uint_32 *offset_x, png_uint_32 *offset_y, int
101*unit_type);
102
103png_uint_32 png_get_pCAL (png_structp png_ptr, png_infop
104info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
105int *type, int *nparams, png_charp *units, png_charpp *params);
106
107png_uint_32 png_get_pHYs (png_structp png_ptr, png_infop
108info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int
109*unit_type);
110
111float png_get_pixel_aspect_ratio (png_structp png_ptr,
112png_infop info_ptr);
113
114png_uint_32 png_get_pixels_per_meter (png_structp png_ptr,
115png_infop info_ptr);
116
117png_voidp png_get_progressive_ptr (png_structp png_ptr);
118
119png_uint_32 png_get_PLTE (png_structp png_ptr, png_infop
120info_ptr, png_colorp *palette, int *num_palette);
121
122png_uint_32 png_get_rowbytes (png_structp png_ptr, png_infop
123info_ptr);
124
125png_uint_32 png_get_sBIT (png_structp png_ptr, png_infop
126info_ptr, png_color_8p *sig_bit);
127
128png_bytep png_get_signature (png_structp png_ptr, png_infop
129info_ptr);
130
131png_uint_32 png_get_sRGB (png_structp png_ptr, png_infop
132info_ptr, int *intent);
133
134png_uint_32 png_get_text (png_structp png_ptr, png_infop
135info_ptr, png_textp *text_ptr, int *num_text);
136
137png_uint_32 png_get_tIME (png_structp png_ptr, png_infop
138info_ptr, png_timep *mod_time);
139
140png_uint_32 png_get_tRNS (png_structp png_ptr, png_infop
141info_ptr, png_bytep *trans, int *num_trans, png_color_16p
142*trans_values);
143
144png_uint_32 png_get_valid (png_structp png_ptr, png_infop
145info_ptr, png_uint_32 flag);
146
147png_uint_32 png_get_x_offset_microns (png_structp png_ptr,
148png_infop info_ptr);
149
150png_uint_32 png_get_x_offset_pixels (png_structp png_ptr,
151png_infop info_ptr);
152
153png_uint_32 png_get_x_pixels_per_meter (png_structp png_ptr,
154png_infop info_ptr);
155
156png_uint_32 png_get_y_offset_microns (png_structp png_ptr,
157png_infop info_ptr);
158
159png_uint_32 png_get_y_offset_pixels (png_structp png_ptr,
160png_infop info_ptr);
161
162png_uint_32 png_get_y_pixels_per_meter (png_structp png_ptr,
163png_infop info_ptr);
164
165void png_info_init (png_infop info_ptr);
166
167void png_init_io (png_structp png_ptr, FILE *fp);
168
169png_voidp png_malloc (png_structp png_ptr, png_uint_32 size);
170
171voidp png_memcpy (png_voidp s1, png_voidp s2, png_size_t size);
172
173png_voidp png_memcpy_check (png_structp png_ptr, png_voidp s1,
174png_voidp s2, png_uint_32 size);
175
176voidp png_memset (png_voidp s1, int value, png_size_t size);
177
178png_voidp png_memset_check (png_structp png_ptr, png_voidp
179s1, int value, png_uint_32 size);
180
181void png_process_data (png_structp png_ptr, png_infop info_ptr,
182png_bytep buffer, png_size_t buffer_size);
183
184void png_progressive_combine_row (png_structp png_ptr,
185png_bytep old_row, png_bytep new_row);
186
187void png_read_destroy (png_structp png_ptr, png_infop info_ptr,
188png_infop end_info_ptr);
189
190void png_read_end (png_structp png_ptr, png_infop info_ptr);
191
192void png_read_image (png_structp png_ptr, png_bytepp image);
193
194void png_read_info (png_structp png_ptr, png_infop info_ptr);
195
196void png_read_row (png_structp png_ptr, png_bytep row,
197png_bytep display_row);
198
199void png_read_rows (png_structp png_ptr, png_bytepp row,
200png_bytepp display_row, png_uint_32 num_rows);
201
202void png_read_update_info (png_structp png_ptr, png_infop
203info_ptr);
204
205void png_set_background (png_structp png_ptr, png_color_16p
206background_color, int background_gamma_code, int need_expand,
207double background_gamma);
208
209void png_set_bgr (png_structp png_ptr);
210
211void png_set_bKGD (png_structp png_ptr, png_infop info_ptr,
212png_color_16p background);
213
214void png_set_cHRM (png_structp png_ptr, png_infop info_ptr,
215double white_x, double white_y, double red_x, double red_y,
216double green_x, double green_y, double blue_x, double blue_y);
217
218void png_set_compression_level (png_structp png_ptr, int
219level);
220
221void png_set_compression_mem_level (png_structp png_ptr, int
222mem_level);
223
224void png_set_compression_method (png_structp png_ptr, int
225method);
226
227void png_set_compression_strategy (png_structp png_ptr, int
228strategy);
229
230void png_set_compression_window_bits (png_structp png_ptr, int
231window_bits);
232
233void png_set_crc_action (png_structp png_ptr, int crit_action,
234int ancil_action);
235
236void png_set_dither (png_structp png_ptr, png_colorp palette,
237int num_palette, int maximum_colors, png_uint_16p histogram,
238int full_dither);
239
240void png_set_error_fn (png_structp png_ptr, png_voidp
241error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn);
242
243void png_set_expand (png_structp png_ptr);
244
245void png_set_filler (png_structp png_ptr, png_uint_32 filler,
246int flags);
247
248void png_set_filter (png_structp png_ptr, int method, int
249filters);
250
251void png_set_filter_heuristics (png_structp png_ptr, int
252heuristic_method, int num_weights, png_doublep filter_weights,
253png_doublep filter_costs);
254
255void png_set_flush (png_structp png_ptr, int nrows);
256
257void png_set_gamma (png_structp png_ptr, double screen_gamma,
258double default_file_gamma);
259
260void png_set_gAMA (png_structp png_ptr, png_infop info_ptr,
261double file_gamma);
262
263void png_set_gray_to_rgb (png_structp png_ptr);
264
265void png_set_hIST (png_structp png_ptr, png_infop info_ptr,
266png_uint_16p hist);
267
268int png_set_interlace_handling (png_structp png_ptr);
269
270void png_set_invert_alpha (png_structp png_ptr);
271
272void png_set_invert_mono (png_structp png_ptr);
273
274void png_set_IHDR (png_structp png_ptr, png_infop info_ptr,
275png_uint_32 width, png_uint_32 height, int bit_depth, int
276color_type, int interlace_type, int compression_type, int
277filter_type);
278
279void png_set_oFFs (png_structp png_ptr, png_infop info_ptr,
280png_uint_32 offset_x, png_uint_32 offset_y, int unit_type);
281
282void png_set_packing (png_structp png_ptr);
283
284void png_set_packswap (png_structp png_ptr);
285
286void png_set_pCAL (png_structp png_ptr, png_infop info_ptr,
287png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int
288nparams, png_charp units, png_charpp params);
289
290void png_set_pHYs (png_structp png_ptr, png_infop info_ptr,
291png_uint_32 res_x, png_uint_32 res_y, int unit_type);
292
293void png_set_progressive_read_fn (png_structp png_ptr,
294png_voidp progressive_ptr, png_progressive_info_ptr info_fn,
295png_progressive_row_ptr row_fn, png_progressive_end_ptr
296end_fn);
297
298void png_set_PLTE (png_structp png_ptr, png_infop info_ptr,
299png_colorp palette, int num_palette);
300
301void png_set_read_fn (png_structp png_ptr, png_voidp io_ptr,
302png_rw_ptr read_data_fn);
303
304void png_set_read_status_fn (png_structp png_ptr, png_read_status_ptr
305 read_row_fn);
306
307void png_set_read_user_transform_fn (png_structp png_ptr,
308 png_user_transform_ptr read_user_transform_fn);
309
310void png_set_rgb_to_gray (png_structp png_ptr);
311
312void png_set_sBIT (png_structp png_ptr, png_infop info_ptr,
313png_color_8p sig_bit);
314
315void png_set_shift (png_structp png_ptr, png_color_8p
316true_bits);
317
318void png_set_sig_bytes (png_structp png_ptr, int num_bytes);
319
320void png_set_sRGB (png_structp png_ptr, png_infop info_ptr, int
321intent);
322
323void png_set_sRGB_gAMA_and_cHRM (png_structp png_ptr, png_infop
324info_ptr, int intent);
325
326void png_set_strip_16 (png_structp png_ptr);
327
328void png_set_strip_alpha (png_structp png_ptr);
329
330void png_set_swap (png_structp png_ptr);
331
332void png_set_swap_alpha (png_structp png_ptr);
333
334void png_set_text (png_structp png_ptr, png_infop info_ptr,
335png_textp text_ptr, int num_text);
336
337void png_set_tIME (png_structp png_ptr, png_infop info_ptr,
338png_timep mod_time);
339
340void png_set_tRNS (png_structp png_ptr, png_infop info_ptr,
341png_bytep trans, int num_trans, png_color_16p trans_values);
342
343void png_set_write_fn (png_structp png_ptr, png_voidp io_ptr,
344png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn);
345
346void png_set_write_status_fn (png_structp png_ptr, png_write_status_ptr
347 write_row_fn);
348
349void png_set_write_user_transform_fn (png_structp png_ptr,
350 png_user_transform_ptr write_user_transform_fn);
351
352int png_sig_cmp (png_bytep sig, png_size_t start, png_size_t
353num_to_check);
354
355void png_start_read_image (png_structp png_ptr);
356
357void png_warning (png_structp png_ptr, png_const_charp
358message);
359
360void png_write_chunk (png_structp png_ptr, png_bytep
361chunk_name, png_bytep data, png_size_t length);
362
363void png_write_chunk_data (png_structp png_ptr, png_bytep data,
364png_size_t length);
365
366void png_write_chunk_end (png_structp png_ptr);
367
368void png_write_chunk_start (png_structp png_ptr, png_bytep
369chunk_name, png_uint_32 length);
370
371void png_write_destroy (png_structp png_ptr);
372
373void png_write_destroy_info (png_infop info_ptr);
374
375void png_write_end (png_structp png_ptr, png_infop info_ptr);
376
377void png_write_flush (png_structp png_ptr);
378
379void png_write_image (png_structp png_ptr, png_bytepp image);
380
381void png_write_info (png_structp png_ptr, png_infop info_ptr);
382
383void png_write_row (png_structp png_ptr, png_bytep row);
384
385void png_write_rows (png_structp png_ptr, png_bytepp row,
386png_uint_32 num_rows);
387
388.SH DESCRIPTION
389The
390.I libpng
391library supports encoding, decoding, and various manipulations of
392the Portable Network Graphics (PNG) format image files. It uses the
393.IR zlib(3)
394compression library.
395Following is a copy of the libpng.txt file that accompanies libpng.
396.SH LIBPNG.TXT
397libpng.txt - A description on how to use and modify libpng
398
399 libpng version 1.0.1 March 15, 1998
400 Updated and distributed by Glenn Randers-Pehrson
401 <randeg@alumni.rpi.edu>
402 Copyright (c) 1998, Glenn Randers-Pehrson
403 For conditions of distribution and use, see copyright
404 notice in png.h.
405
406 based on:
407
408 libpng 1.0 beta 6 version 0.96 May 28, 1997
409 Updated and distributed by Andreas Dilger
410 Copyright (c) 1996, 1997 Andreas Dilger
411
412 libpng 1.0 beta 2 - version 0.88 January 26, 1996
413 For conditions of distribution and use, see copyright
414 notice in png.h. Copyright (c) 1995, 1996 Guy Eric
415 Schalnat, Group 42, Inc.
416
417 Updated/rewritten per request in the libpng FAQ
418 Copyright (c) 1995 Frank J. T. Wojcik
419 December 18, 1995 && January 20, 1996
420
421.SH I. Introduction
422
423This file describes how to use and modify the PNG reference library
424(known as libpng) for your own use. There are five sections to this
425file: introduction, structures, reading, writing, and modification and
426configuration notes for various special platforms. In addition to this
427file, example.c is a good starting point for using the library, as
428it is heavily commented and should include everything most people
429will need. We assume that libpng is already installed; see the
430INSTALL file for instructions on how to install libpng.
431
432Libpng was written as a companion to the PNG specification, as a way
433of reducing the amount of time and effort it takes to support the PNG
434file format in application programs. The PNG specification is available
435as RFC 2083 <ftp://ftp.uu.net/graphics/png/documents/> and as a
436W3C Recommendation <http://www.w3.org/TR/REC.png.html>. Some
437additional chunks are described in the special-purpose public chunks
438documents at <ftp://ftp.uu.net/graphics/png/documents/>. Other information
439about PNG can be found at the PNG home page, <http://www.cdrom.com/pub/png/>.
440
441Most users will not have to modify the library significantly; advanced
442users may want to modify it more. All attempts were made to make it as
443complete as possible, while keeping the code easy to understand.
444Currently, this library only supports C. Support for other languages
445is being considered.
446
447Libpng has been designed to handle multiple sessions at one time,
448to be easily modifiable, to be portable to the vast majority of
449machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
450to use. The ultimate goal of libpng is to promote the acceptance of
451the PNG file format in whatever way possible. While there is still
452work to be done (see the TODO file), libpng should cover the
453majority of the needs of its users.
454
455Libpng uses zlib for its compression and decompression of PNG files.
456The zlib compression utility is a general purpose utility that is
457useful for more than PNG files, and can be used without libpng.
458See the documentation delivered with zlib for more details.
459You can usually find the source files for the zlib utility wherever you
460find the libpng source files.
461
462Libpng is thread safe, provided the threads are using different
463instances of the structures. Each thread should have its own
464png_struct and png_info instances, and thus its own image.
465Libpng does not protect itself against two threads using the
466same instance of a structure.
467
468
469.SH II. Structures
470
471There are two main structures that are important to libpng, png_struct
472and png_info. The first, png_struct, is an internal structure that
473will not, for the most part, be used by a user except as the first
474variable passed to every libpng function call.
475
476The png_info structure is designed to provide information about the
477PNG file. At one time, the fields of png_info were intended to be
478directly accessible to the user. However, this tended to cause problems
479with applications using dynamically loaded libraries, and as a result
480a set of interface functions for png_info was developed. The fields
481of png_info are still available for older applications, but it is
482suggested that applications use the new interfaces if at all possible.
483
484The png.h header file is an invaluable reference for programming with libpng.
485And while I'm on the topic, make sure you include the libpng header file:
486
487#include <png.h>
488
489.SH III. Reading
490
491Reading PNG files:
492
493We'll now walk you through the possible functions to call when reading
494in a PNG file, briefly explaining the syntax and purpose of each one.
495See example.c and png.h for more detail. While Progressive reading
496is covered in the next section, you will still need some of the
497functions discussed in this section to read a PNG file.
498
499You will want to do the I/O initialization(*) before you get into libpng,
500so if it doesn't work, you don't have much to undo. Of course, you
501will also want to insure that you are, in fact, dealing with a PNG
502file. Libpng provides a simple check to see if a file is a PNG file.
503To use it, pass in the first 1 to 8 bytes of the file, and it will
504return true or false (1 or 0) depending on whether the bytes could be
505part of a PNG file. Of course, the more bytes you pass in, the
506greater the accuracy of the prediction.
507
508If you are intending to keep the file pointer open for use in libpng,
509you must ensure you don't read more than 8 bytes from the beginning
510of the file, and you also have to make a call to png_set_sig_bytes_read()
511with the number of bytes you read from the beginning. Libpng will
512then only check the bytes (if any) that your program didn't read.
513
514(*): If you are not using the standard I/O functions, you will need
515to replace them with custom functions. See the discussion under
516Customizing libpng.
517
518
519 FILE *fp = fopen(file_name, "rb");
520 if (!fp)
521 {
522 return;
523 }
524 fread(header, 1, number, fp);
525 is_png = png_check_sig(header, 0, number);
526 if (!is_png)
527 {
528 return;
529 }
530
531
532Next, png_struct and png_info need to be allocated and initialized. In
533order to ensure that the size of these structures is correct even with a
534dynamically linked libpng, there are functions to initialize and
535allocate the structures. We also pass the library version, optional
536pointers to error handling functions, and a pointer to a data struct for
537use by the error functions, if necessary (the pointer and functions can
538be NULL if the default error handlers are to be used). See the section
539on Changes to Libpng below regarding the old initialization functions.
540
541 png_structp png_ptr = png_create_read_struct
542 (PNG_LIBPNG_VER_STRING, (void *)user_error_ptr,
543 user_error_fn, user_warning_fn);
544 if (!png_ptr)
545 return;
546
547 png_infop info_ptr = png_create_info_struct(png_ptr);
548 if (!info_ptr)
549 {
550 png_destroy_read_struct(&png_ptr,
551 (png_infopp)NULL, (png_infopp)NULL);
552 return;
553 }
554
555 png_infop end_info = png_create_info_struct(png_ptr);
556 if (!end_info)
557 {
558 png_destroy_read_struct(&png_ptr, &info_ptr,
559 (png_infopp)NULL);
560 return;
561 }
562
563
564The error handling routines passed to png_create_read_struct() are only
565necessary if you are not using the libpng supplied error handling
566functions. When libpng encounters an error, it expects to longjmp back
567to your routine. Therefore, you will need to call setjmp and pass the
568jmpbuf field of your png_struct. If you read the file from different
569routines, you will need to update the jmpbuf field every time you enter
570a new routine that will call a png_ function.
571
572See your documentation of setjmp/longjmp for your compiler for more
573handling in the Customizing Libpng section below for more information on
574the libpng error handling. If an error occurs, and libpng longjmp's
575back to your setjmp, you will want to call png_destroy_read_struct() to
576free any memory.
577
578 if (setjmp(png_ptr->jmpbuf))
579 {
580 png_destroy_read_struct(&png_ptr, &info_ptr,
581 &end_info);
582 fclose(fp);
583 return;
584 }
585
586Now you need to set up the input code. The default for libpng is to
587use the C function fread(). If you use this, you will need to pass a
588valid FILE * in the function png_init_io(). Be sure that the file is
589opened in binary mode. If you wish to handle reading data in another
590way, you need not call the png_init_io() function, but you must then
591implement the libpng I/O methods discussed in the Customizing Libpng
592section below.
593
594 png_init_io(png_ptr, fp);
595
596If you had previously opened the file and read any of the signature from
597the beginning in order to see if this was a PNG file, you need to let
598libpng know that there are some bytes missing from the start of the file.
599
600 png_set_sig_bytes(png_ptr, number);
601
602At this point, you can set up a callback function that will be
603called after each row has been read, which you can use to control
604a progress meter or the like. It's demonstrated in pngtest.c.
605You must supply a function
606
607 void read_row_callback(png_ptr, png_uint_32 row, int pass);
608 {
609 /* put your code here */
610 }
611
612(You can give it another name that you like instead of "read_row_callback")
613
614To inform libpng about your function, use
615
616 png_set_read_status_fn(png_ptr, read_row_callback);
617
618In PNG files, the alpha channel in an image is the level of opacity.
619If you need the alpha channel in an image to be the level of transparency
620instead of opacity, you can invert the alpha channel (or the tRNS chunk
621data) after it's read, so that 0 is fully opaque and 255 (in 8-bit or
622paletted images) or 65535 (in 16-bit images) is fully transparent, with
623
624 png_set_invert_alpha(png_ptr);
625
626This has to appear here rather than later with the other transformations
627because the tRNS chunk data must be modified in the case of paletted images.
628If your image is not a paletted image, the tRNS data (which in such cases
629represents a single color to be rendered as transparent) won't be changed.
630
631Finally, you can write your own transformation function if none of
632the existing ones meets your needs. This is done by setting a callback
633with
634
635 png_set_read_user_transform_fn(png_ptr,
636 read_transform_fn);
637
638You must supply the function
639
640 void read_transform_fn(png_ptr ptr, row_info_ptr
641 row_info, png_bytep data)
642
643See pngtest.c for a working example. Your function will be called
644after all of the other transformations have been processed.
645
646You are now ready to read all the file information up to the actual
647image data. You do this with a call to png_read_info().
648
649 png_read_info(png_ptr, info_ptr);
650
651Functions are used to get the information from the info_ptr:
652
653 png_get_IHDR(png_ptr, info_ptr, &width, &height,
654 &bit_depth, &color_type, &interlace_type,
655 &compression_type, &filter_type);
656
657 width - holds the width of the image
658 in pixels (up to 2^31).
659 height - holds the height of the image
660 in pixels (up to 2^31).
661 bit_depth - holds the bit depth of one of the
662 image channels. (valid values are
663 1, 2, 4, 8, 16 and depend also on
664 the color_type. See also
665 significant bits (sBIT) below).
666 color_type - describes which color/alpha channels
667 are present.
668 PNG_COLOR_TYPE_GRAY
669 (bit depths 1, 2, 4, 8, 16)
670 PNG_COLOR_TYPE_GRAY_ALPHA
671 (bit depths 8, 16)
672 PNG_COLOR_TYPE_PALETTE
673 (bit depths 1, 2, 4, 8)
674 PNG_COLOR_TYPE_RGB
675 (bit_depths 8, 16)
676 PNG_COLOR_TYPE_RGB_ALPHA
677 (bit_depths 8, 16)
678
679 PNG_COLOR_MASK_PALETTE
680 PNG_COLOR_MASK_COLOR
681 PNG_COLOR_MASK_ALPHA
682
683 filter_type - (must be PNG_FILTER_TYPE_BASE
684 for PNG 1.0)
685 compression_type - (must be PNG_COMPRESSION_TYPE_BASE
686 for PNG 1.0)
687 interlace_type - (PNG_INTERLACE_NONE or
688 PNG_INTERLACE_ADAM7)
689 Any or all of interlace_type, compression_type, of
690 filter_type can be
691 NULL if you are not interested in their values.
692
693 channels = png_get_channels(png_ptr, info_ptr);
694 channels - number of channels of info for the
695 color type (valid values are 1 (GRAY,
696 PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
697 4 (RGB_ALPHA or RGB + filler byte))
698 rowbytes = png_get_rowbytes(png_ptr, info_ptr);
699 rowbytes - number of bytes needed to hold a row
700
701 signature = png_get_signature(png_ptr, info_ptr);
702 signature - holds the signature read from the
703 file (if any). The data is kept in
704 the same offset it would be if the
705 whole signature were read (i.e. if an
706 application had already read in 4
707 bytes of signature before starting
708 libpng, the remaining 4 bytes would
709 be in signature[4] through signature[7]
710 (see png_set_sig_bytes())).
711
712
713 width = png_get_image_width(png_ptr,
714 info_ptr);
715 height = png_get_image_height(png_ptr,
716 info_ptr);
717 bit_depth = png_get_bit_depth(png_ptr,
718 info_ptr);
719 color_type = png_get_color_type(png_ptr,
720 info_ptr);
721 filter_type = png_get_filter_type(png_ptr,
722 info_ptr);
723 compression_type = png_get_compression_type(png_ptr,
724 info_ptr);
725 interlace_type = png_get_interlace_type(png_ptr,
726 info_ptr);
727
728
729These are also important, but their validity depends on whether the chunk
730has been read. The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
731png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
732data has been read, or zero if it is missing. The parameters to the
733png_get_<chunk> are set directly if they are simple data types, or a pointer
734into the info_ptr is returned for any complex types.
735
736 png_get_PLTE(png_ptr, info_ptr, &palette,
737 &num_palette);
738 palette - the palette for the file
739 (array of png_color)
740 num_palette - number of entries in the palette
741
742 png_get_gAMA(png_ptr, info_ptr, &gamma);
743 gamma - the gamma the file is written
744 at (PNG_INFO_gAMA)
745
746 png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
747 srgb_intent - the rendering intent (PNG_INFO_sRGB)
748 The presence of the sRGB chunk
749 means that the pixel data is in the
750 sRGB color space. This chunk also
751 implies specific values of gAMA and
752 cHRM.
753
754 png_get_sBIT(png_ptr, info_ptr, &sig_bit);
755 sig_bit - the number of significant bits for
756 (PNG_INFO_sBIT) each of the gray,
757 red, green, and blue channels,
758 whichever are appropriate for the
759 given color type (png_color_16)
760
761 png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
762 &trans_values);
763 trans - array of transparent entries for
764 palette (PNG_INFO_tRNS)
765 trans_values - transparent pixel for non-paletted
766 images (PNG_INFO_tRNS)
767 num_trans - number of transparent entries
768 (PNG_INFO_tRNS)
769
770 png_get_hIST(png_ptr, info_ptr, &hist);
771 (PNG_INFO_hIST)
772 hist - histogram of palette (array of
773 png_color_16)
774
775 png_get_tIME(png_ptr, info_ptr, &mod_time);
776 mod_time - time image was last modified
777 (PNG_VALID_tIME)
778
779 png_get_bKGD(png_ptr, info_ptr, &background);
780 background - background color (PNG_VALID_bKGD)
781
782 num_text = png_get_text(png_ptr, info_ptr, &text_ptr);
783 text_ptr - array of png_text holding image
784 comments
785 text_ptr[i]->key - keyword for comment.
786 text_ptr[i]->text - text comments for current
787 keyword.
788 text_ptr[i]->compression - type of compression used
789 on "text" PNG_TEXT_COMPRESSION_NONE
790 or PNG_TEXT_COMPRESSION_zTXt
791 num_text - number of comments
792
793 png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
794 &unit_type);
795 offset_x - positive offset from the left edge
796 of the screen
797 offset_y - positive offset from the top edge
798 of the screen
799 unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
800
801 png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
802 &unit_type);
803 res_x - pixels/unit physical resolution in
804 x direction
805 res_y - pixels/unit physical resolution in
806 x direction
807 unit_type - PNG_RESOLUTION_UNKNOWN,
808 PNG_RESOLUTION_METER
809
810The data from the pHYs chunk can be retrieved in several convenient
811forms:
812
813 res_x = png_get_x_pixels_per_meter(png_ptr,
814 info_ptr)
815 res_y = png_get_y_pixels_per_meter(png_ptr,
816 info_ptr)
817 res_x_and_y = png_get_pixels_per_meter(png_ptr,
818 info_ptr)
819 aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
820 info_ptr)
821
822 (Each of these returns 0 [signifying "unknown"] if
823 the data is not present or if res_x is 0;
824 res_x_and_y is 0 if res_x != res_y)
825
826For more information, see the png_info definition in png.h and the
827PNG specification for chunk contents. Be careful with trusting
828rowbytes, as some of the transformations could increase the space
829needed to hold a row (expand, filler, gray_to_rgb, etc.).
830See png_read_update_info(), below.
831
832A quick word about text_ptr and num_text. PNG stores comments in
833keyword/text pairs, one pair per chunk, with no limit on the number
834of text chunks, and a 2^31 byte limit on their size. While there are
835suggested keywords, there is no requirement to restrict the use to these
836strings. It is strongly suggested that keywords and text be sensible
837to humans (that's the point), so don't use abbreviations. Non-printing
838symbols are not allowed. See the PNG specification for more details.
839There is also no requirement to have text after the keyword.
840
841Keywords should be limited to 79 Latin-1 characters without leading or
842trailing spaces, but non-consecutive spaces are allowed within the
843keyword. It is possible to have the same keyword any number of times.
844The text_ptr is an array of png_text structures, each holding pointer
845to a keyword and a pointer to a text string. Only the text string may
846be null. The keyword/text pairs are put into the array in the order
847that they are received. However, some or all of the text chunks may be
848after the image, so, to make sure you have read all the text chunks,
849don't mess with these until after you read the stuff after the image.
850This will be mentioned again below in the discussion that goes with
851png_read_end().
852
853After you've read the header information, you can set up the library
854to handle any special transformations of the image data. The various
855ways to transform the data will be described in the order that they
856should occur. This is important, as some of these change the color
857type and/or bit depth of the data, and some others only work on
858certain color types and bit depths. Even though each transformation
859checks to see if it has data that it can do something with, you should
860make sure to only enable a transformation if it will be valid for the
861data. For example, don't swap red and blue on grayscale data.
862
863The colors used for the background and transparency values should be
864supplied in the same format/depth as the current image data. They
865are stored in the same format/depth as the image data in a bKGD or tRNS
866chunk, so this is what libpng expects for this data. The colors are
867transformed to keep in sync with the image data when an application
868calls the png_read_update_info() routine (see below).
869
870Data will be decoded into the supplied row buffers packed into bytes
871unless the library has been told to transform it into another format.
872For example, 4 bit/pixel paletted or grayscale data will be returned
8732 pixels/byte with the leftmost pixel in the high-order bits of the
874byte, unless png_set_packing() is called. 8-bit RGB data will be stored
875in RGBRGBRGB format unless png_set_filler() is called to insert filler
876bytes, either before or after each RGB triplet. 16-bit RGB data will
877be returned RRGGBBRRGGBB, with the most significant byte of the color
878value first, unless png_set_strip_16() is called to transform it to
879regular RGBRGB triplets.
880
881The following code transforms grayscale images of less than 8 to 8 bits,
882changes paletted images to RGB, and adds a full alpha channel if there is
883transparency information in a tRNS chunk. This is most useful on
884grayscale images with bit depths of 2 or 4 or if there is a multiple-image
885viewing application that wishes to treat all images in the same way.
886
887 if (color_type == PNG_COLOR_TYPE_PALETTE &&
888 bit_depth <= 8) png_set_expand(png_ptr);
889
890 if (color_type == PNG_COLOR_TYPE_GRAY &&
891 bit_depth < 8) png_set_expand(png_ptr);
892
893 if (png_get_valid(png_ptr, info_ptr,
894 PNG_INFO_tRNS)) png_set_expand(png_ptr);
895
896PNG can have files with 16 bits per channel. If you only can handle
8978 bits per channel, this will strip the pixels down to 8 bit.
898
899 if (bit_depth == 16)
900 png_set_strip_16(png_ptr);
901
902The png_set_background() function tells libpng to composite images
903with alpha or simple transparency against the supplied background
904color. If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
905you may use this color, or supply another color more suitable for
906the current display (e.g., the background color from a web page). You
907need to tell libpng whether the color is in the gamma space of the
908display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
909(PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
910that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
911know why anyone would use this, but it's here).
912
913If, for some reason, you don't need the alpha channel on an image,
914and you want to remove it rather than combining it with the background
915(but the image author certainly had in mind that you *would* combine
916it with the background, so that's what you should probably do):
917
918 if (color_type & PNG_COLOR_MASK_ALPHA)
919 png_set_strip_alpha(png_ptr);
920
921PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
922they can, resulting in, for example, 8 pixels per byte for 1 bit
923files. This code expands to 1 pixel per byte without changing the
924values of the pixels:
925
926 if (bit_depth < 8)
927 png_set_packing(png_ptr);
928
929PNG files have possible bit depths of 1, 2, 4, 8, and 16. All pixels
930stored in a PNG image have been "scaled" or "shifted" up to the next
931higher possible bit depth (e.g. from 5 bits/sample in the range [0,31] to
9328 bits/sample in the range [0, 255]). However, it is also possible to
933convert the PNG pixel data back to the original bit depth of the image.
934This call reduces the pixels back down to the original bit depth:
935
936 png_color_16p sig_bit;
937
938 if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
939 png_set_shift(png_ptr, sig_bit);
940
941PNG files store 3-color pixels in red, green, blue order. This code
942changes the storage of the pixels to blue, green, red:
943
944 if (color_type == PNG_COLOR_TYPE_RGB ||
945 color_type == PNG_COLOR_TYPE_RGB_ALPHA)
946 png_set_bgr(png_ptr);
947
948PNG files store RGB pixels packed into 3 bytes. This code expands them
949into 4 bytes for windowing systems that need them in this format:
950
951 if (bit_depth == 8 && color_type ==
952 PNG_COLOR_TYPE_RGB) png_set_filler(png_ptr,
953 filler, PNG_FILLER_BEFORE);
954
955where "filler" is the number to fill with, and the location is
956either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
957you want the filler before the RGB or after. This transformation
958does not affect images that already have full alpha channels.
959
960If you are reading an image with an alpha channel, and you need the
961data as ARGB instead of the normal PNG format RGBA:
962
963 if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
964 png_set_swap_alpha(png_ptr);
965
966For some uses, you may want a grayscale image to be represented as
967RGB. This code will do that conversion:
968
969 if (color_type == PNG_COLOR_TYPE_GRAY ||
970 color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
971 png_set_gray_to_rgb(png_ptr);
972
973If you have a grayscale and you are using png_set_expand() to change to
974a higher bit-depth you must indicate if the supplied background gray
975is supplied in the original file bit depth (need_expand = 1) or in the
976expanded bit depth (need_expand = 0). Similarly, if you are reading
977a paletted image, you must indicate if you have supplied the background
978as a palette index that needs to be expanded (need_expand = 1). You can
979also specify an RGB triplet that isn't in the palette when setting your
980background for a paletted image.
981
982 png_color_16 my_background;
983 png_color_16p image_background;
984
985 if (png_get_bKGD(png_ptr, info_ptr,
986 &image_background))
987 png_set_background(png_ptr, image_background),
988 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
989 else
990 png_set_background(png_ptr, &my_background,
991 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
992
993To properly display PNG images on any kind of system, the application needs
994to know what the display gamma is. Ideally, the user will know this, and
995the application will allow them to set it. One method of allowing the user
996to set the display gamma separately for each system is to check for the
997DISPLAY_GAMMA and VIEWING_GAMMA environment variables or for a SCREEN_GAMMA
998environment variable, which will hopefully be correctly set.
999
1000Note that display_gamma is the gamma of your display, while screen_gamma is
1001the overall gamma correction required to produce pleasing results,
1002which depends on the lighting conditions in the surrounding environment.
1003Screen_gamma is display_gamma/viewing_gamma, where viewing_gamma is
1004the amount of additional gamma correction needed to compensate for
1005a (viewing_gamma=1.25) environment. In a dim or brightly lit room, no
1006compensation other than the display_gamma is needed (viewing_gamma=1.0).
1007
1008 if (/* We have a user-defined screen
1009 gamma value */)
1010 {
1011 screen_gamma = user_defined_screen_gamma;
1012 }
1013 /* One way that applications can share the same
1014 screen gamma value */
1015 else if ((gamma_str = getenv("SCREEN_GAMMA"))
1016 != NULL)
1017 {
1018 screen_gamma = atof(gamma_str);
1019 }
1020 /* If we don't have another value */
1021 else
1022 {
1023 screen_gamma = 2.2; /* A good guess for a
1024 PC monitor in a bright office or a dim room */
1025 screen_gamma = 2.0; /* A good guess for a
1026 PC monitor in a dark room */
1027 screen_gamma = 1.7 or 1.0; /* A good
1028 guess for Mac systems */
1029 }
1030
1031The png_set_gamma() function handles gamma transformations of the data.
1032Pass both the file gamma and the current screen_gamma. If the file does
1033not have a gamma value, you can pass one anyway if you have an idea what
1034it is (usually 0.50 is a good guess for GIF images on PCs). Note
1035that file gammas are inverted from screen gammas. See the discussions
1036on gamma in the PNG specification for an excellent description of what
1037gamma is, and why all applications should support it. It is strongly
1038recommended that PNG viewers support gamma correction.
1039
1040 if (png_get_gAMA(png_ptr, info_ptr, &gamma))
1041 png_set_gamma(png_ptr, screen_gamma, gamma);
1042 else
1043 png_set_gamma(png_ptr, screen_gamma, 0.50);
1044
1045If you need to reduce an RGB file to a paletted file, or if a paletted
1046file has more entries then will fit on your screen, png_set_dither()
1047will do that. Note that this is a simple match dither that merely
1048finds the closest color available. This should work fairly well with
1049optimized palettes, and fairly badly with linear color cubes. If you
1050pass a palette that is larger then maximum_colors, the file will
1051reduce the number of colors in the palette so it will fit into
1052maximum_colors. If there is a histogram, it will use it to make
1053more intelligent choices when reducing the palette. If there is no
1054histogram, it may not do as good a job.
1055
1056 if (color_type & PNG_COLOR_MASK_COLOR)
1057 {
1058 if (png_get_valid(png_ptr, info_ptr,
1059 PNG_INFO_PLTE))
1060 {
1061 png_color_16p histogram;
1062
1063 png_get_hIST(png_ptr, info_ptr,
1064 &histogram);
1065 png_set_dither(png_ptr, palette, num_palette,
1066 max_screen_colors, histogram, 1);
1067 }
1068 else
1069 {
1070 png_color std_color_cube[MAX_SCREEN_COLORS] =
1071 { ... colors ... };
1072
1073 png_set_dither(png_ptr, std_color_cube,
1074 MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
1075 NULL,0);
1076 }
1077 }
1078
1079PNG files describe monochrome as black being zero and white being one.
1080The following code will reverse this (make black be one and white be
1081zero):
1082
1083 if (bit_depth == 1 && color_type == PNG_COLOR_GRAY)
1084 png_set_invert_mono(png_ptr);
1085
1086PNG files store 16 bit pixels in network byte order (big-endian,
1087ie. most significant bits first). This code changes the storage to the
1088other way (little-endian, i.e. least significant bits first, the
1089way PCs store them):
1090
1091 if (bit_depth == 16)
1092 png_set_swap(png_ptr);
1093
1094If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
1095need to change the order the pixels are packed into bytes, you can use:
1096
1097 if (bit_depth < 8)
1098 png_set_packswap(png_ptr);
1099
1100The last thing to handle is interlacing; this is covered in detail below,
1101but you must call the function here if you want libpng to handle expansion
1102of the interlaced image.
1103
1104 number_of_passes = png_set_interlace_handling(png_ptr);
1105
1106After setting the transformations, libpng can update your png_info
1107structure to reflect any transformations you've requested with this
1108call. This is most useful to update the info structure's rowbytes
1109field so you can use it to allocate your image memory. This function
1110will also update your palette with the correct screen_gamma and
1111background if these have been given with the calls above.
1112
1113 png_read_update_info(png_ptr, info_ptr);
1114
1115After you call png_read_update_info(), you can allocate any
1116memory you need to hold the image. The row data is simply
1117raw byte data for all forms of images. As the actual allocation
1118varies among applications, no example will be given. If you
1119are allocating one large chunk, you will need to build an
1120array of pointers to each row, as it will be needed for some
1121of the functions below.
1122
1123After you've allocated memory, you can read the image data.
1124The simplest way to do this is in one function call. If you are
1125allocating enough memory to hold the whole image, you can just
1126call png_read_image() and libpng will read in all the image data
1127and put it in the memory area supplied. You will need to pass in
1128an array of pointers to each row.
1129
1130This function automatically handles interlacing, so you don't need
1131to call png_set_interlace_handling() or call this function multiple
1132times, or any of that other stuff necessary with png_read_rows().
1133
1134 png_read_image(png_ptr, row_pointers);
1135
1136where row_pointers is:
1137
1138 png_bytep row_pointers[height];
1139
1140You can point to void or char or whatever you use for pixels.
1141
1142If you don't want to read in the whole image at once, you can
1143use png_read_rows() instead. If there is no interlacing (check
1144interlace_type == PNG_INTERLACE_NONE), this is simple:
1145
1146 png_read_rows(png_ptr, row_pointers, NULL,
1147 number_of_rows);
1148
1149where row_pointers is the same as in the png_read_image() call.
1150
1151If you are doing this just one row at a time, you can do this with
1152row_pointers:
1153
1154 png_bytep row_pointers = row;
1155 png_read_row(png_ptr, &row_pointers, NULL);
1156
1157If the file is interlaced (info_ptr->interlace_type != 0), things get
1158somewhat harder. The only current (PNG Specification version 1.0)
1159interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7)
1160is a somewhat complicated 2D interlace scheme, known as Adam7, that
1161breaks down an image into seven smaller images of varying size, based
1162on an 8x8 grid.
1163
1164libpng can fill out those images or it can give them to you "as is".
1165If you want them filled out, there are two ways to do that. The one
1166mentioned in the PNG specification is to expand each pixel to cover
1167those pixels that have not been read yet (the "rectangle" method).
1168This results in a blocky image for the first pass, which gradually
1169smooths out as more pixels are read. The other method is the "sparkle"
1170method, where pixels are drawn only in their final locations, with the
1171rest of the image remaining whatever colors they were initialized to
1172before the start of the read. The first method usually looks better,
1173but tends to be slower, as there are more pixels to put in the rows.
1174
1175If you don't want libpng to handle the interlacing details, just call
1176png_read_rows() seven times to read in all seven images. Each of the
1177images is a valid image by itself, or they can all be combined on an
11788x8 grid to form a single image (although if you intend to combine them
1179you would be far better off using the libpng interlace handling).
1180
1181The first pass will return an image 1/8 as wide as the entire image
1182(every 8th column starting in column 0) and 1/8 as high as the original
1183(every 8th row starting in row 0), the second will be 1/8 as wide
1184(starting in column 4) and 1/8 as high (also starting in row 0). The
1185third pass will be 1/4 as wide (every 4th pixel starting in column 0) and
11861/8 as high (every 8th row starting in row 4), and the fourth pass will
1187be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
1188and every 4th row starting in row 0). The fifth pass will return an
1189image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
1190while the sixth pass will be 1/2 as wide and 1/2 as high as the original
1191(starting in column 1 and row 0). The seventh and final pass will be as
1192wide as the original, and 1/2 as high, containing all of the odd
1193numbered scanlines. Phew!
1194
1195If you want libpng to expand the images, call this before calling
1196png_start_read_image() or png_read_update_info():
1197
1198 if (interlace_type == PNG_INTERLACE_ADAM7)
1199 number_of_passes
1200 = png_set_interlace_handling(png_ptr);
1201
1202This will return the number of passes needed. Currently, this
1203is seven, but may change if another interlace type is added.
1204This function can be called even if the file is not interlaced,
1205where it will return one pass.
1206
1207If you are not going to display the image after each pass, but are
1208going to wait until the entire image is read in, use the sparkle
1209effect. This effect is faster and the end result of either method
1210is exactly the same. If you are planning on displaying the image
1211after each pass, the "rectangle" effect is generally considered the
1212better looking one.
1213
1214If you only want the "sparkle" effect, just call png_read_rows() as
1215normal, with the third parameter NULL. Make sure you make pass over
1216the image number_of_passes times, and you don't change the data in the
1217rows between calls. You can change the locations of the data, just
1218not the data. Each pass only writes the pixels appropriate for that
1219pass, and assumes the data from previous passes is still valid.
1220
1221 png_read_rows(png_ptr, row_pointers, NULL,
1222 number_of_rows);
1223
1224If you only want the first effect (the rectangles), do the same as
1225before except pass the row buffer in the third parameter, and leave
1226the second parameter NULL.
1227
1228 png_read_rows(png_ptr, NULL, row_pointers,
1229 number_of_rows);
1230
1231After you are finished reading the image, you can finish reading
1232the file. If you are interested in comments or time, which may be
1233stored either before or after the image data, you should pass the
1234separate png_info struct if you want to keep the comments from
1235before and after the image separate. If you are not interested, you
1236can pass NULL.
1237
1238 png_read_end(png_ptr, end_info);
1239
1240When you are done, you can free all memory allocated by libpng like this:
1241
1242 png_destroy_read_struct(&png_ptr, &info_ptr,
1243 &end_info);
1244
1245For a more compact example of reading a PNG image, see the file example.c.
1246
1247
1248Reading PNG files progressively:
1249
1250The progressive reader is slightly different then the non-progressive
1251reader. Instead of calling png_read_info(), png_read_rows(), and
1252png_read_end(), you make one call to png_process_data(), which calls
1253callbacks when it has the info, a row, or the end of the image. You
1254set up these callbacks with png_set_progressive_read_fn(). You don't
1255have to worry about the input/output functions of libpng, as you are
1256giving the library the data directly in png_process_data(). I will
1257assume that you have read the section on reading PNG files above,
1258so I will only highlight the differences (although I will show
1259all of the code).
1260
1261png_structp png_ptr;
1262png_infop info_ptr;
1263
1264 /* An example code fragment of how you would
1265 initialize the progressive reader in your
1266 application. */
1267 int
1268 initialize_png_reader()
1269 {
1270 png_ptr = png_create_read_struct
1271 (PNG_LIBPNG_VER_STRING, (void *)user_error_ptr,
1272 user_error_fn, user_warning_fn);
1273 if (!png_ptr)
1274 return -1;
1275 info_ptr = png_create_info_struct(png_ptr);
1276 if (!info_ptr)
1277 {
1278 png_destroy_read_struct(&png_ptr, (png_infopp)NULL,
1279 (png_infopp)NULL);
1280 return -1;
1281 }
1282
1283 if (setjmp(png_ptr->jmpbuf))
1284 {
1285 png_destroy_read_struct(&png_ptr, &info_ptr,
1286 (png_infopp)NULL);
1287 return -1;
1288 }
1289
1290 /* This one's new. You can provide functions
1291 to be called when the header info is valid,
1292 when each row is completed, and when the image
1293 is finished. If you aren't using all functions,
1294 you can specify a NULL parameter. You can use
1295 any struct as the user_ptr (cast to a void pointer
1296 for the function call), and retrieve the pointer
1297 from inside the callbacks using the function
1298
1299 png_get_progressive_ptr(png_ptr);
1300
1301 which will return a void pointer, which you have
1302 to cast appropriately.
1303 */
1304 png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
1305 info_callback, row_callback, end_callback);
1306
1307 return 0;
1308 }
1309
1310 /* A code fragment that you call as you receive blocks
1311 of data */
1312 int
1313 process_data(png_bytep buffer, png_uint_32 length)
1314 {
1315 if (setjmp(png_ptr->jmpbuf))
1316 {
1317 png_destroy_read_struct(&png_ptr, &info_ptr,
1318 (png_infopp)NULL);
1319 return -1;
1320 }
1321
1322 /* This one's new also. Simply give it a chunk
1323 of data from the file stream (in order, of
1324 course). On machines with segmented memory
1325 models machines, don't give it any more than
1326 64K. The library seems to run fine with sizes
1327 of 4K. Although you can give it much less if
1328 necessary (I assume you can give it chunks of
1329 1 byte, I haven't tried less then 256 bytes
1330 yet). When this function returns, you may
1331 want to display any rows that were generated
1332 in the row callback if you don't already do
1333 so there.
1334 */
1335 png_process_data(png_ptr, info_ptr, buffer, length);
1336 return 0;
1337 }
1338
1339 /* This function is called (as set by
1340 png_set_progressive_fn() above) when enough data
1341 has been supplied so all of the header has been
1342 read.
1343 */
1344 void
1345 info_callback(png_structp png_ptr, png_infop info)
1346 {
1347 /* Do any setup here, including setting any of
1348 the transformations mentioned in the Reading
1349 PNG files section. For now, you _must_ call
1350 either png_start_read_image() or
1351 png_read_update_info() after all the
1352 transformations are set (even if you don't set
1353 any). You may start getting rows before
1354 png_process_data() returns, so this is your
1355 last chance to prepare for that.
1356 */
1357 }
1358
1359 /* This function is called when each row of image
1360 data is complete */
1361 void
1362 row_callback(png_structp png_ptr, png_bytep new_row,
1363 png_uint_32 row_num, int pass)
1364 {
1365 /* If the image is interlaced, and you turned
1366 on the interlace handler, this function will
1367 be called for every row in every pass. Some
1368 of these rows will not be changed from the
1369 previous pass. When the row is not changed,
1370 the new_row variable will be NULL. The rows
1371 and passes are called in order, so you don't
1372 really need the row_num and pass, but I'm
1373 supplying them because it may make your life
1374 easier.
1375
1376 For the non-NULL rows of interlaced images,
1377 you must call png_progressive_combine_row()
1378 passing in the row and the old row. You can
1379 call this function for NULL rows (it will just
1380 return) and for non-interlaced images (it just
1381 does the memcpy for you) if it will make the
1382 code easier. Thus, you can just do this for
1383 all cases:
1384 */
1385
1386 png_progressive_combine_row(png_ptr, old_row,
1387 new_row);
1388
1389 /* where old_row is what was displayed for
1390 previous rows. Note that the first pass
1391 (pass == 0, really) will completely cover
1392 the old row, so the rows do not have to be
1393 initialized. After the first pass (and only
1394 for interlaced images), you will have to pass
1395 the current row, and the function will combine
1396 the old row and the new row.
1397 */
1398 }
1399
1400 void
1401 end_callback(png_structp png_ptr, png_infop info)
1402 {
1403 /* This function is called after the whole image
1404 has been read, including any chunks after the
1405 image (up to and including the IEND). You
1406 will usually have the same info chunk as you
1407 had in the header, although some data may have
1408 been added to the comments and time fields.
1409
1410 Most people won't do much here, perhaps setting
1411 a flag that marks the image as finished.
1412 */
1413 }
1414
1415.SH IV. Writing
1416
1417Much of this is very similar to reading. However, everything of
1418importance is repeated here, so you won't have to constantly look
1419back up in the reading section to understand writing.
1420
1421You will want to do the I/O initialization before you get into libpng,
1422so if it doesn't work, you don't have anything to undo. If you are not
1423using the standard I/O functions, you will need to replace them with
1424custom writing functions. See the discussion under Customizing libpng.
1425
1426 FILE *fp = fopen(file_name, "wb");
1427 if (!fp)
1428 {
1429 return;
1430 }
1431
1432Next, png_struct and png_info need to be allocated and initialized.
1433As these can be both relatively large, you may not want to store these
1434on the stack, unless you have stack space to spare. Of course, you
1435will want to check if they return NULL. If you are also reading,
1436you won't want to name your read structure and your write structure
1437both "png_ptr"; you can call them anything you like, such as
1438"read_ptr" and "write_ptr". Look at pngtest.c, for example.
1439
1440 png_structp png_ptr = png_create_write_struct
1441 (PNG_LIBPNG_VER_STRING, (void *)user_error_ptr,
1442 user_error_fn, user_warning_fn);
1443 if (!png_ptr)
1444 return;
1445
1446 png_infop info_ptr = png_create_info_struct(png_ptr);
1447 if (!info_ptr)
1448 {
1449 png_destroy_write_struct(&png_ptr,
1450 (png_infopp)NULL);
1451 return;
1452 }
1453
1454After you have these structures, you will need to set up the
1455error handling. When libpng encounters an error, it expects to
1456longjmp() back to your routine. Therefore, you will need to call
1457setjmp and pass the jmpbuf field of your png_struct. If you
1458write the file from different routines, you will need to update
1459the jmpbuf field every time you enter a new routine that will
1460call a png_ function. See your documentation of setjmp/longjmp
1461for your compiler for more information on setjmp/longjmp. See
1462the discussion on libpng error handling in the Customizing Libpng
1463section below for more information on the libpng error handling.
1464
1465 if (setjmp(png_ptr->jmpbuf))
1466 {
1467 png_destroy_write_struct(&png_ptr, &info_ptr);
1468 fclose(fp);
1469 return;
1470 }
1471
1472Now you need to set up the output code. The default for libpng is to
1473use the C function fwrite(). If you use this, you will need to pass a
1474valid FILE * in the function png_init_io(). Be sure that the file is
1475opened in binary mode. Again, if you wish to handle writing data in
1476another way, see the discussion on libpng I/O handling in the Customizing
1477Libpng section below.
1478
1479 png_init_io(png_ptr, fp);
1480
1481At this point, you can set up a callback function that will be
1482called after each row has been written, which you can use to control
1483a progress meter or the like. It's demonstrated in pngtest.c.
1484You must supply a function
1485
1486 void write_row_callback(png_ptr, png_uint_32 row, int pass);
1487 {
1488 /* put your code here */
1489 }
1490
1491(You can give it another name that you like instead of "write_row_callback")
1492
1493To inform libpng about your function, use
1494
1495 png_set_write_status_fn(png_ptr, write_row_callback);
1496
1497You now have the option of modifying how the compression library will
1498run. The following functions are mainly for testing, but may be useful
1499in some cases, like if you need to write PNG files extremely fast and
1500are willing to give up some compression, or if you want to get the
1501maximum possible compression at the expense of slower writing. If you
1502have no special needs in this area, let the library do what it wants by
1503not calling this function at all, as it has been tuned to deliver a good
1504speed/compression ratio. The second parameter to png_set_filter() is
1505the filter method, for which the only valid value is '0' (as of the
1506October 1996 PNG specification, version 1.0). The third parameter is a
1507flag that indicates
1508which filter type(s) are to be tested for each scanline. See the
1509Compression Library for details on the specific filter types.
1510
1511
1512 /* turn on or off filtering, and/or choose
1513 specific filters */
1514 png_set_filter(png_ptr, 0,
1515 PNG_FILTER_NONE | PNG_FILTER_SUB |
1516 PNG_FILTER_PAETH);
1517
1518The png_set_compression_???() functions interface to the zlib compression
1519library, and should mostly be ignored unless you really know what you are
1520doing. The only generally useful call is png_set_compression_level()
1521which changes how much time zlib spends on trying to compress the image
1522data. See the Compression Library for details on the compression levels.
1523
1524 /* set the zlib compression level */
1525 png_set_compression_level(png_ptr,
1526 Z_BEST_COMPRESSION);
1527
1528 /* set other zlib parameters */
1529 png_set_compression_mem_level(png_ptr, 8);
1530 png_set_compression_strategy(png_ptr,
1531 Z_DEFAULT_STRATEGY);
1532 png_set_compression_window_bits(png_ptr, 15);
1533 png_set_compression_method(png_ptr, 8);
1534
1535You now need to fill in the png_info structure with all the data you
1536wish to write before the actual image. Note that the only thing you
1537are allowed to write after the image is the text chunks and the time
1538chunk (as of PNG Specification 1.0, anyway). See png_write_end() and
1539the latest PNG specification for more information on that. If you
1540wish to write them before the image, fill them in now, and flag that
1541data as being valid. If you want to wait until after the data, don't
1542fill them until png_write_end(). For all the fields in png_info and
1543their data types, see png.h. For explanations of what the fields
1544contain, see the PNG specification.
1545
1546Some of the more important parts of the png_info are:
1547
1548 png_set_IHDR(png_ptr, info_ptr, width, height,
1549 bit_depth, color_type, interlace_type,
1550 compression_type, filter_type)
1551 width - holds the width of the image
1552 in pixels (up to 2^31).
1553 height - holds the height of the image
1554 in pixels (up to 2^31).
1555 bit_depth - holds the bit depth of one of the
1556 image channels.
1557 (valid values are 1, 2, 4, 8, 16
1558 and depend also on the
1559 color_type. See also significant
1560 bits (sBIT) below).
1561 color_type - describes which color/alpha
1562 channels are present.
1563 PNG_COLOR_TYPE_GRAY
1564 (bit depths 1, 2, 4, 8, 16)
1565 PNG_COLOR_TYPE_GRAY_ALPHA
1566 (bit depths 8, 16)
1567 PNG_COLOR_TYPE_PALETTE
1568 (bit depths 1, 2, 4, 8)
1569 PNG_COLOR_TYPE_RGB
1570 (bit_depths 8, 16)
1571 PNG_COLOR_TYPE_RGB_ALPHA
1572 (bit_depths 8, 16)
1573
1574 PNG_COLOR_MASK_PALETTE
1575 PNG_COLOR_MASK_COLOR
1576 PNG_COLOR_MASK_ALPHA
1577
1578 interlace_type - PNG_INTERLACE_NONE or
1579 PNG_INTERLACE_ADAM7
1580 compression_type - (must be
1581 PNG_COMPRESSION_TYPE_DEFAULT)
1582 filter_type - (must be PNG_FILTER_TYPE_DEFAULT)
1583
1584 png_set_PLTE(png_ptr, info_ptr, palette,
1585 num_palette);
1586 palette - the palette for the file
1587 (array of png_color)
1588 num_palette - number of entries in the palette
1589
1590 png_set_gAMA(png_ptr, info_ptr, gamma);
1591 gamma - the gamma the image was created
1592 at (PNG_INFO_gAMA)
1593
1594 png_set_sRGB(png_ptr, info_ptr, srgb_intent);
1595 srgb_intent - the rendering intent
1596 (PNG_INFO_sRGB) The presence of
1597 the sRGB chunk means that the pixel
1598 data is in the sRGB color space.
1599 This chunk also implies specific
1600 values of gAMA and cHRM. Rendering
1601 intent is the CSS-1 property that
1602 has been defined by the International
1603 Color Consortium
1604 (http://www.color.org).
1605 It can be one of
1606 PNG_SRGB_INTENT_SATURATION,
1607 PNG_SRGB_INTENT_PERCEPTUAL,
1608 PNG_SRGB_INTENT_ABSOLUTE, or
1609 PNG_SRGB_INTENT_RELATIVE.
1610
1611
1612 png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
1613 srgb_intent);
1614 srgb_intent - the rendering intent
1615 (PNG_INFO_sRGB) The presence of the
1616 sRGB chunk means that the pixel
1617 data is in the sRGB color space.
1618 This function also causes gAMA and
1619 cHRM chunks with the specific values
1620 that are consistent with sRGB to be
1621 written.
1622
1623 png_set_sBIT(png_ptr, info_ptr, sig_bit);
1624 sig_bit - the number of significant bits for
1625 (PNG_INFO_sBIT) each of the gray, red,
1626 green, and blue channels, whichever are
1627 appropriate for the given color type
1628 (png_color_16)
1629
1630 png_set_tRNS(png_ptr, info_ptr, trans, num_trans,
1631 trans_values);
1632 trans - array of transparent entries for
1633 palette (PNG_INFO_tRNS)
1634 trans_values - transparent pixel for non-paletted
1635 images (PNG_INFO_tRNS)
1636 num_trans - number of transparent entries
1637 (PNG_INFO_tRNS)
1638
1639 png_set_hIST(png_ptr, info_ptr, hist);
1640 (PNG_INFO_hIST)
1641 hist - histogram of palette (array of
1642 png_color_16)
1643
1644 png_set_tIME(png_ptr, info_ptr, mod_time);
1645 mod_time - time image was last modified
1646 (PNG_VALID_tIME)
1647
1648 png_set_bKGD(png_ptr, info_ptr, background);
1649 background - background color (PNG_VALID_bKGD)
1650
1651 png_set_text(png_ptr, info_ptr, text_ptr, num_text);
1652 text_ptr - array of png_text holding image
1653 comments
1654 text_ptr[i]->key - keyword for comment.
1655 text_ptr[i]->text - text comments for current
1656 keyword.
1657 text_ptr[i]->compression - type of compression used
1658 on "text" PNG_TEXT_COMPRESSION_NONE or
1659 PNG_TEXT_COMPRESSION_zTXt
1660 num_text - number of comments in text_ptr
1661
1662 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
1663 unit_type);
1664 offset_x - positive offset from the left
1665 edge of the screen
1666 offset_y - positive offset from the top
1667 edge of the screen
1668 unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
1669
1670 png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
1671 unit_type);
1672 res_x - pixels/unit physical resolution
1673 in x direction
1674 res_y - pixels/unit physical resolution
1675 in y direction
1676 unit_type - PNG_RESOLUTION_UNKNOWN,
1677 PNG_RESOLUTION_METER
1678
1679In PNG files, the alpha channel in an image is the level of opacity.
1680If your data is supplied as a level of transparency, you can invert the
1681alpha channel before you write it, so that 0 is fully transparent and 255
1682(in 8-bit or paletted images) or 65535 (in 16-bit images) is fully opaque,
1683with
1684
1685 png_set_invert_alpha(png_ptr);
1686
1687This must appear here instead of later with the other transformations
1688because in the case of paletted images the tRNS chunk data has to
1689be inverted before the tRNS chunk is written. If your image is not a
1690paletted image, the tRNS data (which in such cases represents a single
1691color to be rendered as transparent) won't be changed.
1692
1693A quick word about text and num_text. text is an array of png_text
1694structures. num_text is the number of valid structures in the array.
1695If you want, you can use max_text to hold the size of the array, but
1696libpng ignores it for writing (it does use it for reading). Each
1697png_text structure holds a keyword-text value, and a compression type.
1698The compression types have the same valid numbers as the compression
1699types of the image data. Currently, the only valid number is zero.
1700However, you can store text either compressed or uncompressed, unlike
1701images which always have to be compressed. So if you don't want the
1702text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
1703Until text gets around 1000 bytes, it is not worth compressing it.
1704After the text has been written out to the file, the compression type
1705is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
1706so that it isn't written out again at the end (in case you are calling
1707png_write_end() with the same struct.
1708
1709The keywords that are given in the PNG Specification are:
1710
1711 Title Short (one line) title or
1712 caption for image
1713 Author Name of image's creator
1714 Description Description of image (possibly long)
1715 Copyright Copyright notice
1716 Creation Time Time of original image creation
1717 (usually RFC 1123 format, see below)
1718 Software Software used to create the image
1719 Disclaimer Legal disclaimer
1720 Warning Warning of nature of content
1721 Source Device used to create the image
1722 Comment Miscellaneous comment; conversion
1723 from other image format
1724
1725The keyword-text pairs work like this. Keywords should be short
1726simple descriptions of what the comment is about. Some typical
1727keywords are found in the PNG specification, as is some recommendations
1728on keywords. You can repeat keywords in a file. You can even write
1729some text before the image and some after. For example, you may want
1730to put a description of the image before the image, but leave the
1731disclaimer until after, so viewers working over modem connections
1732don't have to wait for the disclaimer to go over the modem before
1733they start seeing the image. Finally, keywords should be full
1734words, not abbreviations. Keywords and text are in the ISO 8859-1
1735(Latin-1) character set (a superset of regular ASCII) and can not
1736contain NUL characters, and should not contain control or other
1737unprintable characters. To make the comments widely readable, stick
1738with basic ASCII, and avoid machine specific character set extensions
1739like the IBM-PC character set. The keyword must be present, but
1740you can leave off the text string on non-compressed pairs.
1741Compressed pairs must have a text string, as only the text string
1742is compressed anyway, so the compression would be meaningless.
1743
1744PNG supports modification time via the png_time structure. Two
1745conversion routines are proved, png_convert_from_time_t() for
1746time_t and png_convert_from_struct_tm() for struct tm. The
1747time_t routine uses gmtime(). You don't have to use either of
1748these, but if you wish to fill in the png_time structure directly,
1749you should provide the time in universal time (GMT) if possible
1750instead of your local time. Note that the year number is the full
1751year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and
1752that months start with 1.
1753
1754If you want to store the time of the original image creation, you should
1755use a plain tEXt chunk with the "Creation Time" keyword. This is
1756necessary because the "creation time" of a PNG image is somewhat vague,
1757depending on whether you mean the PNG file, the time the image was
1758created in a non-PNG format, a still photo from which the image was
1759scanned, or possibly the subject matter itself. In order to facilitate
1760machine-readable dates, it is recommended that the "Creation Time"
1761tEXt chunk use RFC 1123 format dates (e.g. 22 May 1997 18:07:10 GMT"),
1762although this isn't a requirement. Unlike the tIME chunk, the
1763"Creation Time" tEXt chunk is not expected to be automatically changed
1764by the software. To facilitate the use of RFC 1123 dates, a function
1765png_convert_to_rfc1123(png_timep) is provided to convert from PNG
1766time to an RFC 1123 format string.
1767
1768You are now ready to write all the file information up to the actual
1769image data. You do this with a call to png_write_info().
1770
1771 png_write_info(png_ptr, info_ptr);
1772
1773After you've written the file information, you can set up the library
1774to handle any special transformations of the image data. The various
1775ways to transform the data will be described in the order that they
1776should occur. This is important, as some of these change the color
1777type and/or bit depth of the data, and some others only work on
1778certain color types and bit depths. Even though each transformation
1779checks to see if it has data that it can do something with, you should
1780make sure to only enable a transformation if it will be valid for the
1781data. For example, don't swap red and blue on grayscale data.
1782
1783PNG files store RGB pixels packed into 3 bytes. This code tells
1784the library to expect input data with 4 bytes per pixel
1785
1786 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1787
1788where the 0 is the value that will be put in the 4th byte, and the
1789location is either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending
1790upon whether the filler byte is stored XRGB or RGBX.
1791
1792PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
1793they can, resulting in, for example, 8 pixels per byte for 1 bit files.
1794If the data is supplied at 1 pixel per byte, use this code, which will
1795correctly pack the pixels into a single byte:
1796
1797 png_set_packing(png_ptr);
1798
1799PNG files reduce possible bit depths to 1, 2, 4, 8, and 16. If your
1800data is of another bit depth, you can write an sBIT chunk into the
1801file so that decoders can get the original data if desired.
1802
1803 /* Set the true bit depth of the image data */
1804 if (color_type & PNG_COLOR_MASK_COLOR)
1805 {
1806 sig_bit.red = true_bit_depth;
1807 sig_bit.green = true_bit_depth;
1808 sig_bit.blue = true_bit_depth;
1809 }
1810 else
1811 {
1812 sig_bit.gray = true_bit_depth;
1813 }
1814 if (color_type & PNG_COLOR_MASK_ALPHA)
1815 {
1816 sig_bit.alpha = true_bit_depth;
1817 }
1818
1819 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
1820
1821If the data is stored in the row buffer in a bit depth other than
1822one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG),
1823this will scale the values to appear to be the correct bit depth as
1824is required by PNG.
1825
1826 png_set_shift(png_ptr, &sig_bit);
1827
1828PNG files store 16 bit pixels in network byte order (big-endian,
1829ie. most significant bits first). This code would be used if they are
1830supplied the other way (little-endian, i.e. least significant bits
1831first, the way PCs store them):
1832
1833 if (bit_depth > 8)
1834 png_set_swap(png_ptr);
1835
1836If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
1837need to change the order the pixels are packed into bytes, you can use:
1838
1839 if (bit_depth < 8)
1840 png_set_packswap(png_ptr);
1841
1842PNG files store 3 color pixels in red, green, blue order. This code
1843would be used if they are supplied as blue, green, red:
1844
1845 png_set_bgr(png_ptr);
1846
1847PNG files describe monochrome as black being zero and white being
1848one. This code would be used if the pixels are supplied with this reversed
1849(black being one and white being zero):
1850
1851 png_set_invert_mono(png_ptr);
1852
1853Finally, you can write your own transformation function if none of
1854the existing ones meets your needs. This is done by setting a callback
1855with
1856
1857 png_set_write_user_transform_fn(png_ptr,
1858 write_transform_fn);
1859
1860You must supply the function
1861
1862 void write_transform_fn(png_ptr ptr, row_info_ptr
1863 row_info, png_bytep data)
1864
1865See pngtest.c for a working example. Your function will be called
1866before any of the other transformations have been processed.
1867
1868It is possible to have libpng flush any pending output, either manually,
1869or automatically after a certain number of lines have been written. To
1870flush the output stream a single time call:
1871
1872 png_write_flush(png_ptr);
1873
1874and to have libpng flush the output stream periodically after a certain
1875number of scanlines have been written, call:
1876
1877 png_set_flush(png_ptr, nrows);
1878
1879Note that the distance between rows is from the last time png_write_flush()
1880was called, or the first row of the image if it has never been called.
1881So if you write 50 lines, and then png_set_flush 25, it will flush the
1882output on the next scanline, and every 25 lines thereafter, unless
1883png_write_flush() is called before 25 more lines have been written.
1884If nrows is too small (less than about 10 lines for a 640 pixel wide
1885RGB image) the image compression may decrease noticeably (although this
1886may be acceptable for real-time applications). Infrequent flushing will
1887only degrade the compression performance by a few percent over images
1888that do not use flushing.
1889
1890That's it for the transformations. Now you can write the image data.
1891The simplest way to do this is in one function call. If have the
1892whole image in memory, you can just call png_write_image() and libpng
1893will write the image. You will need to pass in an array of pointers to
1894each row. This function automatically handles interlacing, so you don't
1895need to call png_set_interlace_handling() or call this function multiple
1896times, or any of that other stuff necessary with png_write_rows().
1897
1898 png_write_image(png_ptr, row_pointers);
1899
1900where row_pointers is:
1901
1902 png_bytef *row_pointers[height];
1903
1904You can point to void or char or whatever you use for pixels.
1905
1906If you can't want to write the whole image at once, you can
1907use png_write_rows() instead. If the file is not interlaced,
1908this is simple:
1909
1910 png_write_rows(png_ptr, row_pointers,
1911 number_of_rows);
1912
1913row_pointers is the same as in the png_write_image() call.
1914
1915If you are just writing one row at a time, you can do this with
1916row_pointers:
1917
1918 png_bytep row_pointer = row;
1919
1920 png_write_row(png_ptr, &row_pointer);
1921
1922When the file is interlaced, things can get a good deal more
1923complicated. The only currently (as of February 1998 -- PNG Specification
1924version 1.0, dated October 1996) defined interlacing scheme for PNG files
1925is the "Adam7" interlace scheme, that breaks down an
1926image into seven smaller images of varying size. libpng will build
1927these images for you, or you can do them yourself. If you want to
1928build them yourself, see the PNG specification for details of which
1929pixels to write when.
1930
1931If you don't want libpng to handle the interlacing details, just
1932use png_set_interlace_handling() and call png_write_rows() the
1933correct number of times to write all seven sub-images.
1934
1935If you want libpng to build the sub-images, call this before you start
1936writing any rows:
1937
1938 number_of_passes =
1939 png_set_interlace_handling(png_ptr);
1940
1941This will return the number of passes needed. Currently, this
1942is seven, but may change if another interlace type is added.
1943
1944Then write the complete image number_of_passes times.
1945
1946 png_write_rows(png_ptr, row_pointers,
1947 number_of_rows);
1948
1949As some of these rows are not used, and thus return immediately,
1950you may want to read about interlacing in the PNG specification,
1951and only update the rows that are actually used.
1952
1953After you are finished writing the image, you should finish writing
1954the file. If you are interested in writing comments or time, you should
1955pass an appropriately filled png_info pointer. If you are not interested,
1956you can pass NULL.
1957
1958 png_write_end(png_ptr, info_ptr);
1959
1960When you are done, you can free all memory used by libpng like this:
1961
1962 png_destroy_write_struct(&png_ptr, &info_ptr);
1963
1964You must free any data you allocated for info_ptr, such as comments,
1965palette, or histogram, before the call to png_destroy_write_struct();
1966
1967For a more compact example of writing a PNG image, see the file example.c.
1968
1969
1970.SH V. Modifying/Customizing libpng:
1971
1972There are two issues here. The first is changing how libpng does
1973standard things like memory allocation, input/output, and error handling.
1974The second deals with more complicated things like adding new chunks,
1975adding new transformations, and generally changing how libpng works.
1976
1977All of the memory allocation, input/output, and error handling in libpng
1978goes through callbacks which are user settable. The default routines are
1979in pngmem.c, pngrio.c, pngwio.c, and pngerror.c respectively. To change
1980these functions, call the appropriate png_set_???_fn() function.
1981
1982Memory allocation is done through the functions png_large_malloc(),
1983png_malloc(), png_realloc(), png_large_free(), and png_free(). These
1984currently just call the standard C functions. The large functions must
1985handle exactly 64K, but they don't have to handle more than that. If
1986your pointers can't access more then 64K at a time, you will want to set
1987MAXSEG_64K in zlib.h. Since it is unlikely that the method of handling
1988memory allocation on a platform will change between applications, these
1989functions must be modified in the library at compile time.
1990
1991Input/Output in libpng is done through png_read() and png_write(),
1992which currently just call fread() and fwrite(). The FILE * is stored in
1993png_struct and is initialized via png_init_io(). If you wish to change
1994the method of I/O, the library supplies callbacks that you can set
1995through the function png_set_read_fn() and png_set_write_fn() at run
1996time, instead of calling the png_init_io() function. These functions
1997also provide a void pointer that can be retrieved via the function
1998png_get_io_ptr(). For example:
1999
2000 png_set_read_fn(png_structp png_ptr,
2001 voidp io_ptr, png_rw_ptr read_data_fn)
2002
2003 png_set_write_fn(png_structp png_ptr,
2004 voidp io_ptr, png_rw_ptr write_data_fn,
2005 png_flush_ptr output_flush_fn);
2006
2007 voidp io_ptr = png_get_io_ptr(png_ptr);
2008
2009The replacement I/O functions should have prototypes as follows:
2010
2011 void user_read_data(png_structp png_ptr,
2012 png_bytep data, png_uint_32 length);
2013 void user_write_data(png_structp png_ptr,
2014 png_bytep data, png_uint_32 length);
2015 void user_flush_data(png_structp png_ptr);
2016
2017Supplying NULL for the read, write, or flush functions sets them back
2018to using the default C stream functions. It is an error to read from
2019a write stream, and vice versa.
2020
2021Error handling in libpng is done through png_error() and png_warning().
2022Errors handled through png_error() are fatal, meaning that png_error()
2023should never return to its caller. Currently, this is handled via
2024setjmp() and longjmp(), but you could change this to do things like
2025exit() if you should wish. On non-fatal errors, png_warning() is called
2026to print a warning message, and then control returns to the calling code.
2027By default png_error() and png_warning() print a message on stderr via
2028fprintf() unless the library is compiled with PNG_NO_STDIO defined. If
2029you wish to change the behavior of the error functions, you will need to
2030set up your own message callbacks. These functions are normally supplied
2031at the time that the png_struct is created. It is also possible to change
2032these functions after png_create_???_struct() has been called by calling:
2033
2034 png_set_error_fn(png_structp png_ptr,
2035 png_voidp error_ptr, png_error_ptr error_fn,
2036 png_error_ptr warning_fn);
2037
2038 png_voidp error_ptr = png_get_error_ptr(png_ptr);
2039
2040If NULL is supplied for either error_fn or warning_fn, then the libpng
2041default function will be used, calling fprintf() and/or longjmp() if a
2042problem is encountered. The replacement error functions should have
2043parameters as follows:
2044
2045 void user_error_fn(png_structp png_ptr,
2046 png_const_charp error_msg);
2047 void user_warning_fn(png_structp png_ptr,
2048 png_const_charp warning_msg);
2049
2050The motivation behind using setjmp() and longjmp() is the C++ throw and
2051catch exception handling methods. This makes the code much easier to write,
2052as there is no need to check every return code of every function call.
2053However, there are some uncertainties about the status of local variables
2054after a longjmp, so the user may want to be careful about doing anything after
2055setjmp returns non-zero besides returning itself. Consult your compiler
2056documentation for more details.
2057
2058If you need to read or write custom chunks, you will need to get deeper
2059into the libpng code, as a mechanism has not yet been supplied for user
2060callbacks with custom chunks. First, read the PNG specification, and have
2061a first level of understanding of how it works. Pay particular attention
2062to the sections that describe chunk names, and look at how other chunks
2063were designed, so you can do things similarly. Second, check out the
2064sections of libpng that read and write chunks. Try to find a chunk that
2065is similar to yours and copy off of it. More details can be found in the
2066comments inside the code. A way of handling unknown chunks in a generic
2067method, potentially via callback functions, would be best.
2068
2069If you wish to write your own transformation for the data, look through
2070the part of the code that does the transformations, and check out some of
2071the simpler ones to get an idea of how they work. Try to find a similar
2072transformation to the one you want to add and copy off of it. More details
2073can be found in the comments inside the code itself.
2074
2075Configuring for 16 bit platforms:
2076
2077You may need to change the png_large_malloc() and png_large_free()
2078routines in pngmem.c, as these are required to allocate 64K, although
2079there is already support for many of the common DOS compilers. Also,
2080you will want to look into zconf.h to tell zlib (and thus libpng) that
2081it cannot allocate more then 64K at a time. Even if you can, the memory
2082won't be accessible. So limit zlib and libpng to 64K by defining MAXSEG_64K.
2083
2084Configuring for DOS:
2085
2086For DOS users which only have access to the lower 640K, you will
2087have to limit zlib's memory usage via a png_set_compression_mem_level()
2088call. See zlib.h or zconf.h in the zlib library for more information.
2089
2090Configuring for Medium Model:
2091
2092Libpng's support for medium model has been tested on most of the popular
2093compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
2094defined, and FAR gets defined to far in pngconf.h, and you should be
2095all set. Everything in the library (except for zlib's structure) is
2096expecting far data. You must use the typedefs with the p or pp on
2097the end for pointers (or at least look at them and be careful). Make
2098note that the row's of data are defined as png_bytepp which is a
2099unsigned char far * far *.
2100
2101Configuring for gui/windowing platforms:
2102
2103You will need to write new error and warning functions that use the GUI
2104interface, as described previously, and set them to be the error and
2105warning functions at the time that png_create_???_struct() is called,
2106in order to have them available during the structure initialization.
2107They can be changed later via png_set_error_fn(). On some compilers,
2108you may also have to change the memory allocators (png_malloc, etc.).
2109
2110Configuring for compiler xxx:
2111
2112All includes for libpng are in pngconf.h. If you need to add/change/delete
2113an include, this is the place to do it. The includes that are not
2114needed outside libpng are protected by the PNG_INTERNAL definition,
2115which is only defined for those routines inside libpng itself. The
2116files in libpng proper only include png.h, which includes pngconf.h.
2117
2118Configuring zlib:
2119
2120There are special functions to configure the compression. Perhaps the
2121most useful one changes the compression level, which currently uses
2122input compression values in the range 0 - 9. The library normally
2123uses the default compression level (Z_DEFAULT_COMPRESSION = 6). Tests
2124have shown that for a large majority of images, compression values in
2125the range 3-6 compress nearly as well as higher levels, and do so much
2126faster. For online applications it may be desirable to have maximum speed
2127(Z_BEST_SPEED = 1). With versions of zlib after v0.99, you can also
2128specify no compression (Z_NO_COMPRESSION = 0), but this would create
2129files larger than just storing the raw bitmap. You can specify the
2130compression level by calling:
2131
2132 png_set_compression_level(png_ptr, level);
2133
2134Another useful one is to reduce the memory level used by the library.
2135The memory level defaults to 8, but it can be lowered if you are
2136short on memory (running DOS, for example, where you only have 640K).
2137
2138 png_set_compression_mem_level(png_ptr, level);
2139
2140The other functions are for configuring zlib. They are not recommended
2141for normal use and may result in writing an invalid PNG file. See
2142zlib.h for more information on what these mean.
2143
2144 png_set_compression_strategy(png_ptr,
2145 strategy);
2146 png_set_compression_window_bits(png_ptr,
2147 window_bits);
2148 png_set_compression_method(png_ptr, method);
2149
2150Controlling row filtering:
2151
2152If you want to control whether libpng uses filtering or not, which
2153filters are used, and how it goes about picking row filters, you
2154can call one of these functions. The selection and configuration
2155of row filters can have a significant impact on the size and
2156encoding speed and a somewhat lesser impact on the decoding speed
2157of an image. Filtering is enabled by default for RGB and grayscale
2158images (with and without alpha), and for 8-bit paletted images, but
2159not for paletted images with bit depths less than 8 bits/pixel.
2160
2161The 'method' parameter sets the main filtering method, which is
2162currently only '0' in the PNG 1.0 specification. The 'filters'
2163parameter sets which filter(s), if any, should be used for each
2164scanline. Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
2165to turn filtering on and off, respectively.
2166
2167Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
2168PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
2169ORed together '|' to specify one or more filters to use. These
2170filters are described in more detail in the PNG specification. If
2171you intend to change the filter type during the course of writing
2172the image, you should start with flags set for all of the filters
2173you intend to use so that libpng can initialize its internal
2174structures appropriately for all of the filter types.
2175
2176 filters = PNG_FILTER_NONE | PNG_FILTER_SUB
2177 | PNG_FILTER_UP;
2178 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
2179 filters);
2180
2181It is also possible to influence how libpng chooses from among the
2182available filters. This is done in two ways - by telling it how
2183important it is to keep the same filter for successive rows, and
2184by telling it the relative computational costs of the filters.
2185
2186 double weights[3] = {1.5, 1.3, 1.1},
2187 costs[PNG_FILTER_VALUE_LAST] =
2188 {1.0, 1.3, 1.3, 1.5, 1.7};
2189
2190 png_set_filter_selection(png_ptr,
2191 PNG_FILTER_SELECTION_WEIGHTED, 3,
2192 weights, costs);
2193
2194The weights are multiplying factors which indicate to libpng that row
2195should be the same for successive rows unless another row filter is that
2196many times better than the previous filter. In the above example, if
2197the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
2198"sum of absolute differences" 1.5 x 1.3 times higher than other filters
2199and still be chosen, while the NONE filter could have a sum 1.1 times
2200higher than other filters and still be chosen. Unspecified weights are
2201taken to be 1.0, and the specified weights should probably be declining
2202like those above in order to emphasize recent filters over older filters.
2203
2204The filter costs specify for each filter type a relative decoding cost
2205to be considered when selecting row filters. This means that filters
2206with higher costs are less likely to be chosen over filters with lower
2207costs, unless their "sum of absolute differences" is that much smaller.
2208The costs do not necessarily reflect the exact computational speeds of
2209the various filters, since this would unduly influence the final image
2210size.
2211
2212Note that the numbers above were invented purely for this example and
2213are given only to help explain the function usage. Little testing has
2214been done to find optimum values for either the costs or the weights.
2215
2216Removing unwanted object code:
2217
2218There are a bunch of #define's in pngconf.h that control what parts of
2219libpng are compiled. All the defines end in _SUPPORTED. If you are
2220never going to use an ability, you can change the #define to #undef
2221before recompiling libpng and save yourself code and data space.
2222You can also turn a number of them off en masse with a compiler directive
2223that defines PNG_READ[or WRITE]_TRANSFORMS_NOT_SUPPORTED, or
2224PNG_READ[or WRITE]_ANCILLARY_CHUNKS_NOT_SUPPORTED, or all four,
2225along with directives to turn on any of the capabilities that you do
2226want. The PNG_READ[or WRITE]_TRANSFORMS_NOT_SUPPORTED directives disable
2227the extra transformations but still leave the library fully capable of reading
2228and writing PNG files with all known public chunks [except for sPLT].
2229Use of the PNG_READ[or WRITE]_ANCILLARY_CHUNKS_NOT_SUPPORTED directive
2230produces a library that is incapable of reading or writing ancillary chunks.
2231If you are not using the progressive reading capability, you can
2232turn that off with PNG_PROGRESSIVE_READ_NOT_SUPPORTED (don't confuse
2233this with the INTERLACING capability, which you'll still have).
2234
2235All the reading and writing specific code are in separate files, so the
2236linker should only grab the files it needs. However, if you want to
2237make sure, or if you are building a stand alone library, all the
2238reading files start with pngr and all the writing files start with
2239pngw. The files that don't match either (like png.c, pngtrans.c, etc.)
2240are used for both reading and writing, and always need to be included.
2241The progressive reader is in pngpread.c
2242
2243If you are creating or distributing a dynamically linked library (a .so
2244or DLL file), you should not remove or disable any parts of the library,
2245as this will cause applications linked with different versions of the
2246library to fail if they call functions not available in your library.
2247The size of the library itself should not be an issue, because only
2248those sections which are actually used will be loaded into memory.
2249
2250
2251Changes to Libpng from version 0.88
2252
2253It should be noted that versions of libpng later than 0.96 are not
2254distributed by the original libpng author, Guy Schalnat, nor by
2255Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
2256distributed versions 0.89 through 0.96, but rather by another member
2257of the original PNG Group, Glenn Randers-Pehrson. Guy and Andreas are
2258still alive and well, but they have moved on to other things.
2259
2260The old libpng functions png_read_init(), png_write_init(),
2261png_info_init(), png_read_destroy(), and png_write_destory() have been
2262moved to PNG_INTERNAL in version 0.95 to discourage their use. The
2263preferred method of creating and initializing the libpng structures is
2264via the png_create_read_struct(), png_create_write_struct(), and
2265png_create_info_struct() because they isolate the size of the structures
2266from the application, allow version error checking, and also allow the
2267use of custom error handling routines during the initialization, which
2268the old functions do not. The functions png_read_destroy() and
2269png_write_destroy() do not actually free the memory that libpng
2270allocated for these structs, but just reset the data structures, so they
2271can be used instead of png_destroy_read_struct() and
2272png_destroy_write_struct() if you feel there is too much system overhead
2273allocating and freeing the png_struct for each image read.
2274
2275Setting the error callbacks via png_set_message_fn() before
2276png_read_init() as was suggested in libpng-0.88 is no longer supported
2277because this caused applications which do not use custom error functions
2278to fail if the png_ptr was not initialized to zero. It is still possible
2279to set the error callbacks AFTER png_read_init(), or to change them with
2280png_set_error_fn(), which is essentially the same function, but with a
2281new name to force compilation errors with applications that try to use
2282the old method.
2283
2284.SH NOTE
2285
2286Note about libpng version numbers:
2287
2288Due to various miscommunications, unforeseen code incompatibilities
2289and occasional factors outside the authors' control, version numbering
2290on the library has not always been consistent and straightforward.
2291The following table summarizes matters since version 0.89c, which was
2292the first widely used release:
2293
2294 source png.h png.h shared-lib
2295 version string int version
2296 ------- ------ ------ ----------
2297 0.89c 0.89 89 1.0.89
2298 0.90 0.90 90 0.90 [should be 2.0.90]
2299 0.95 0.95 95 0.95 [should be 2.0.95]
2300 0.96 0.96 96 0.96 [should be 2.0.96]
2301 0.97b 1.00.97 97 1.0.1 [should be 2.0.97]
2302 0.97c 0.97 97 2.0.97
2303 0.98 0.98 98 2.0.98
2304 0.99 0.99 98 2.0.99
2305 0.99a-m 0.99 99 2.0.99
2306 1.00 1.00 100 2.1.0 [int should be 10000]
2307 1.0.0 1.0.0 100 2.1.0 [int should be 10000]
2308 1.0.1 1.0.1 10001 2.1.0
2309
2310Henceforth the source version will match the shared-library
2311minor and patch numbers; the shared-library major version number will be
2312used for changes in backward compatibility, as it is intended.
2313The PNG_PNGLIB_VER macro, which is not used within libpng but
2314is available for applications, is an unsigned integer of the form
2315xyyzz corresponding to the source version x.y.z (leading zeros in y and z).
2316
2317.SH "SEE ALSO"
2318libpngpf(3), png(5)
2319.LP
2320.IR libpng :
2321.IP
2322ftp://ftp.uu.net/graphics/png
2323http://www.cdrom.com/pub/png
2324
2325.LP
2326.IR zlib :
2327.IP
2328(generally) at the same location as
2329.I libpng
2330or at
2331.br
2332ftp://ftp.uu.net/pub/archiving/zip/zlib
2333.br
2334http://www.cdrom.com/pub/infozip/zlib
2335
2336.LP
2337.IR PNG specification: RFC 2083
2338.IP
2339(generally) at the same location as
2340.I libpng
2341or at
2342.br
2343ftp://ds.internic.net/rfc/rfc2083.txt
2344.br
2345or (as a W3C Recommendation) at
2346.br
2347http://www.w3.org/TR/REC-png.html
2348
2349.LP
2350In the case of any inconsistency between the PNG specification
2351and this library, the specification takes precedence.
2352
2353.SH AUTHORS
2354This man page: Glenn Randers-Pehrson
2355<randeg@alumni.rpi.edu>
2356
2357Contributing Authors: John Bowler, Kevin Bracey, Sam Bushell, Andreas Dilger,
2358Magnus Holmgren, Tom Lane, Dave Martindale, Glenn Randers-Pehrson,
2359Greg Roelofs, Guy Eric Schalnat, Paul Schmidt, Tom Tanner, Willem van
2360Schaik, Tim Wegner.
2361<png-implement@dworkin.wustl.edu>
2362
2363The contributing authors would like to thank all those who helped
2364with testing, bug fixes, and patience. This wouldn't have been
2365possible without all of you.
2366
2367Thanks to Frank J. T. Wojcik for helping with the documentation.
2368
2369Libpng version 1.0.1 March 15, 1998:
2370Initially created in 1995 by Guy Eric Schalnat, then of Group 42, Inc.
2371Currently maintained by Glenn Randers-Pehrson (randeg@alumni.rpi.edu).
2372
2373Supported by the PNG development group
2374.br
2375(png-implement@dworkin.wustl.edu).
2376
2377.SH COPYRIGHT NOTICE:
2378
2379The PNG Reference Library (libpng) is supplied "AS IS". The Contributing
2380Authors and Group 42, Inc. disclaim all warranties, expressed or implied,
2381including, without limitation, the warranties of merchantability and of
2382fitness for any purpose. The Contributing Authors and Group 42, Inc.
2383assume no liability for direct, indirect, incidental, special, exemplary,
2384or consequential damages, which may result from the use of the PNG
2385Reference Library, even if advised of the possibility of such damage.
2386
2387Permission is hereby granted to use, copy, modify, and distribute this
2388source code, or portions hereof, for any purpose, without fee, subject
2389to the following restrictions:
2390
2391 1. The origin of this source code must not be
2392 misrepresented.
2393
2394 2. Altered versions must be plainly marked as such
2395 and must not be misrepresented as being the
2396 original source.
2397
2398 3. This Copyright notice may not be removed or
2399 altered from any source or altered source
2400 distribution.
2401
2402The Contributing Authors and Group 42, Inc. specifically permit, without
2403fee, and encourage the use of this source code as a component to
2404supporting the PNG file format in commercial products. If you use this
2405source code in a product, acknowledgment is not required but would be
2406appreciated.
2407
2408.\" end of man page
2409