/src/FreeImage/Source/LibPNG/libpng-manual.txt

https://bitbucket.org/cabalistic/ogredeps/ · Plain Text · 4628 lines · 3570 code · 1058 blank · 0 comment · 0 complexity · 701b19a436624e206255c9cb8c4169b1 MD5 · raw file

Large files are truncated click here to view the full file

  1. libpng-manual.txt - A description on how to use and modify libpng
  2. libpng version 1.5.9 - February 18, 2012
  3. Updated and distributed by Glenn Randers-Pehrson
  4. <glennrp at users.sourceforge.net>
  5. Copyright (c) 1998-2011 Glenn Randers-Pehrson
  6. This document is released under the libpng license.
  7. For conditions of distribution and use, see the disclaimer
  8. and license in png.h
  9. Based on:
  10. libpng versions 0.97, January 1998, through 1.5.9 - February 18, 2012
  11. Updated and distributed by Glenn Randers-Pehrson
  12. Copyright (c) 1998-2011 Glenn Randers-Pehrson
  13. libpng 1.0 beta 6 version 0.96 May 28, 1997
  14. Updated and distributed by Andreas Dilger
  15. Copyright (c) 1996, 1997 Andreas Dilger
  16. libpng 1.0 beta 2 - version 0.88 January 26, 1996
  17. For conditions of distribution and use, see copyright
  18. notice in png.h. Copyright (c) 1995, 1996 Guy Eric
  19. Schalnat, Group 42, Inc.
  20. Updated/rewritten per request in the libpng FAQ
  21. Copyright (c) 1995, 1996 Frank J. T. Wojcik
  22. December 18, 1995 & January 20, 1996
  23. I. Introduction
  24. This file describes how to use and modify the PNG reference library
  25. (known as libpng) for your own use. There are five sections to this
  26. file: introduction, structures, reading, writing, and modification and
  27. configuration notes for various special platforms. In addition to this
  28. file, example.c is a good starting point for using the library, as
  29. it is heavily commented and should include everything most people
  30. will need. We assume that libpng is already installed; see the
  31. INSTALL file for instructions on how to install libpng.
  32. For examples of libpng usage, see the files "example.c", "pngtest.c",
  33. and the files in the "contrib" directory, all of which are included in
  34. the libpng distribution.
  35. Libpng was written as a companion to the PNG specification, as a way
  36. of reducing the amount of time and effort it takes to support the PNG
  37. file format in application programs.
  38. The PNG specification (second edition), November 2003, is available as
  39. a W3C Recommendation and as an ISO Standard (ISO/IEC 15948:2003 (E)) at
  40. <http://www.w3.org/TR/2003/REC-PNG-20031110/
  41. The W3C and ISO documents have identical technical content.
  42. The PNG-1.2 specification is available at
  43. <http://www.libpng.org/pub/png/documents/>. It is technically equivalent
  44. to the PNG specification (second edition) but has some additional material.
  45. The PNG-1.0 specification is available
  46. as RFC 2083 <http://www.libpng.org/pub/png/documents/> and as a
  47. W3C Recommendation <http://www.w3.org/TR/REC.png.html>.
  48. Some additional chunks are described in the special-purpose public chunks
  49. documents at <http://www.libpng.org/pub/png/documents/>.
  50. Other information
  51. about PNG, and the latest version of libpng, can be found at the PNG home
  52. page, <http://www.libpng.org/pub/png/>.
  53. Most users will not have to modify the library significantly; advanced
  54. users may want to modify it more. All attempts were made to make it as
  55. complete as possible, while keeping the code easy to understand.
  56. Currently, this library only supports C. Support for other languages
  57. is being considered.
  58. Libpng has been designed to handle multiple sessions at one time,
  59. to be easily modifiable, to be portable to the vast majority of
  60. machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
  61. to use. The ultimate goal of libpng is to promote the acceptance of
  62. the PNG file format in whatever way possible. While there is still
  63. work to be done (see the TODO file), libpng should cover the
  64. majority of the needs of its users.
  65. Libpng uses zlib for its compression and decompression of PNG files.
  66. Further information about zlib, and the latest version of zlib, can
  67. be found at the zlib home page, <http://www.info-zip.org/pub/infozip/zlib/>.
  68. The zlib compression utility is a general purpose utility that is
  69. useful for more than PNG files, and can be used without libpng.
  70. See the documentation delivered with zlib for more details.
  71. You can usually find the source files for the zlib utility wherever you
  72. find the libpng source files.
  73. Libpng is thread safe, provided the threads are using different
  74. instances of the structures. Each thread should have its own
  75. png_struct and png_info instances, and thus its own image.
  76. Libpng does not protect itself against two threads using the
  77. same instance of a structure.
  78. II. Structures
  79. There are two main structures that are important to libpng, png_struct
  80. and png_info. Both are internal structures that are no longer exposed
  81. in the libpng interface (as of libpng 1.5.0).
  82. The png_info structure is designed to provide information about the
  83. PNG file. At one time, the fields of png_info were intended to be
  84. directly accessible to the user. However, this tended to cause problems
  85. with applications using dynamically loaded libraries, and as a result
  86. a set of interface functions for png_info (the png_get_*() and png_set_*()
  87. functions) was developed, and direct access to the png_info fields was
  88. deprecated..
  89. The png_struct structure is the object used by the library to decode a
  90. single image. As of 1.5.0 this structure is also not exposed.
  91. Almost all libpng APIs require a pointer to a png_struct as the first argument.
  92. Many (in particular the png_set and png_get APIs) also require a pointer
  93. to png_info as the second argument. Some application visible macros
  94. defined in png.h designed for basic data access (reading and writing
  95. integers in the PNG format) don't take a png_info pointer, but it's almost
  96. always safe to assume that a (png_struct*) has to be passed to call an API
  97. function.
  98. You can have more than one png_info structure associated with an image,
  99. as illustrated in pngtest.c, one for information valid prior to the
  100. IDAT chunks and another (called "end_info" below) for things after them.
  101. The png.h header file is an invaluable reference for programming with libpng.
  102. And while I'm on the topic, make sure you include the libpng header file:
  103. #include <png.h>
  104. and also (as of libpng-1.5.0) the zlib header file, if you need it:
  105. #include <zlib.h>
  106. Types
  107. The png.h header file defines a number of integral types used by the
  108. APIs. Most of these are fairly obvious; for example types corresponding
  109. to integers of particular sizes and types for passing color values.
  110. One exception is how non-integral numbers are handled. For application
  111. convenience most APIs that take such numbers have C (double) arguments,
  112. however internally PNG, and libpng, use 32 bit signed integers and encode
  113. the value by multiplying by 100,000. As of libpng 1.5.0 a convenience
  114. macro PNG_FP_1 is defined in png.h along with a type (png_fixed_point)
  115. which is simply (png_int_32).
  116. All APIs that take (double) arguments also have a matching API that
  117. takes the corresponding fixed point integer arguments. The fixed point
  118. API has the same name as the floating point one with "_fixed" appended.
  119. The actual range of values permitted in the APIs is frequently less than
  120. the full range of (png_fixed_point) (-21474 to +21474). When APIs require
  121. a non-negative argument the type is recorded as png_uint_32 above. Consult
  122. the header file and the text below for more information.
  123. Special care must be take with sCAL chunk handling because the chunk itself
  124. uses non-integral values encoded as strings containing decimal floating point
  125. numbers. See the comments in the header file.
  126. Configuration
  127. The main header file function declarations are frequently protected by C
  128. preprocessing directives of the form:
  129. #ifdef PNG_feature_SUPPORTED
  130. declare-function
  131. #endif
  132. ...
  133. #ifdef PNG_feature_SUPPORTED
  134. use-function
  135. #endif
  136. The library can be built without support for these APIs, although a
  137. standard build will have all implemented APIs. Application programs
  138. should check the feature macros before using an API for maximum
  139. portability. From libpng 1.5.0 the feature macros set during the build
  140. of libpng are recorded in the header file "pnglibconf.h" and this file
  141. is always included by png.h.
  142. If you don't need to change the library configuration from the default, skip to
  143. the next section ("Reading").
  144. Notice that some of the makefiles in the 'scripts' directory and (in 1.5.0) all
  145. of the build project files in the 'projects' directory simply copy
  146. scripts/pnglibconf.h.prebuilt to pnglibconf.h. This means that these build
  147. systems do not permit easy auto-configuration of the library - they only
  148. support the default configuration.
  149. The easiest way to make minor changes to the libpng configuration when
  150. auto-configuration is supported is to add definitions to the command line
  151. using (typically) CPPFLAGS. For example:
  152. CPPFLAGS=-DPNG_NO_FLOATING_ARITHMETIC
  153. will change the internal libpng math implementation for gamma correction and
  154. other arithmetic calculations to fixed point, avoiding the need for fast
  155. floating point support. The result can be seen in the generated pnglibconf.h -
  156. make sure it contains the changed feature macro setting.
  157. If you need to make more extensive configuration changes - more than one or two
  158. feature macro settings - you can either add -DPNG_USER_CONFIG to the build
  159. command line and put a list of feature macro settings in pngusr.h or you can set
  160. DFA_XTRA (a makefile variable) to a file containing the same information in the
  161. form of 'option' settings.
  162. A. Changing pnglibconf.h
  163. A variety of methods exist to build libpng. Not all of these support
  164. reconfiguration of pnglibconf.h. To reconfigure pnglibconf.h it must either be
  165. rebuilt from scripts/pnglibconf.dfa using awk or it must be edited by hand.
  166. Hand editing is achieved by copying scripts/pnglibconf.h.prebuilt to
  167. pnglibconf.h and changing the lines defining the supported features, paying
  168. very close attention to the 'option' information in scripts/pnglibconf.dfa
  169. that describes those features and their requirements. This is easy to get
  170. wrong.
  171. B. Configuration using DFA_XTRA
  172. Rebuilding from pnglibconf.dfa is easy if a functioning 'awk', or a later
  173. variant such as 'nawk' or 'gawk', is available. The configure build will
  174. automatically find an appropriate awk and build pnglibconf.h.
  175. The scripts/pnglibconf.mak file contains a set of make rules for doing the
  176. same thing if configure is not used, and many of the makefiles in the scripts
  177. directory use this approach.
  178. When rebuilding simply write a new file containing changed options and set
  179. DFA_XTRA to the name of this file. This causes the build to append the new file
  180. to the end of scripts/pnglibconf.dfa. The pngusr.dfa file should contain lines
  181. of the following forms:
  182. everything = off
  183. This turns all optional features off. Include it at the start of pngusr.dfa to
  184. make it easier to build a minimal configuration. You will need to turn at least
  185. some features on afterward to enable either reading or writing code, or both.
  186. option feature on
  187. option feature off
  188. Enable or disable a single feature. This will automatically enable other
  189. features required by a feature that is turned on or disable other features that
  190. require a feature which is turned off. Conflicting settings will cause an error
  191. message to be emitted by awk.
  192. setting feature default value
  193. Changes the default value of setting 'feature' to 'value'. There are a small
  194. number of settings listed at the top of pnglibconf.h, they are documented in the
  195. source code. Most of these values have performance implications for the library
  196. but most of them have no visible effect on the API. Some can also be overridden
  197. from the API.
  198. This method of building a customized pnglibconf.h is illustrated in
  199. contrib/pngminim/*. See the "$(PNGCONF):" target in the makefile and
  200. pngusr.dfa in these directories.
  201. C. Configuration using PNG_USR_CONFIG
  202. If -DPNG_USR_CONFIG is added to the CFLAGS when pnglibconf.h is built the file
  203. pngusr.h will automatically be included before the options in
  204. scripts/pnglibconf.dfa are processed. Your pngusr.h file should contain only
  205. macro definitions turning features on or off or setting settings.
  206. Apart from the global setting "everything = off" all the options listed above
  207. can be set using macros in pngusr.h:
  208. #define PNG_feature_SUPPORTED
  209. is equivalent to:
  210. option feature on
  211. #define PNG_NO_feature
  212. is equivalent to:
  213. option feature off
  214. #define PNG_feature value
  215. is equivalent to:
  216. setting feature default value
  217. Notice that in both cases, pngusr.dfa and pngusr.h, the contents of the
  218. pngusr file you supply override the contents of scripts/pnglibconf.dfa
  219. If confusing or incomprehensible behavior results it is possible to
  220. examine the intermediate file pnglibconf.dfn to find the full set of
  221. dependency information for each setting and option. Simply locate the
  222. feature in the file and read the C comments that precede it.
  223. This method is also illustrated in the contrib/pngminim/* makefiles and
  224. pngusr.h.
  225. III. Reading
  226. We'll now walk you through the possible functions to call when reading
  227. in a PNG file sequentially, briefly explaining the syntax and purpose
  228. of each one. See example.c and png.h for more detail. While
  229. progressive reading is covered in the next section, you will still
  230. need some of the functions discussed in this section to read a PNG
  231. file.
  232. Setup
  233. You will want to do the I/O initialization(*) before you get into libpng,
  234. so if it doesn't work, you don't have much to undo. Of course, you
  235. will also want to insure that you are, in fact, dealing with a PNG
  236. file. Libpng provides a simple check to see if a file is a PNG file.
  237. To use it, pass in the first 1 to 8 bytes of the file to the function
  238. png_sig_cmp(), and it will return 0 (false) if the bytes match the
  239. corresponding bytes of the PNG signature, or nonzero (true) otherwise.
  240. Of course, the more bytes you pass in, the greater the accuracy of the
  241. prediction.
  242. If you are intending to keep the file pointer open for use in libpng,
  243. you must ensure you don't read more than 8 bytes from the beginning
  244. of the file, and you also have to make a call to png_set_sig_bytes_read()
  245. with the number of bytes you read from the beginning. Libpng will
  246. then only check the bytes (if any) that your program didn't read.
  247. (*): If you are not using the standard I/O functions, you will need
  248. to replace them with custom functions. See the discussion under
  249. Customizing libpng.
  250. FILE *fp = fopen(file_name, "rb");
  251. if (!fp)
  252. {
  253. return (ERROR);
  254. }
  255. fread(header, 1, number, fp);
  256. is_png = !png_sig_cmp(header, 0, number);
  257. if (!is_png)
  258. {
  259. return (NOT_PNG);
  260. }
  261. Next, png_struct and png_info need to be allocated and initialized. In
  262. order to ensure that the size of these structures is correct even with a
  263. dynamically linked libpng, there are functions to initialize and
  264. allocate the structures. We also pass the library version, optional
  265. pointers to error handling functions, and a pointer to a data struct for
  266. use by the error functions, if necessary (the pointer and functions can
  267. be NULL if the default error handlers are to be used). See the section
  268. on Changes to Libpng below regarding the old initialization functions.
  269. The structure allocation functions quietly return NULL if they fail to
  270. create the structure, so your application should check for that.
  271. png_structp png_ptr = png_create_read_struct
  272. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  273. user_error_fn, user_warning_fn);
  274. if (!png_ptr)
  275. return (ERROR);
  276. png_infop info_ptr = png_create_info_struct(png_ptr);
  277. if (!info_ptr)
  278. {
  279. png_destroy_read_struct(&png_ptr,
  280. (png_infopp)NULL, (png_infopp)NULL);
  281. return (ERROR);
  282. }
  283. If you want to use your own memory allocation routines,
  284. use a libpng that was built with PNG_USER_MEM_SUPPORTED defined, and use
  285. png_create_read_struct_2() instead of png_create_read_struct():
  286. png_structp png_ptr = png_create_read_struct_2
  287. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  288. user_error_fn, user_warning_fn, (png_voidp)
  289. user_mem_ptr, user_malloc_fn, user_free_fn);
  290. The error handling routines passed to png_create_read_struct()
  291. and the memory alloc/free routines passed to png_create_struct_2()
  292. are only necessary if you are not using the libpng supplied error
  293. handling and memory alloc/free functions.
  294. When libpng encounters an error, it expects to longjmp back
  295. to your routine. Therefore, you will need to call setjmp and pass
  296. your png_jmpbuf(png_ptr). If you read the file from different
  297. routines, you will need to update the longjmp buffer every time you enter
  298. a new routine that will call a png_*() function.
  299. See your documentation of setjmp/longjmp for your compiler for more
  300. information on setjmp/longjmp. See the discussion on libpng error
  301. handling in the Customizing Libpng section below for more information
  302. on the libpng error handling. If an error occurs, and libpng longjmp's
  303. back to your setjmp, you will want to call png_destroy_read_struct() to
  304. free any memory.
  305. if (setjmp(png_jmpbuf(png_ptr)))
  306. {
  307. png_destroy_read_struct(&png_ptr, &info_ptr,
  308. &end_info);
  309. fclose(fp);
  310. return (ERROR);
  311. }
  312. Pass (png_infopp)NULL instead of &end_info if you didn't create
  313. an end_info structure.
  314. If you would rather avoid the complexity of setjmp/longjmp issues,
  315. you can compile libpng with PNG_NO_SETJMP, in which case
  316. errors will result in a call to PNG_ABORT() which defaults to abort().
  317. You can #define PNG_ABORT() to a function that does something
  318. more useful than abort(), as long as your function does not
  319. return.
  320. Now you need to set up the input code. The default for libpng is to
  321. use the C function fread(). If you use this, you will need to pass a
  322. valid FILE * in the function png_init_io(). Be sure that the file is
  323. opened in binary mode. If you wish to handle reading data in another
  324. way, you need not call the png_init_io() function, but you must then
  325. implement the libpng I/O methods discussed in the Customizing Libpng
  326. section below.
  327. png_init_io(png_ptr, fp);
  328. If you had previously opened the file and read any of the signature from
  329. the beginning in order to see if this was a PNG file, you need to let
  330. libpng know that there are some bytes missing from the start of the file.
  331. png_set_sig_bytes(png_ptr, number);
  332. You can change the zlib compression buffer size to be used while
  333. reading compressed data with
  334. png_set_compression_buffer_size(png_ptr, buffer_size);
  335. where the default size is 8192 bytes. Note that the buffer size
  336. is changed immediately and the buffer is reallocated immediately,
  337. instead of setting a flag to be acted upon later.
  338. If you want CRC errors to be handled in a different manner than
  339. the default, use
  340. png_set_crc_action(png_ptr, crit_action, ancil_action);
  341. The values for png_set_crc_action() say how libpng is to handle CRC errors in
  342. ancillary and critical chunks, and whether to use the data contained
  343. therein. Note that it is impossible to "discard" data in a critical
  344. chunk.
  345. Choices for (int) crit_action are
  346. PNG_CRC_DEFAULT 0 error/quit
  347. PNG_CRC_ERROR_QUIT 1 error/quit
  348. PNG_CRC_WARN_USE 3 warn/use data
  349. PNG_CRC_QUIET_USE 4 quiet/use data
  350. PNG_CRC_NO_CHANGE 5 use the current value
  351. Choices for (int) ancil_action are
  352. PNG_CRC_DEFAULT 0 error/quit
  353. PNG_CRC_ERROR_QUIT 1 error/quit
  354. PNG_CRC_WARN_DISCARD 2 warn/discard data
  355. PNG_CRC_WARN_USE 3 warn/use data
  356. PNG_CRC_QUIET_USE 4 quiet/use data
  357. PNG_CRC_NO_CHANGE 5 use the current value
  358. Setting up callback code
  359. You can set up a callback function to handle any unknown chunks in the
  360. input stream. You must supply the function
  361. read_chunk_callback(png_structp png_ptr,
  362. png_unknown_chunkp chunk);
  363. {
  364. /* The unknown chunk structure contains your
  365. chunk data, along with similar data for any other
  366. unknown chunks: */
  367. png_byte name[5];
  368. png_byte *data;
  369. png_size_t size;
  370. /* Note that libpng has already taken care of
  371. the CRC handling */
  372. /* put your code here. Search for your chunk in the
  373. unknown chunk structure, process it, and return one
  374. of the following: */
  375. return (-n); /* chunk had an error */
  376. return (0); /* did not recognize */
  377. return (n); /* success */
  378. }
  379. (You can give your function another name that you like instead of
  380. "read_chunk_callback")
  381. To inform libpng about your function, use
  382. png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr,
  383. read_chunk_callback);
  384. This names not only the callback function, but also a user pointer that
  385. you can retrieve with
  386. png_get_user_chunk_ptr(png_ptr);
  387. If you call the png_set_read_user_chunk_fn() function, then all unknown
  388. chunks will be saved when read, in case your callback function will need
  389. one or more of them. This behavior can be changed with the
  390. png_set_keep_unknown_chunks() function, described below.
  391. At this point, you can set up a callback function that will be
  392. called after each row has been read, which you can use to control
  393. a progress meter or the like. It's demonstrated in pngtest.c.
  394. You must supply a function
  395. void read_row_callback(png_structp png_ptr,
  396. png_uint_32 row, int pass);
  397. {
  398. /* put your code here */
  399. }
  400. (You can give it another name that you like instead of "read_row_callback")
  401. To inform libpng about your function, use
  402. png_set_read_status_fn(png_ptr, read_row_callback);
  403. When this function is called the row has already been completely processed and
  404. the 'row' and 'pass' refer to the next row to be handled. For the
  405. non-interlaced case the row that was just handled is simply one less than the
  406. passed in row number, and pass will always be 0. For the interlaced case the
  407. same applies unless the row value is 0, in which case the row just handled was
  408. the last one from one of the preceding passes. Because interlacing may skip a
  409. pass you cannot be sure that the preceding pass is just 'pass-1', if you really
  410. need to know what the last pass is record (row,pass) from the callback and use
  411. the last recorded value each time.
  412. As with the user transform you can find the output row using the
  413. PNG_ROW_FROM_PASS_ROW macro.
  414. Unknown-chunk handling
  415. Now you get to set the way the library processes unknown chunks in the
  416. input PNG stream. Both known and unknown chunks will be read. Normal
  417. behavior is that known chunks will be parsed into information in
  418. various info_ptr members while unknown chunks will be discarded. This
  419. behavior can be wasteful if your application will never use some known
  420. chunk types. To change this, you can call:
  421. png_set_keep_unknown_chunks(png_ptr, keep,
  422. chunk_list, num_chunks);
  423. keep - 0: default unknown chunk handling
  424. 1: ignore; do not keep
  425. 2: keep only if safe-to-copy
  426. 3: keep even if unsafe-to-copy
  427. You can use these definitions:
  428. PNG_HANDLE_CHUNK_AS_DEFAULT 0
  429. PNG_HANDLE_CHUNK_NEVER 1
  430. PNG_HANDLE_CHUNK_IF_SAFE 2
  431. PNG_HANDLE_CHUNK_ALWAYS 3
  432. chunk_list - list of chunks affected (a byte string,
  433. five bytes per chunk, NULL or '\0' if
  434. num_chunks is 0)
  435. num_chunks - number of chunks affected; if 0, all
  436. unknown chunks are affected. If nonzero,
  437. only the chunks in the list are affected
  438. Unknown chunks declared in this way will be saved as raw data onto a
  439. list of png_unknown_chunk structures. If a chunk that is normally
  440. known to libpng is named in the list, it will be handled as unknown,
  441. according to the "keep" directive. If a chunk is named in successive
  442. instances of png_set_keep_unknown_chunks(), the final instance will
  443. take precedence. The IHDR and IEND chunks should not be named in
  444. chunk_list; if they are, libpng will process them normally anyway.
  445. If you know that your application will never make use of some particular
  446. chunks, use PNG_HANDLE_CHUNK_NEVER (or 1) as demonstrated below.
  447. Here is an example of the usage of png_set_keep_unknown_chunks(),
  448. where the private "vpAg" chunk will later be processed by a user chunk
  449. callback function:
  450. png_byte vpAg[5]={118, 112, 65, 103, (png_byte) '\0'};
  451. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  452. png_byte unused_chunks[]=
  453. {
  454. 104, 73, 83, 84, (png_byte) '\0', /* hIST */
  455. 105, 84, 88, 116, (png_byte) '\0', /* iTXt */
  456. 112, 67, 65, 76, (png_byte) '\0', /* pCAL */
  457. 115, 67, 65, 76, (png_byte) '\0', /* sCAL */
  458. 115, 80, 76, 84, (png_byte) '\0', /* sPLT */
  459. 116, 73, 77, 69, (png_byte) '\0', /* tIME */
  460. };
  461. #endif
  462. ...
  463. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  464. /* ignore all unknown chunks: */
  465. png_set_keep_unknown_chunks(read_ptr, 1, NULL, 0);
  466. /* except for vpAg: */
  467. png_set_keep_unknown_chunks(read_ptr, 2, vpAg, 1);
  468. /* also ignore unused known chunks: */
  469. png_set_keep_unknown_chunks(read_ptr, 1, unused_chunks,
  470. (int)sizeof(unused_chunks)/5);
  471. #endif
  472. User limits
  473. The PNG specification allows the width and height of an image to be as
  474. large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.
  475. Since very few applications really need to process such large images,
  476. we have imposed an arbitrary 1-million limit on rows and columns.
  477. Larger images will be rejected immediately with a png_error() call. If
  478. you wish to change this limit, you can use
  479. png_set_user_limits(png_ptr, width_max, height_max);
  480. to set your own limits, or use width_max = height_max = 0x7fffffffL
  481. to allow all valid dimensions (libpng may reject some very large images
  482. anyway because of potential buffer overflow conditions).
  483. You should put this statement after you create the PNG structure and
  484. before calling png_read_info(), png_read_png(), or png_process_data().
  485. When writing a PNG datastream, put this statement before calling
  486. png_write_info() or png_write_png().
  487. If you need to retrieve the limits that are being applied, use
  488. width_max = png_get_user_width_max(png_ptr);
  489. height_max = png_get_user_height_max(png_ptr);
  490. The PNG specification sets no limit on the number of ancillary chunks
  491. allowed in a PNG datastream. You can impose a limit on the total number
  492. of sPLT, tEXt, iTXt, zTXt, and unknown chunks that will be stored, with
  493. png_set_chunk_cache_max(png_ptr, user_chunk_cache_max);
  494. where 0x7fffffffL means unlimited. You can retrieve this limit with
  495. chunk_cache_max = png_get_chunk_cache_max(png_ptr);
  496. This limit also applies to the number of buffers that can be allocated
  497. by png_decompress_chunk() while decompressing iTXt, zTXt, and iCCP chunks.
  498. You can also set a limit on the amount of memory that a compressed chunk
  499. other than IDAT can occupy, with
  500. png_set_chunk_malloc_max(png_ptr, user_chunk_malloc_max);
  501. and you can retrieve the limit with
  502. chunk_malloc_max = png_get_chunk_malloc_max(png_ptr);
  503. Any chunks that would cause either of these limits to be exceeded will
  504. be ignored.
  505. Information about your system
  506. If you intend to display the PNG or to incorporate it in other image data you
  507. need to tell libpng information about your display or drawing surface so that
  508. libpng can convert the values in the image to match the display.
  509. From libpng-1.5.4 this information can be set before reading the PNG file
  510. header. In earlier versions png_set_gamma() existed but behaved incorrectly if
  511. called before the PNG file header had been read and png_set_alpha_mode() did not
  512. exist.
  513. If you need to support versions prior to libpng-1.5.4 test the version number
  514. as illustrated below using "PNG_LIBPNG_VER >= 10504" and follow the procedures
  515. described in the appropriate manual page.
  516. You give libpng the encoding expected by your system expressed as a 'gamma'
  517. value. You can also specify a default encoding for the PNG file in
  518. case the required information is missing from the file. By default libpng
  519. assumes that the PNG data matches your system, to keep this default call:
  520. png_set_gamma(png_ptr, screen_gamma, 1/screen_gamma/*file gamma*/);
  521. or you can use the fixed point equivalent:
  522. png_set_gamma_fixed(png_ptr, PNG_FP_1*screen_gamma, PNG_FP_1/screen_gamma);
  523. If you don't know the gamma for your system it is probably 2.2 - a good
  524. approximation to the IEC standard for display systems (sRGB). If images are
  525. too contrasty or washed out you got the value wrong - check your system
  526. documentation!
  527. Many systems permit the system gamma to be changed via a lookup table in the
  528. display driver, a few systems, including older Macs, change the response by
  529. default. As of 1.5.4 three special values are available to handle common
  530. situations:
  531. PNG_DEFAULT_sRGB: Indicates that the system conforms to the IEC 61966-2-1
  532. standard. This matches almost all systems.
  533. PNG_GAMMA_MAC_18: Indicates that the system is an older (pre Mac OS 10.6)
  534. Apple Macintosh system with the default settings.
  535. PNG_GAMMA_LINEAR: Just the fixed point value for 1.0 - indicates that the
  536. system expects data with no gamma encoding.
  537. You would use the linear (unencoded) value if you need to process the pixel
  538. values further because this avoids the need to decode and reencode each
  539. component value whenever arithmetic is performed. A lot of graphics software
  540. uses linear values for this reason, often with higher precision component values
  541. to preserve overall accuracy.
  542. The second thing you may need to tell libpng about is how your system handles
  543. alpha channel information. Some, but not all, PNG files contain an alpha
  544. channel. To display these files correctly you need to compose the data onto a
  545. suitable background, as described in the PNG specification.
  546. Libpng only supports composing onto a single color (using png_set_background;
  547. see below). Otherwise you must do the composition yourself and, in this case,
  548. you may need to call png_set_alpha_mode:
  549. #if PNG_LIBPNG_VER >= 10504
  550. png_set_alpha_mode(png_ptr, mode, screen_gamma);
  551. #else
  552. png_set_gamma(png_ptr, screen_gamma, 1.0/screen_gamma);
  553. #endif
  554. The screen_gamma value is the same as the argument to png_set_gamma; however,
  555. how it affects the output depends on the mode. png_set_alpha_mode() sets the
  556. file gamma default to 1/screen_gamma, so normally you don't need to call
  557. png_set_gamma. If you need different defaults call png_set_gamma() before
  558. png_set_alpha_mode() - if you call it after it will override the settings made
  559. by png_set_alpha_mode().
  560. The mode is as follows:
  561. PNG_ALPHA_PNG: The data is encoded according to the PNG specification. Red,
  562. green and blue, or gray, components are gamma encoded color
  563. values and are not premultiplied by the alpha value. The
  564. alpha value is a linear measure of the contribution of the
  565. pixel to the corresponding final output pixel.
  566. You should normally use this format if you intend to perform
  567. color correction on the color values; most, maybe all, color
  568. correction software has no handling for the alpha channel and,
  569. anyway, the math to handle pre-multiplied component values is
  570. unnecessarily complex.
  571. Before you do any arithmetic on the component values you need
  572. to remove the gamma encoding and multiply out the alpha
  573. channel. See the PNG specification for more detail. It is
  574. important to note that when an image with an alpha channel is
  575. scaled, linear encoded, pre-multiplied component values must
  576. be used!
  577. The remaining modes assume you don't need to do any further color correction or
  578. that if you do, your color correction software knows all about alpha (it
  579. probably doesn't!)
  580. PNG_ALPHA_STANDARD: The data libpng produces
  581. is encoded in the standard way
  582. assumed by most correctly written graphics software.
  583. The gamma encoding will be removed by libpng and the
  584. linear component values will be pre-multiplied by the
  585. alpha channel.
  586. With this format the final image must be re-encoded to
  587. match the display gamma before the image is displayed.
  588. If your system doesn't do that, yet still seems to
  589. perform arithmetic on the pixels without decoding them,
  590. it is broken - check out the modes below.
  591. With PNG_ALPHA_STANDARD libpng always produces linear
  592. component values, whatever screen_gamma you supply. The
  593. screen_gamma value is, however, used as a default for
  594. the file gamma if the PNG file has no gamma information.
  595. If you call png_set_gamma() after png_set_alpha_mode() you
  596. will override the linear encoding. Instead the
  597. pre-multiplied pixel values will be gamma encoded but
  598. the alpha channel will still be linear. This may
  599. actually match the requirements of some broken software,
  600. but it is unlikely.
  601. While linear 8-bit data is often used it has
  602. insufficient precision for any image with a reasonable
  603. dynamic range. To avoid problems, and if your software
  604. supports it, use png_set_expand_16() to force all
  605. components to 16 bits.
  606. PNG_ALPHA_OPTIMIZED: This mode is the same
  607. as PNG_ALPHA_STANDARD except that
  608. completely opaque pixels are gamma encoded according to
  609. the screen_gamma value. Pixels with alpha less than 1.0
  610. will still have linear components.
  611. Use this format if you have control over your
  612. compositing software and do don't do other arithmetic
  613. (such as scaling) on the data you get from libpng. Your
  614. compositing software can simply copy opaque pixels to
  615. the output but still has linear values for the
  616. non-opaque pixels.
  617. In normal compositing, where the alpha channel encodes
  618. partial pixel coverage (as opposed to broad area
  619. translucency), the inaccuracies of the 8-bit
  620. representation of non-opaque pixels are irrelevant.
  621. You can also try this format if your software is broken;
  622. it might look better.
  623. PNG_ALPHA_BROKEN: This is PNG_ALPHA_STANDARD;
  624. however, all component values,
  625. including the alpha channel are gamma encoded. This is
  626. an appropriate format to try if your software, or more
  627. likely hardware, is totally broken, i.e., if it performs
  628. linear arithmetic directly on gamma encoded values.
  629. In most cases of broken software or hardware the bug in the final display
  630. manifests as a subtle halo around composited parts of the image. You may not
  631. even perceive this as a halo; the composited part of the image may simply appear
  632. separate from the background, as though it had been cut out of paper and pasted
  633. on afterward.
  634. If you don't have to deal with bugs in software or hardware, or if you can fix
  635. them, there are three recommended ways of using png_set_alpha_mode():
  636. png_set_alpha_mode(png_ptr, PNG_ALPHA_PNG,
  637. screen_gamma);
  638. You can do color correction on the result (libpng does not currently
  639. support color correction internally). When you handle the alpha channel
  640. you need to undo the gamma encoding and multiply out the alpha.
  641. png_set_alpha_mode(png_ptr, PNG_ALPHA_STANDARD,
  642. screen_gamma);
  643. png_set_expand_16(png_ptr);
  644. If you are using the high level interface, don't call png_set_expand_16();
  645. instead pass PNG_TRANSFORM_EXPAND_16 to the interface.
  646. With this mode you can't do color correction, but you can do arithmetic,
  647. including composition and scaling, on the data without further processing.
  648. png_set_alpha_mode(png_ptr, PNG_ALPHA_OPTIMIZED,
  649. screen_gamma);
  650. You can avoid the expansion to 16-bit components with this mode, but you
  651. lose the ability to scale the image or perform other linear arithmetic.
  652. All you can do is compose the result onto a matching output. Since this
  653. mode is libpng-specific you also need to write your own composition
  654. software.
  655. If you don't need, or can't handle, the alpha channel you can call
  656. png_set_background() to remove it by compositing against a fixed color. Don't
  657. call png_set_strip_alpha() to do this - it will leave spurious pixel values in
  658. transparent parts of this image.
  659. png_set_background(png_ptr, &background_color,
  660. PNG_BACKGROUND_GAMMA_SCREEN, 0, 1);
  661. The background_color is an RGB or grayscale value according to the data format
  662. libpng will produce for you. Because you don't yet know the format of the PNG
  663. file, if you call png_set_background at this point you must arrange for the
  664. format produced by libpng to always have 8-bit or 16-bit components and then
  665. store the color as an 8-bit or 16-bit color as appropriate. The color contains
  666. separate gray and RGB component values, so you can let libpng produce gray or
  667. RGB output according to the input format, but low bit depth grayscale images
  668. must always be converted to at least 8-bit format. (Even though low bit depth
  669. grayscale images can't have an alpha channel they can have a transparent
  670. color!)
  671. You set the transforms you need later, either as flags to the high level
  672. interface or libpng API calls for the low level interface. For reference the
  673. settings and API calls required are:
  674. 8-bit values:
  675. PNG_TRANSFORM_SCALE_16 | PNG_EXPAND
  676. png_set_expand(png_ptr); png_set_scale_16(png_ptr);
  677. If you must get exactly the same inaccurate results
  678. produced by default in versions prior to libpng-1.5.4,
  679. use PNG_TRANSFORM_STRIP_16 and png_set_strip_16(png_ptr)
  680. instead.
  681. 16-bit values:
  682. PNG_TRANSFORM_EXPAND_16
  683. png_set_expand_16(png_ptr);
  684. In either case palette image data will be expanded to RGB. If you just want
  685. color data you can add PNG_TRANSFORM_GRAY_TO_RGB or png_set_gray_to_rgb(png_ptr)
  686. to the list.
  687. Calling png_set_background before the PNG file header is read will not work
  688. prior to libpng-1.5.4. Because the failure may result in unexpected warnings or
  689. errors it is therefore much safer to call png_set_background after the head has
  690. been read. Unfortunately this means that prior to libpng-1.5.4 it cannot be
  691. used with the high level interface.
  692. The high-level read interface
  693. At this point there are two ways to proceed; through the high-level
  694. read interface, or through a sequence of low-level read operations.
  695. You can use the high-level interface if (a) you are willing to read
  696. the entire image into memory, and (b) the input transformations
  697. you want to do are limited to the following set:
  698. PNG_TRANSFORM_IDENTITY No transformation
  699. PNG_TRANSFORM_SCALE_16 Strip 16-bit samples to
  700. 8-bit accurately
  701. PNG_TRANSFORM_STRIP_16 Chop 16-bit samples to
  702. 8-bit less accurately
  703. PNG_TRANSFORM_STRIP_ALPHA Discard the alpha channel
  704. PNG_TRANSFORM_PACKING Expand 1, 2 and 4-bit
  705. samples to bytes
  706. PNG_TRANSFORM_PACKSWAP Change order of packed
  707. pixels to LSB first
  708. PNG_TRANSFORM_EXPAND Perform set_expand()
  709. PNG_TRANSFORM_INVERT_MONO Invert monochrome images
  710. PNG_TRANSFORM_SHIFT Normalize pixels to the
  711. sBIT depth
  712. PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
  713. to BGRA
  714. PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
  715. to AG
  716. PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
  717. to transparency
  718. PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
  719. PNG_TRANSFORM_GRAY_TO_RGB Expand grayscale samples
  720. to RGB (or GA to RGBA)
  721. PNG_TRANSFORM_EXPAND_16 Expand samples to 16 bits
  722. (This excludes setting a background color, doing gamma transformation,
  723. quantizing, and setting filler.) If this is the case, simply do this:
  724. png_read_png(png_ptr, info_ptr, png_transforms, NULL)
  725. where png_transforms is an integer containing the bitwise OR of some
  726. set of transformation flags. This call is equivalent to png_read_info(),
  727. followed the set of transformations indicated by the transform mask,
  728. then png_read_image(), and finally png_read_end().
  729. (The final parameter of this call is not yet used. Someday it might point
  730. to transformation parameters required by some future input transform.)
  731. You must use png_transforms and not call any png_set_transform() functions
  732. when you use png_read_png().
  733. After you have called png_read_png(), you can retrieve the image data
  734. with
  735. row_pointers = png_get_rows(png_ptr, info_ptr);
  736. where row_pointers is an array of pointers to the pixel data for each row:
  737. png_bytep row_pointers[height];
  738. If you know your image size and pixel size ahead of time, you can allocate
  739. row_pointers prior to calling png_read_png() with
  740. if (height > PNG_UINT_32_MAX/png_sizeof(png_byte))
  741. png_error (png_ptr,
  742. "Image is too tall to process in memory");
  743. if (width > PNG_UINT_32_MAX/pixel_size)
  744. png_error (png_ptr,
  745. "Image is too wide to process in memory");
  746. row_pointers = png_malloc(png_ptr,
  747. height*png_sizeof(png_bytep));
  748. for (int i=0; i<height, i++)
  749. row_pointers[i]=NULL; /* security precaution */
  750. for (int i=0; i<height, i++)
  751. row_pointers[i]=png_malloc(png_ptr,
  752. width*pixel_size);
  753. png_set_rows(png_ptr, info_ptr, &row_pointers);
  754. Alternatively you could allocate your image in one big block and define
  755. row_pointers[i] to point into the proper places in your block.
  756. If you use png_set_rows(), the application is responsible for freeing
  757. row_pointers (and row_pointers[i], if they were separately allocated).
  758. If you don't allocate row_pointers ahead of time, png_read_png() will
  759. do it, and it'll be free'ed by libpng when you call png_destroy_*().
  760. The low-level read interface
  761. If you are going the low-level route, you are now ready to read all
  762. the file information up to the actual image data. You do this with a
  763. call to png_read_info().
  764. png_read_info(png_ptr, info_ptr);
  765. This will process all chunks up to but not including the image data.
  766. This also copies some of the data from the PNG file into the decode structure
  767. for use in later transformations. Important information copied in is:
  768. 1) The PNG file gamma from the gAMA chunk. This overwrites the default value
  769. provided by an earlier call to png_set_gamma or png_set_alpha_mode.
  770. 2) Prior to libpng-1.5.4 the background color from a bKGd chunk. This
  771. damages the information provided by an earlier call to png_set_background
  772. resulting in unexpected behavior. Libpng-1.5.4 no longer does this.
  773. 3) The number of significant bits in each component value. Libpng uses this to
  774. optimize gamma handling by reducing the internal lookup table sizes.
  775. 4) The transparent color information from a tRNS chunk. This can be modified by
  776. a later call to png_set_tRNS.
  777. Querying the info structure
  778. Functions are used to get the information from the info_ptr once it
  779. has been read. Note that these fields may not be completely filled
  780. in until png_read_end() has read the chunk data following the image.
  781. png_get_IHDR(png_ptr, info_ptr, &width, &height,
  782. &bit_depth, &color_type, &interlace_type,
  783. &compression_type, &filter_method);
  784. width - holds the width of the image
  785. in pixels (up to 2^31).
  786. height - holds the height of the image
  787. in pixels (up to 2^31).
  788. bit_depth - holds the bit depth of one of the
  789. image channels. (valid values are
  790. 1, 2, 4, 8, 16 and depend also on
  791. the color_type. See also
  792. significant bits (sBIT) below).
  793. color_type - describes which color/alpha channels
  794. are present.
  795. PNG_COLOR_TYPE_GRAY
  796. (bit depths 1, 2, 4, 8, 16)
  797. PNG_COLOR_TYPE_GRAY_ALPHA
  798. (bit depths 8, 16)
  799. PNG_COLOR_TYPE_PALETTE
  800. (bit depths 1, 2, 4, 8)
  801. PNG_COLOR_TYPE_RGB
  802. (bit_depths 8, 16)
  803. PNG_COLOR_TYPE_RGB_ALPHA
  804. (bit_depths 8, 16)
  805. PNG_COLOR_MASK_PALETTE
  806. PNG_COLOR_MASK_COLOR
  807. PNG_COLOR_MASK_ALPHA
  808. interlace_type - (PNG_INTERLACE_NONE or
  809. PNG_INTERLACE_ADAM7)
  810. compression_type - (must be PNG_COMPRESSION_TYPE_BASE
  811. for PNG 1.0)
  812. filter_method - (must be PNG_FILTER_TYPE_BASE
  813. for PNG 1.0, and can also be
  814. PNG_INTRAPIXEL_DIFFERENCING if
  815. the PNG datastream is embedded in
  816. a MNG-1.0 datastream)
  817. Any or all of interlace_type, compression_type, or
  818. filter_method can be NULL if you are
  819. not interested in their values.
  820. Note that png_get_IHDR() returns 32-bit data into
  821. the application's width and height variables.
  822. This is an unsafe situation if these are 16-bit
  823. variables. In such situations, the
  824. png_get_image_width() and png_get_image_height()
  825. functions described below are safer.
  826. width = png_get_image_width(png_ptr,
  827. info_ptr);
  828. height = png_get_image_height(png_ptr,
  829. info_ptr);
  830. bit_depth = png_get_bit_depth(png_ptr,
  831. info_ptr);
  832. color_type = png_get_color_type(png_ptr,
  833. info_ptr);
  834. interlace_type = png_get_interlace_type(png_ptr,
  835. info_ptr);
  836. compression_type = png_get_compression_type(png_ptr,
  837. info_ptr);
  838. filter_method = png_get_filter_type(png_ptr,
  839. info_ptr);
  840. channels = png_get_channels(png_ptr, info_ptr);
  841. channels - number of channels of info for the
  842. color type (valid values are 1 (GRAY,
  843. PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
  844. 4 (RGB_ALPHA or RGB + filler byte))
  845. rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  846. rowbytes - number of bytes needed to hold a row
  847. signature = png_get_signature(png_ptr, info_ptr);
  848. signature - holds the signature read from the
  849. file (if any). The data is kept in
  850. the same offset it would be if the
  851. whole signature were read (i.e. if an
  852. application had already read in 4
  853. bytes of signature before starting
  854. libpng, the remaining 4 bytes would
  855. be in signature[4] through signature[7]
  856. (see png_set_sig_bytes())).
  857. These are also important, but their validity depends on whether the chunk
  858. has been read. The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
  859. png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
  860. data has been read, or zero if it is missing. The parameters to the
  861. png_get_<chunk> are set directly if they are simple data types, or a
  862. pointer into the info_ptr is returned for any complex types.
  863. png_get_PLTE(png_ptr, info_ptr, &palette,
  864. &num_palette);
  865. palette - the palette for the file
  866. (array of png_color)
  867. num_palette - number of entries in the palette
  868. png_get_gAMA(png_ptr, info_ptr, &file_gamma);
  869. png_get_gAMA_fixed(png_ptr, info_ptr, &int_file_gamma);
  870. file_gamma - the gamma at which the file is
  871. written (PNG_INFO_gAMA)
  872. int_file_gamma - 100,000 times the gamma at which the
  873. file is written
  874. png_get_cHRM(png_ptr, info_ptr, &white_x, &white_y, &red_x, &red_y,
  875. &green_x, &green_y, &blue_x, &blue_y)
  876. png_get_cHRM_XYZ(png_ptr, info_ptr, &red_X, &red_Y, &red_Z, &green_X,
  877. &green_Y, &green_Z, &blue_X, &blue_Y, &blue_Z)
  878. png_get_cHRM_fixed(png_ptr, info_ptr, &int_white_x, &int_white_y,
  879. &int_red_x, &int_red_y, &int_green_x, &int_green_y,
  880. &int_blue_x, &int_blue_y)
  881. png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &int_red_X, &int_red_Y,
  882. &int_red_Z, &int_green_X, &int_green_Y, &int_green_Z,
  883. &int_blue_X, &int_blue_Y, &int_blue_Z)
  884. {white,red,green,blue}_{x,y}
  885. A color space encoding specified using the chromaticities
  886. of the end points and the white point. (PNG_INFO_cHRM)
  887. {red,green,blue}_{X,Y,Z}
  888. A color space encoding specified using the encoding end
  889. points - the CIE tristimulus specification of the intended
  890. color of the red, green and blue channels in the PNG RGB
  891. data. The white point is simply the sum of the three end
  892. points. (PNG_INFO_cHRM)
  893. png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
  894. file_srgb_intent - the rendering intent (PNG_INFO_sRGB)
  895. The presence of the sRGB chunk
  896. means that the pixel data is in the
  897. sRGB color space. This chunk also
  898. implies specific values of gAMA and
  899. cHRM.
  900. png_get_iCCP(png_ptr, info_ptr, &name,
  901. &compression_type, &profile, &proflen);
  902. name - The profile name.
  903. compression_type - The compression type; always
  904. PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
  905. You may give NULL to this argument to
  906. ignore it.
  907. profile - International Color Consortium color
  908. profile data. May contain NULs.
  909. proflen - length of profile data in bytes.
  910. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  911. sig_bit - the number of significant bits for
  912. (PNG_INFO_sBIT) each of the gray,
  913. red, green, and blue channels,
  914. whichever are appropriate for the
  915. given color type (png_color_16)
  916. png_get_tRNS(png_ptr, info_ptr, &trans_alpha,
  917. &num_trans, &trans_color);
  918. trans_alpha - array of alpha (transparency)
  919. entries for palette (PNG_INFO_tRNS)
  920. num_trans - number of transparent entries
  921. (PNG_INFO_tRNS)
  922. trans_color - graylevel or color