Subversion Repositories Kolibri OS

Rev

Details | Last modification | View Log | RSS feed

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