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