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