PageRenderTime 148ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/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
Possible License(s): LGPL-3.0, BSD-3-Clause, CPL-1.0, Unlicense, GPL-2.0, GPL-3.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, BSD-2-Clause, LGPL-2.1
  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 sample values of
  923. the single transparent color for
  924. non-paletted images (PNG_INFO_tRNS)
  925. png_get_hIST(png_ptr, info_ptr, &hist);
  926. (PNG_INFO_hIST)
  927. hist - histogram of palette (array of
  928. png_uint_16)
  929. png_get_tIME(png_ptr, info_ptr, &mod_time);
  930. mod_time - time image was last modified
  931. (PNG_VALID_tIME)
  932. png_get_bKGD(png_ptr, info_ptr, &background);
  933. background - background color (of type
  934. png_color_16p) (PNG_VALID_bKGD)
  935. valid 16-bit red, green and blue
  936. values, regardless of color_type
  937. num_comments = png_get_text(png_ptr, info_ptr,
  938. &text_ptr, &num_text);
  939. num_comments - number of comments
  940. text_ptr - array of png_text holding image
  941. comments
  942. text_ptr[i].compression - type of compression used
  943. on "text" PNG_TEXT_COMPRESSION_NONE
  944. PNG_TEXT_COMPRESSION_zTXt
  945. PNG_ITXT_COMPRESSION_NONE
  946. PNG_ITXT_COMPRESSION_zTXt
  947. text_ptr[i].key - keyword for comment. Must contain
  948. 1-79 characters.
  949. text_ptr[i].text - text comments for current
  950. keyword. Can be empty.
  951. text_ptr[i].text_length - length of text string,
  952. after decompression, 0 for iTXt
  953. text_ptr[i].itxt_length - length of itxt string,
  954. after decompression, 0 for tEXt/zTXt
  955. text_ptr[i].lang - language of comment (empty
  956. string for unknown).
  957. text_ptr[i].lang_key - keyword in UTF-8
  958. (empty string for unknown).
  959. Note that the itxt_length, lang, and lang_key
  960. members of the text_ptr structure only exist when the
  961. library is built with iTXt chunk support. Prior to
  962. libpng-1.4.0 the library was built by default without
  963. iTXt support. Also note that when iTXt is supported,
  964. they contain NULL pointers when the "compression"
  965. field contains PNG_TEXT_COMPRESSION_NONE or
  966. PNG_TEXT_COMPRESSION_zTXt.
  967. num_text - number of comments (same as
  968. num_comments; you can put NULL here
  969. to avoid the duplication)
  970. Note while png_set_text() will accept text, language,
  971. and translated keywords that can be NULL pointers, the
  972. structure returned by png_get_text will always contain
  973. regular zero-terminated C strings. They might be
  974. empty strings but they will never be NULL pointers.
  975. num_spalettes = png_get_sPLT(png_ptr, info_ptr,
  976. &palette_ptr);
  977. num_spalettes - number of sPLT chunks read.
  978. palette_ptr - array of palette structures holding
  979. contents of one or more sPLT chunks
  980. read.
  981. png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
  982. &unit_type);
  983. offset_x - positive offset from the left edge
  984. of the screen (can be negative)
  985. offset_y - positive offset from the top edge
  986. of the screen (can be negative)
  987. unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
  988. png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
  989. &unit_type);
  990. res_x - pixels/unit physical resolution in
  991. x direction
  992. res_y - pixels/unit physical resolution in
  993. x direction
  994. unit_type - PNG_RESOLUTION_UNKNOWN,
  995. PNG_RESOLUTION_METER
  996. png_get_sCAL(png_ptr, info_ptr, &unit, &width,
  997. &height)
  998. unit - physical scale units (an integer)
  999. width - width of a pixel in physical scale units
  1000. height - height of a pixel in physical scale units
  1001. (width and height are doubles)
  1002. png_get_sCAL_s(png_ptr, info_ptr, &unit, &width,
  1003. &height)
  1004. unit - physical scale units (an integer)
  1005. width - width of a pixel in physical scale units
  1006. (expressed as a string)
  1007. height - height of a pixel in physical scale units
  1008. (width and height are strings like "2.54")
  1009. num_unknown_chunks = png_get_unknown_chunks(png_ptr,
  1010. info_ptr, &unknowns)
  1011. unknowns - array of png_unknown_chunk
  1012. structures holding unknown chunks
  1013. unknowns[i].name - name of unknown chunk
  1014. unknowns[i].data - data of unknown chunk
  1015. unknowns[i].size - size of unknown chunk's data
  1016. unknowns[i].location - position of chunk in file
  1017. The value of "i" corresponds to the order in which the
  1018. chunks were read from the PNG file or inserted with the
  1019. png_set_unknown_chunks() function.
  1020. The value of "location" is a bitwise "or" of
  1021. PNG_HAVE_IHDR (0x01)
  1022. PNG_HAVE_PLTE (0x02)
  1023. PNG_AFTER_IDAT (0x08)
  1024. The data from the pHYs chunk can be retrieved in several convenient
  1025. forms:
  1026. res_x = png_get_x_pixels_per_meter(png_ptr,
  1027. info_ptr)
  1028. res_y = png_get_y_pixels_per_meter(png_ptr,
  1029. info_ptr)
  1030. res_x_and_y = png_get_pixels_per_meter(png_ptr,
  1031. info_ptr)
  1032. res_x = png_get_x_pixels_per_inch(png_ptr,
  1033. info_ptr)
  1034. res_y = png_get_y_pixels_per_inch(png_ptr,
  1035. info_ptr)
  1036. res_x_and_y = png_get_pixels_per_inch(png_ptr,
  1037. info_ptr)
  1038. aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
  1039. info_ptr)
  1040. Each of these returns 0 [signifying "unknown"] if
  1041. the data is not present or if res_x is 0;
  1042. res_x_and_y is 0 if res_x != res_y
  1043. Note that because of the way the resolutions are
  1044. stored internally, the inch conversions won't
  1045. come out to exactly even number. For example,
  1046. 72 dpi is stored as 0.28346 pixels/meter, and
  1047. when this is retrieved it is 71.9988 dpi, so
  1048. be sure to round the returned value appropriately
  1049. if you want to display a reasonable-looking result.
  1050. The data from the oFFs chunk can be retrieved in several convenient
  1051. forms:
  1052. x_offset = png_get_x_offset_microns(png_ptr, info_ptr);
  1053. y_offset = png_get_y_offset_microns(png_ptr, info_ptr);
  1054. x_offset = png_get_x_offset_inches(png_ptr, info_ptr);
  1055. y_offset = png_get_y_offset_inches(png_ptr, info_ptr);
  1056. Each of these returns 0 [signifying "unknown" if both
  1057. x and y are 0] if the data is not present or if the
  1058. chunk is present but the unit is the pixel. The
  1059. remark about inexact inch conversions applies here
  1060. as well, because a value in inches can't always be
  1061. converted to microns and back without some loss
  1062. of precision.
  1063. For more information, see the
  1064. PNG specification for chunk contents. Be careful with trusting
  1065. rowbytes, as some of the transformations could increase the space
  1066. needed to hold a row (expand, filler, gray_to_rgb, etc.).
  1067. See png_read_update_info(), below.
  1068. A quick word about text_ptr and num_text. PNG stores comments in
  1069. keyword/text pairs, one pair per chunk, with no limit on the number
  1070. of text chunks, and a 2^31 byte limit on their size. While there are
  1071. suggested keywords, there is no requirement to restrict the use to these
  1072. strings. It is strongly suggested that keywords and text be sensible
  1073. to humans (that's the point), so don't use abbreviations. Non-printing
  1074. symbols are not allowed. See the PNG specification for more details.
  1075. There is also no requirement to have text after the keyword.
  1076. Keywords should be limited to 79 Latin-1 characters without leading or
  1077. trailing spaces, but non-consecutive spaces are allowed within the
  1078. keyword. It is possible to have the same keyword any number of times.
  1079. The text_ptr is an array of png_text structures, each holding a
  1080. pointer to a language string, a pointer to a keyword and a pointer to
  1081. a text string. The text string, language code, and translated
  1082. keyword may be empty or NULL pointers. The keyword/text
  1083. pairs are put into the array in the order that they are received.
  1084. However, some or all of the text chunks may be after the image, so, to
  1085. make sure you have read all the text chunks, don't mess with these
  1086. until after you read the stuff after the image. This will be
  1087. mentioned again below in the discussion that goes with png_read_end().
  1088. Input transformations
  1089. After you've read the header information, you can set up the library
  1090. to handle any special transformations of the image data. The various
  1091. ways to transform the data will be described in the order that they
  1092. should occur. This is important, as some of these change the color
  1093. type and/or bit depth of the data, and some others only work on
  1094. certain color types and bit depths.
  1095. Transformations you request are ignored if they don't have any meaning for a
  1096. particular input data format. However some transformations can have an effect
  1097. as a result of a previous transformation. If you specify a contradictory set of
  1098. transformations, for example both adding and removing the alpha channel, you
  1099. cannot predict the final result.
  1100. The color used for the transparency values should be supplied in the same
  1101. format/depth as the current image data. It is stored in the same format/depth
  1102. as the image data in a tRNS chunk, so this is what libpng expects for this data.
  1103. The color used for the background value depends on the need_expand argument as
  1104. described below.
  1105. Data will be decoded into the supplied row buffers packed into bytes
  1106. unless the library has been told to transform it into another format.
  1107. For example, 4 bit/pixel paletted or grayscale data will be returned
  1108. 2 pixels/byte with the leftmost pixel in the high-order bits of the
  1109. byte, unless png_set_packing() is called. 8-bit RGB data will be stored
  1110. in RGB RGB RGB format unless png_set_filler() or png_set_add_alpha()
  1111. is called to insert filler bytes, either before or after each RGB triplet.
  1112. 16-bit RGB data will be returned RRGGBB RRGGBB, with the most significant
  1113. byte of the color value first, unless png_set_scale_16() is called to
  1114. transform it to regular RGB RGB triplets, or png_set_filler() or
  1115. png_set_add alpha() is called to insert filler bytes, either before or
  1116. after each RRGGBB triplet. Similarly, 8-bit or 16-bit grayscale data can
  1117. be modified with png_set_filler(), png_set_add_alpha(), png_set_strip_16(),
  1118. or png_set_scale_16().
  1119. The following code transforms grayscale images of less than 8 to 8 bits,
  1120. changes paletted images to RGB, and adds a full alpha channel if there is
  1121. transparency information in a tRNS chunk. This is most useful on
  1122. grayscale images with bit depths of 2 or 4 or if there is a multiple-image
  1123. viewing application that wishes to treat all images in the same way.
  1124. if (color_type == PNG_COLOR_TYPE_PALETTE)
  1125. png_set_palette_to_rgb(png_ptr);
  1126. if (png_get_valid(png_ptr, info_ptr,
  1127. PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
  1128. if (color_type == PNG_COLOR_TYPE_GRAY &&
  1129. bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png_ptr);
  1130. The first two functions are actually aliases for png_set_expand(), added
  1131. in libpng version 1.0.4, with the function names expanded to improve code
  1132. readability. In some future version they may actually do different
  1133. things.
  1134. As of libpng version 1.2.9, png_set_expand_gray_1_2_4_to_8() was
  1135. added. It expands the sample depth without changing tRNS to alpha.
  1136. As of libpng version 1.5.2, png_set_expand_16() was added. It behaves as
  1137. png_set_expand(); however, the resultant channels have 16 bits rather than 8.
  1138. Use this when the output color or gray channels are made linear to avoid fairly
  1139. severe accuracy loss.
  1140. if (bit_depth < 16)
  1141. png_set_expand_16(png_ptr);
  1142. PNG can have files with 16 bits per channel. If you only can handle
  1143. 8 bits per channel, this will strip the pixels down to 8-bit.
  1144. if (bit_depth == 16)
  1145. #if PNG_LIBPNG_VER >= 10504
  1146. png_set_scale_16(png_ptr);
  1147. #else
  1148. png_set_strip_16(png_ptr);
  1149. #endif
  1150. (The more accurate "png_set_scale_16()" API became available in libpng version
  1151. 1.5.4).
  1152. If you need to process the alpha channel on the image separately from the image
  1153. data (for example if you convert it to a bitmap mask) it is possible to have
  1154. libpng strip the channel leaving just RGB or gray data:
  1155. if (color_type & PNG_COLOR_MASK_ALPHA)
  1156. png_set_strip_alpha(png_ptr);
  1157. If you strip the alpha channel you need to find some other way of dealing with
  1158. the information. If, instead, you want to convert the image to an opaque
  1159. version with no alpha channel use png_set_background; see below.
  1160. As of libpng version 1.5.2, almost all useful expansions are supported, the
  1161. major ommissions are conversion of grayscale to indexed images (which can be
  1162. done trivially in the application) and conversion of indexed to grayscale (which
  1163. can be done by a trivial manipulation of the palette.)
  1164. In the following table, the 01 means grayscale with depth<8, 31 means
  1165. indexed with depth<8, other numerals represent the color type, "T" means
  1166. the tRNS chunk is present, A means an alpha channel is present, and O
  1167. means tRNS or alpha is present but all pixels in the image are opaque.
  1168. FROM 01 31 0 0T 0O 2 2T 2O 3 3T 3O 4A 4O 6A 6O
  1169. TO
  1170. 01 - [G] - - - - - - - - - - - - -
  1171. 31 [Q] Q [Q] [Q] [Q] Q Q Q Q Q Q [Q] [Q] Q Q
  1172. 0 1 G + . . G G G G G G B B GB GB
  1173. 0T lt Gt t + . Gt G G Gt G G Bt Bt GBt GBt
  1174. 0O lt Gt t . + Gt Gt G Gt Gt G Bt Bt GBt GBt
  1175. 2 C P C C C + . . C - - CB CB B B
  1176. 2T Ct - Ct C C t + t - - - CBt CBt Bt Bt
  1177. 2O Ct - Ct C C t t + - - - CBt CBt Bt Bt
  1178. 3 [Q] p [Q] [Q] [Q] Q Q Q + . . [Q] [Q] Q Q
  1179. 3T [Qt] p [Qt][Q] [Q] Qt Qt Qt t + t [Qt][Qt] Qt Qt
  1180. 3O [Qt] p [Qt][Q] [Q] Qt Qt Qt t t + [Qt][Qt] Qt Qt
  1181. 4A lA G A T T GA GT GT GA GT GT + BA G GBA
  1182. 4O lA GBA A T T GA GT GT GA GT GT BA + GBA G
  1183. 6A CA PA CA C C A T tT PA P P C CBA + BA
  1184. 6O CA PBA CA C C A tT T PA P P CBA C BA +
  1185. Within the matrix,
  1186. "+" identifies entries where 'from' and 'to' are the same.
  1187. "-" means the transformation is not supported.
  1188. "." means nothing is necessary (a tRNS chunk can just be ignored).
  1189. "t" means the transformation is obtained by png_set_tRNS.
  1190. "A" means the transformation is obtained by png_set_add_alpha().
  1191. "X" means the transformation is obtained by png_set_expand().
  1192. "1" means the transformation is obtained by
  1193. png_set_expand_gray_1_2_4_to_8() (and by png_set_expand() if there
  1194. is no transparency in the original or the final format).
  1195. "C" means the transformation is obtained by png_set_gray_to_rgb().
  1196. "G" means the transformation is obtained by png_set_rgb_to_gray().
  1197. "P" means the transformation is obtained by
  1198. png_set_expand_palette_to_rgb().
  1199. "p" means the transformation is obtained by png_set_packing().
  1200. "Q" means the transformation is obtained by png_set_quantize().
  1201. "T" means the transformation is obtained by png_set_tRNS_to_alpha().
  1202. "B" means the transformation is obtained by png_set_background(), or
  1203. png_strip_alpha().
  1204. When an entry has multiple transforms listed all are required to cause the
  1205. right overall transformation. When two transforms are separated by a comma
  1206. either will do the job. When transforms are enclosed in [] the transform should
  1207. do the job but this is currently unimplemented - a different format will result
  1208. if the suggested transformations are used.
  1209. In PNG files, the alpha channel in an image
  1210. is the level of opacity. If you need the alpha channel in an image to
  1211. be the level of transparency instead of opacity, you can invert the
  1212. alpha channel (or the tRNS chunk data) after it's read, so that 0 is
  1213. fully opaque and 255 (in 8-bit or paletted images) or 65535 (in 16-bit
  1214. images) is fully transparent, with
  1215. png_set_invert_alpha(png_ptr);
  1216. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  1217. they can, resulting in, for example, 8 pixels per byte for 1 bit
  1218. files. This code expands to 1 pixel per byte without changing the
  1219. values of the pixels:
  1220. if (bit_depth < 8)
  1221. png_set_packing(png_ptr);
  1222. PNG files have possible bit depths of 1, 2, 4, 8, and 16. All pixels
  1223. stored in a PNG image have been "scaled" or "shifted" up to the next
  1224. higher possible bit depth (e.g. from 5 bits/sample in the range [0,31]
  1225. to 8 bits/sample in the range [0, 255]). However, it is also possible
  1226. to convert the PNG pixel data back to the original bit depth of the
  1227. image. This call reduces the pixels back down to the original bit depth:
  1228. png_color_8p sig_bit;
  1229. if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
  1230. png_set_shift(png_ptr, sig_bit);
  1231. PNG files store 3-color pixels in red, green, blue order. This code
  1232. changes the storage of the pixels to blue, green, red:
  1233. if (color_type == PNG_COLOR_TYPE_RGB ||
  1234. color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  1235. png_set_bgr(png_ptr);
  1236. PNG files store RGB pixels packed into 3 or 6 bytes. This code expands them
  1237. into 4 or 8 bytes for windowing systems that need them in this format:
  1238. if (color_type == PNG_COLOR_TYPE_RGB)
  1239. png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
  1240. where "filler" is the 8 or 16-bit number to fill with, and the location is
  1241. either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
  1242. you want the filler before the RGB or after. This transformation
  1243. does not affect images that already have full alpha channels. To add an
  1244. opaque alpha channel, use filler=0xff or 0xffff and PNG_FILLER_AFTER which
  1245. will generate RGBA pixels.
  1246. Note that png_set_filler() does not change the color type. If you want
  1247. to do that, you can add a true alpha channel with
  1248. if (color_type == PNG_COLOR_TYPE_RGB ||
  1249. color_type == PNG_COLOR_TYPE_GRAY)
  1250. png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER);
  1251. where "filler" contains the alpha value to assign to each pixel.
  1252. This function was added in libpng-1.2.7.
  1253. If you are reading an image with an alpha channel, and you need the
  1254. data as ARGB instead of the normal PNG format RGBA:
  1255. if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  1256. png_set_swap_alpha(png_ptr);
  1257. For some uses, you may want a grayscale image to be represented as
  1258. RGB. This code will do that conversion:
  1259. if (color_type == PNG_COLOR_TYPE_GRAY ||
  1260. color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  1261. png_set_gray_to_rgb(png_ptr);
  1262. Conversely, you can convert an RGB or RGBA image to grayscale or grayscale
  1263. with alpha.
  1264. if (color_type == PNG_COLOR_TYPE_RGB ||
  1265. color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  1266. png_set_rgb_to_gray(png_ptr, error_action, double red_weight,
  1267. double green_weight);
  1268. error_action = 1: silently do the conversion
  1269. error_action = 2: issue a warning if the original
  1270. image has any pixel where
  1271. red != green or red != blue
  1272. error_action = 3: issue an error and abort the
  1273. conversion if the original
  1274. image has any pixel where
  1275. red != green or red != blue
  1276. red_weight: weight of red component
  1277. green_weight: weight of green component
  1278. If either weight is negative, default
  1279. weights are used.
  1280. In the corresponding fixed point API the red_weight and green_weight values are
  1281. simply scaled by 100,000:
  1282. png_set_rgb_to_gray(png_ptr, error_action, png_fixed_point red_weight,
  1283. png_fixed_point green_weight);
  1284. If you have set error_action = 1 or 2, you can
  1285. later check whether the image really was gray, after processing
  1286. the image rows, with the png_get_rgb_to_gray_status(png_ptr) function.
  1287. It will return a png_byte that is zero if the image was gray or
  1288. 1 if there were any non-gray pixels. Background and sBIT data
  1289. will be silently converted to grayscale, using the green channel
  1290. data for sBIT, regardless of the error_action setting.
  1291. The default values come from the PNG file cHRM chunk if present; otherwise, the
  1292. defaults correspond to the ITU-R recommendation 709, and also the sRGB color
  1293. space, as recommended in the Charles Poynton's Colour FAQ,
  1294. <http://www.poynton.com/>, in section 9:
  1295. <http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html#RTFToC9>
  1296. Y = 0.2126 * R + 0.7152 * G + 0.0722 * B
  1297. Previous versions of this document, 1998 through 2002, recommended a slightly
  1298. different formula:
  1299. Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  1300. Libpng uses an integer approximation:
  1301. Y = (6968 * R + 23434 * G + 2366 * B)/32768
  1302. The calculation is done in a linear colorspace, if the image gamma
  1303. can be determined.
  1304. The png_set_background() function has been described already; it tells libpng to
  1305. composite images with alpha or simple transparency against the supplied
  1306. background color. For compatibility with versions of libpng earlier than
  1307. libpng-1.5.4 it is recommended that you call the function after reading the file
  1308. header, even if you don't want to use the color in a bKGD chunk, if one exists.
  1309. If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
  1310. you may use this color, or supply another color more suitable for
  1311. the current display (e.g., the background color from a web page). You
  1312. need to tell libpng how the color is represented, both the format of the
  1313. component values in the color (the number of bits) and the gamma encoding of the
  1314. color. The function takes two arguments, background_gamma_mode and need_expand
  1315. to convey this information, however only two combinations are likely to be
  1316. useful:
  1317. png_color_16 my_background;
  1318. png_color_16p image_background;
  1319. if (png_get_bKGD(png_ptr, info_ptr, &image_background))
  1320. png_set_background(png_ptr, image_background,
  1321. PNG_BACKGROUND_GAMMA_FILE, 1/*needs to be expanded*/, 1);
  1322. else
  1323. png_set_background(png_ptr, &my_background,
  1324. PNG_BACKGROUND_GAMMA_SCREEN, 0/*do not expand*/, 1);
  1325. The second call was described above - my_background is in the format of the
  1326. final, display, output produced by libpng. Because you now know the format of
  1327. the PNG it is possible to avoid the need to choose either 8-bit or 16-bit
  1328. output and to retain palette images (the palette colors will be modified
  1329. appropriately and the tRNS chunk removed.) However, if you are doing this,
  1330. take great care not to ask for transformations without checking first that
  1331. they apply!
  1332. In the first call the background color has the original bit depth and color type
  1333. of the PNG file. So, for palette images the color is supplied as a palette
  1334. index and for low bit greyscale images the color is a reduced bit value in
  1335. image_background->gray.
  1336. If you didn't call png_set_gamma() before reading the file header, for example
  1337. if you need your code to remain compatible with older versions of libpng prior
  1338. to libpng-1.5.4, this is the place to call it.
  1339. Do not call it if you called png_set_alpha_mode(); doing so will damage the
  1340. settings put in place by png_set_alpha_mode(). (If png_set_alpha_mode() is
  1341. supported then you can certainly do png_set_gamma() before reading the PNG
  1342. header.)
  1343. This API unconditionally sets the screen and file gamma values, so it will
  1344. override the value in the PNG file unless it is called before the PNG file
  1345. reading starts. For this reason you must always call it with the PNG file
  1346. value when you call it in this position:
  1347. if (png_get_gAMA(png_ptr, info_ptr, &file_gamma))
  1348. png_set_gamma(png_ptr, screen_gamma, file_gamma);
  1349. else
  1350. png_set_gamma(png_ptr, screen_gamma, 0.45455);
  1351. If you need to reduce an RGB file to a paletted file, or if a paletted
  1352. file has more entries then will fit on your screen, png_set_quantize()
  1353. will do that. Note that this is a simple match quantization that merely
  1354. finds the closest color available. This should work fairly well with
  1355. optimized palettes, but fairly badly with linear color cubes. If you
  1356. pass a palette that is larger than maximum_colors, the file will
  1357. reduce the number of colors in the palette so it will fit into
  1358. maximum_colors. If there is a histogram, libpng will use it to make
  1359. more intelligent choices when reducing the palette. If there is no
  1360. histogram, it may not do as good a job.
  1361. if (color_type & PNG_COLOR_MASK_COLOR)
  1362. {
  1363. if (png_get_valid(png_ptr, info_ptr,
  1364. PNG_INFO_PLTE))
  1365. {
  1366. png_uint_16p histogram = NULL;
  1367. png_get_hIST(png_ptr, info_ptr,
  1368. &histogram);
  1369. png_set_quantize(png_ptr, palette, num_palette,
  1370. max_screen_colors, histogram, 1);
  1371. }
  1372. else
  1373. {
  1374. png_color std_color_cube[MAX_SCREEN_COLORS] =
  1375. { ... colors ... };
  1376. png_set_quantize(png_ptr, std_color_cube,
  1377. MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
  1378. NULL,0);
  1379. }
  1380. }
  1381. PNG files describe monochrome as black being zero and white being one.
  1382. The following code will reverse this (make black be one and white be
  1383. zero):
  1384. if (bit_depth == 1 && color_type == PNG_COLOR_TYPE_GRAY)
  1385. png_set_invert_mono(png_ptr);
  1386. This function can also be used to invert grayscale and gray-alpha images:
  1387. if (color_type == PNG_COLOR_TYPE_GRAY ||
  1388. color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  1389. png_set_invert_mono(png_ptr);
  1390. PNG files store 16-bit pixels in network byte order (big-endian,
  1391. ie. most significant bits first). This code changes the storage to the
  1392. other way (little-endian, i.e. least significant bits first, the
  1393. way PCs store them):
  1394. if (bit_depth == 16)
  1395. png_set_swap(png_ptr);
  1396. If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
  1397. need to change the order the pixels are packed into bytes, you can use:
  1398. if (bit_depth < 8)
  1399. png_set_packswap(png_ptr);
  1400. Finally, you can write your own transformation function if none of
  1401. the existing ones meets your needs. This is done by setting a callback
  1402. with
  1403. png_set_read_user_transform_fn(png_ptr,
  1404. read_transform_fn);
  1405. You must supply the function
  1406. void read_transform_fn(png_structp png_ptr, png_row_infop
  1407. row_info, png_bytep data)
  1408. See pngtest.c for a working example. Your function will be called
  1409. after all of the other transformations have been processed. Take care with
  1410. interlaced images if you do the interlace yourself - the width of the row is the
  1411. width in 'row_info', not the overall image width.
  1412. If supported, libpng provides two information routines that you can use to find
  1413. where you are in processing the image:
  1414. png_get_current_pass_number(png_structp png_ptr);
  1415. png_get_current_row_number(png_structp png_ptr);
  1416. Don't try using these outside a transform callback - firstly they are only
  1417. supported if user transforms are supported, secondly they may well return
  1418. unexpected results unless the row is actually being processed at the moment they
  1419. are called.
  1420. With interlaced
  1421. images the value returned is the row in the input sub-image image. Use
  1422. PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
  1423. find the output pixel (x,y) given an interlaced sub-image pixel (row,col,pass).
  1424. The discussion of interlace handling above contains more information on how to
  1425. use these values.
  1426. You can also set up a pointer to a user structure for use by your
  1427. callback function, and you can inform libpng that your transform
  1428. function will change the number of channels or bit depth with the
  1429. function
  1430. png_set_user_transform_info(png_ptr, user_ptr,
  1431. user_depth, user_channels);
  1432. The user's application, not libpng, is responsible for allocating and
  1433. freeing any memory required for the user structure.
  1434. You can retrieve the pointer via the function
  1435. png_get_user_transform_ptr(). For example:
  1436. voidp read_user_transform_ptr =
  1437. png_get_user_transform_ptr(png_ptr);
  1438. The last thing to handle is interlacing; this is covered in detail below,
  1439. but you must call the function here if you want libpng to handle expansion
  1440. of the interlaced image.
  1441. number_of_passes = png_set_interlace_handling(png_ptr);
  1442. After setting the transformations, libpng can update your png_info
  1443. structure to reflect any transformations you've requested with this
  1444. call.
  1445. png_read_update_info(png_ptr, info_ptr);
  1446. This is most useful to update the info structure's rowbytes
  1447. field so you can use it to allocate your image memory. This function
  1448. will also update your palette with the correct screen_gamma and
  1449. background if these have been given with the calls above. You may
  1450. only call png_read_update_info() once with a particular info_ptr.
  1451. After you call png_read_update_info(), you can allocate any
  1452. memory you need to hold the image. The row data is simply
  1453. raw byte data for all forms of images. As the actual allocation
  1454. varies among applications, no example will be given. If you
  1455. are allocating one large chunk, you will need to build an
  1456. array of pointers to each row, as it will be needed for some
  1457. of the functions below.
  1458. Remember: Before you call png_read_update_info(), the png_get_*()
  1459. functions return the values corresponding to the original PNG image.
  1460. After you call png_read_update_info the values refer to the image
  1461. that libpng will output. Consequently you must call all the png_set_
  1462. functions before you call png_read_update_info(). This is particularly
  1463. important for png_set_interlace_handling() - if you are going to call
  1464. png_read_update_info() you must call png_set_interlace_handling() before
  1465. it unless you want to receive interlaced output.
  1466. Reading image data
  1467. After you've allocated memory, you can read the image data.
  1468. The simplest way to do this is in one function call. If you are
  1469. allocating enough memory to hold the whole image, you can just
  1470. call png_read_image() and libpng will read in all the image data
  1471. and put it in the memory area supplied. You will need to pass in
  1472. an array of pointers to each row.
  1473. This function automatically handles interlacing, so you don't
  1474. need to call png_set_interlace_handling() (unless you call
  1475. png_read_update_info()) or call this function multiple times, or any
  1476. of that other stuff necessary with png_read_rows().
  1477. png_read_image(png_ptr, row_pointers);
  1478. where row_pointers is:
  1479. png_bytep row_pointers[height];
  1480. You can point to void or char or whatever you use for pixels.
  1481. If you don't want to read in the whole image at once, you can
  1482. use png_read_rows() instead. If there is no interlacing (check
  1483. interlace_type == PNG_INTERLACE_NONE), this is simple:
  1484. png_read_rows(png_ptr, row_pointers, NULL,
  1485. number_of_rows);
  1486. where row_pointers is the same as in the png_read_image() call.
  1487. If you are doing this just one row at a time, you can do this with
  1488. a single row_pointer instead of an array of row_pointers:
  1489. png_bytep row_pointer = row;
  1490. png_read_row(png_ptr, row_pointer, NULL);
  1491. If the file is interlaced (interlace_type != 0 in the IHDR chunk), things
  1492. get somewhat harder. The only current (PNG Specification version 1.2)
  1493. interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7);
  1494. a somewhat complicated 2D interlace scheme, known as Adam7, that
  1495. breaks down an image into seven smaller images of varying size, based
  1496. on an 8x8 grid. This number is defined (from libpng 1.5) as
  1497. PNG_INTERLACE_ADAM7_PASSES in png.h
  1498. libpng can fill out those images or it can give them to you "as is".
  1499. It is almost always better to have libpng handle the interlacing for you.
  1500. If you want the images filled out, there are two ways to do that. The one
  1501. mentioned in the PNG specification is to expand each pixel to cover
  1502. those pixels that have not been read yet (the "rectangle" method).
  1503. This results in a blocky image for the first pass, which gradually
  1504. smooths out as more pixels are read. The other method is the "sparkle"
  1505. method, where pixels are drawn only in their final locations, with the
  1506. rest of the image remaining whatever colors they were initialized to
  1507. before the start of the read. The first method usually looks better,
  1508. but tends to be slower, as there are more pixels to put in the rows.
  1509. If, as is likely, you want libpng to expand the images, call this before
  1510. calling png_start_read_image() or png_read_update_info():
  1511. if (interlace_type == PNG_INTERLACE_ADAM7)
  1512. number_of_passes
  1513. = png_set_interlace_handling(png_ptr);
  1514. This will return the number of passes needed. Currently, this is seven,
  1515. but may change if another interlace type is added. This function can be
  1516. called even if the file is not interlaced, where it will return one pass.
  1517. You then need to read the whole image 'number_of_passes' times. Each time
  1518. will distribute the pixels from the current pass to the correct place in
  1519. the output image, so you need to supply the same rows to png_read_rows in
  1520. each pass.
  1521. If you are not going to display the image after each pass, but are
  1522. going to wait until the entire image is read in, use the sparkle
  1523. effect. This effect is faster and the end result of either method
  1524. is exactly the same. If you are planning on displaying the image
  1525. after each pass, the "rectangle" effect is generally considered the
  1526. better looking one.
  1527. If you only want the "sparkle" effect, just call png_read_rows() as
  1528. normal, with the third parameter NULL. Make sure you make pass over
  1529. the image number_of_passes times, and you don't change the data in the
  1530. rows between calls. You can change the locations of the data, just
  1531. not the data. Each pass only writes the pixels appropriate for that
  1532. pass, and assumes the data from previous passes is still valid.
  1533. png_read_rows(png_ptr, row_pointers, NULL,
  1534. number_of_rows);
  1535. If you only want the first effect (the rectangles), do the same as
  1536. before except pass the row buffer in the third parameter, and leave
  1537. the second parameter NULL.
  1538. png_read_rows(png_ptr, NULL, row_pointers,
  1539. number_of_rows);
  1540. If you don't want libpng to handle the interlacing details, just call
  1541. png_read_rows() PNG_INTERLACE_ADAM7_PASSES times to read in all the images.
  1542. Each of the images is a valid image by itself, however you will almost
  1543. certainly need to distribute the pixels from each sub-image to the
  1544. correct place. This is where everything gets very tricky.
  1545. If you want to retrieve the separate images you must pass the correct
  1546. number of rows to each successive call of png_read_rows(). The calculation
  1547. gets pretty complicated for small images, where some sub-images may
  1548. not even exist because either their width or height ends up zero.
  1549. libpng provides two macros to help you in 1.5 and later versions:
  1550. png_uint_32 width = PNG_PASS_COLS(image_width, pass_number);
  1551. png_uint_32 height = PNG_PASS_ROWS(image_height, pass_number);
  1552. Respectively these tell you the width and height of the sub-image
  1553. corresponding to the numbered pass. 'pass' is in in the range 0 to 6 -
  1554. this can be confusing because the specification refers to the same passes
  1555. as 1 to 7! Be careful, you must check both the width and height before
  1556. calling png_read_rows() and not call it for that pass if either is zero.
  1557. You can, of course, read each sub-image row by row. If you want to
  1558. produce optimal code to make a pixel-by-pixel transformation of an
  1559. interlaced image this is the best approach; read each row of each pass,
  1560. transform it, and write it out to a new interlaced image.
  1561. If you want to de-interlace the image yourself libpng provides further
  1562. macros to help that tell you where to place the pixels in the output image.
  1563. Because the interlacing scheme is rectangular - sub-image pixels are always
  1564. arranged on a rectangular grid - all you need to know for each pass is the
  1565. starting column and row in the output image of the first pixel plus the
  1566. spacing between each pixel. As of libpng 1.5 there are four macros to
  1567. retrieve this information:
  1568. png_uint_32 x = PNG_PASS_START_COL(pass);
  1569. png_uint_32 y = PNG_PASS_START_ROW(pass);
  1570. png_uint_32 xStep = 1U << PNG_PASS_COL_SHIFT(pass);
  1571. png_uint_32 yStep = 1U << PNG_PASS_ROW_SHIFT(pass);
  1572. These allow you to write the obvious loop:
  1573. png_uint_32 input_y = 0;
  1574. png_uint_32 output_y = PNG_PASS_START_ROW(pass);
  1575. while (output_y < output_image_height)
  1576. {
  1577. png_uint_32 input_x = 0;
  1578. png_uint_32 output_x = PNG_PASS_START_COL(pass);
  1579. while (output_x < output_image_width)
  1580. {
  1581. image[output_y][output_x] =
  1582. subimage[pass][input_y][input_x++];
  1583. output_x += xStep;
  1584. }
  1585. ++input_y;
  1586. output_y += yStep;
  1587. }
  1588. Notice that the steps between successive output rows and columns are
  1589. returned as shifts. This is possible because the pixels in the subimages
  1590. are always a power of 2 apart - 1, 2, 4 or 8 pixels - in the original
  1591. image. In practice you may need to directly calculate the output coordinate
  1592. given an input coordinate. libpng provides two further macros for this
  1593. purpose:
  1594. png_uint_32 output_x = PNG_COL_FROM_PASS_COL(input_x, pass);
  1595. png_uint_32 output_y = PNG_ROW_FROM_PASS_ROW(input_y, pass);
  1596. Finally a pair of macros are provided to tell you if a particular image
  1597. row or column appears in a given pass:
  1598. int col_in_pass = PNG_COL_IN_INTERLACE_PASS(output_x, pass);
  1599. int row_in_pass = PNG_ROW_IN_INTERLACE_PASS(output_y, pass);
  1600. Bear in mind that you will probably also need to check the width and height
  1601. of the pass in addition to the above to be sure the pass even exists!
  1602. With any luck you are convinced by now that you don't want to do your own
  1603. interlace handling. In reality normally the only good reason for doing this
  1604. is if you are processing PNG files on a pixel-by-pixel basis and don't want
  1605. to load the whole file into memory when it is interlaced.
  1606. libpng includes a test program, pngvalid, that illustrates reading and
  1607. writing of interlaced images. If you can't get interlacing to work in your
  1608. code and don't want to leave it to libpng (the recommended approach), see
  1609. how pngvalid.c does it.
  1610. Finishing a sequential read
  1611. After you are finished reading the image through the
  1612. low-level interface, you can finish reading the file. If you are
  1613. interested in comments or time, which may be stored either before or
  1614. after the image data, you should pass the separate png_info struct if
  1615. you want to keep the comments from before and after the image
  1616. separate.
  1617. png_infop end_info = png_create_info_struct(png_ptr);
  1618. if (!end_info)
  1619. {
  1620. png_destroy_read_struct(&png_ptr, &info_ptr,
  1621. (png_infopp)NULL);
  1622. return (ERROR);
  1623. }
  1624. png_read_end(png_ptr, end_info);
  1625. If you are not interested, you should still call png_read_end()
  1626. but you can pass NULL, avoiding the need to create an end_info structure.
  1627. png_read_end(png_ptr, (png_infop)NULL);
  1628. If you don't call png_read_end(), then your file pointer will be
  1629. left pointing to the first chunk after the last IDAT, which is probably
  1630. not what you want if you expect to read something beyond the end of
  1631. the PNG datastream.
  1632. When you are done, you can free all memory allocated by libpng like this:
  1633. png_destroy_read_struct(&png_ptr, &info_ptr,
  1634. &end_info);
  1635. or, if you didn't create an end_info structure,
  1636. png_destroy_read_struct(&png_ptr, &info_ptr,
  1637. (png_infopp)NULL);
  1638. It is also possible to individually free the info_ptr members that
  1639. point to libpng-allocated storage with the following function:
  1640. png_free_data(png_ptr, info_ptr, mask, seq)
  1641. mask - identifies data to be freed, a mask
  1642. containing the bitwise OR of one or
  1643. more of
  1644. PNG_FREE_PLTE, PNG_FREE_TRNS,
  1645. PNG_FREE_HIST, PNG_FREE_ICCP,
  1646. PNG_FREE_PCAL, PNG_FREE_ROWS,
  1647. PNG_FREE_SCAL, PNG_FREE_SPLT,
  1648. PNG_FREE_TEXT, PNG_FREE_UNKN,
  1649. or simply PNG_FREE_ALL
  1650. seq - sequence number of item to be freed
  1651. (-1 for all items)
  1652. This function may be safely called when the relevant storage has
  1653. already been freed, or has not yet been allocated, or was allocated
  1654. by the user and not by libpng, and will in those cases do nothing.
  1655. The "seq" parameter is ignored if only one item of the selected data
  1656. type, such as PLTE, is allowed. If "seq" is not -1, and multiple items
  1657. are allowed for the data type identified in the mask, such as text or
  1658. sPLT, only the n'th item in the structure is freed, where n is "seq".
  1659. The default behavior is only to free data that was allocated internally
  1660. by libpng. This can be changed, so that libpng will not free the data,
  1661. or so that it will free data that was allocated by the user with png_malloc()
  1662. or png_zalloc() and passed in via a png_set_*() function, with
  1663. png_data_freer(png_ptr, info_ptr, freer, mask)
  1664. freer - one of
  1665. PNG_DESTROY_WILL_FREE_DATA
  1666. PNG_SET_WILL_FREE_DATA
  1667. PNG_USER_WILL_FREE_DATA
  1668. mask - which data elements are affected
  1669. same choices as in png_free_data()
  1670. This function only affects data that has already been allocated.
  1671. You can call this function after reading the PNG data but before calling
  1672. any png_set_*() functions, to control whether the user or the png_set_*()
  1673. function is responsible for freeing any existing data that might be present,
  1674. and again after the png_set_*() functions to control whether the user
  1675. or png_destroy_*() is supposed to free the data. When the user assumes
  1676. responsibility for libpng-allocated data, the application must use
  1677. png_free() to free it, and when the user transfers responsibility to libpng
  1678. for data that the user has allocated, the user must have used png_malloc()
  1679. or png_zalloc() to allocate it.
  1680. If you allocated your row_pointers in a single block, as suggested above in
  1681. the description of the high level read interface, you must not transfer
  1682. responsibility for freeing it to the png_set_rows or png_read_destroy function,
  1683. because they would also try to free the individual row_pointers[i].
  1684. If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
  1685. separately, do not transfer responsibility for freeing text_ptr to libpng,
  1686. because when libpng fills a png_text structure it combines these members with
  1687. the key member, and png_free_data() will free only text_ptr.key. Similarly,
  1688. if you transfer responsibility for free'ing text_ptr from libpng to your
  1689. application, your application must not separately free those members.
  1690. The png_free_data() function will turn off the "valid" flag for anything
  1691. it frees. If you need to turn the flag off for a chunk that was freed by
  1692. your application instead of by libpng, you can use
  1693. png_set_invalid(png_ptr, info_ptr, mask);
  1694. mask - identifies the chunks to be made invalid,
  1695. containing the bitwise OR of one or
  1696. more of
  1697. PNG_INFO_gAMA, PNG_INFO_sBIT,
  1698. PNG_INFO_cHRM, PNG_INFO_PLTE,
  1699. PNG_INFO_tRNS, PNG_INFO_bKGD,
  1700. PNG_INFO_hIST, PNG_INFO_pHYs,
  1701. PNG_INFO_oFFs, PNG_INFO_tIME,
  1702. PNG_INFO_pCAL, PNG_INFO_sRGB,
  1703. PNG_INFO_iCCP, PNG_INFO_sPLT,
  1704. PNG_INFO_sCAL, PNG_INFO_IDAT
  1705. For a more compact example of reading a PNG image, see the file example.c.
  1706. Reading PNG files progressively
  1707. The progressive reader is slightly different then the non-progressive
  1708. reader. Instead of calling png_read_info(), png_read_rows(), and
  1709. png_read_end(), you make one call to png_process_data(), which calls
  1710. callbacks when it has the info, a row, or the end of the image. You
  1711. set up these callbacks with png_set_progressive_read_fn(). You don't
  1712. have to worry about the input/output functions of libpng, as you are
  1713. giving the library the data directly in png_process_data(). I will
  1714. assume that you have read the section on reading PNG files above,
  1715. so I will only highlight the differences (although I will show
  1716. all of the code).
  1717. png_structp png_ptr;
  1718. png_infop info_ptr;
  1719. /* An example code fragment of how you would
  1720. initialize the progressive reader in your
  1721. application. */
  1722. int
  1723. initialize_png_reader()
  1724. {
  1725. png_ptr = png_create_read_struct
  1726. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  1727. user_error_fn, user_warning_fn);
  1728. if (!png_ptr)
  1729. return (ERROR);
  1730. info_ptr = png_create_info_struct(png_ptr);
  1731. if (!info_ptr)
  1732. {
  1733. png_destroy_read_struct(&png_ptr,
  1734. (png_infopp)NULL, (png_infopp)NULL);
  1735. return (ERROR);
  1736. }
  1737. if (setjmp(png_jmpbuf(png_ptr)))
  1738. {
  1739. png_destroy_read_struct(&png_ptr, &info_ptr,
  1740. (png_infopp)NULL);
  1741. return (ERROR);
  1742. }
  1743. /* This one's new. You can provide functions
  1744. to be called when the header info is valid,
  1745. when each row is completed, and when the image
  1746. is finished. If you aren't using all functions,
  1747. you can specify NULL parameters. Even when all
  1748. three functions are NULL, you need to call
  1749. png_set_progressive_read_fn(). You can use
  1750. any struct as the user_ptr (cast to a void pointer
  1751. for the function call), and retrieve the pointer
  1752. from inside the callbacks using the function
  1753. png_get_progressive_ptr(png_ptr);
  1754. which will return a void pointer, which you have
  1755. to cast appropriately.
  1756. */
  1757. png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
  1758. info_callback, row_callback, end_callback);
  1759. return 0;
  1760. }
  1761. /* A code fragment that you call as you receive blocks
  1762. of data */
  1763. int
  1764. process_data(png_bytep buffer, png_uint_32 length)
  1765. {
  1766. if (setjmp(png_jmpbuf(png_ptr)))
  1767. {
  1768. png_destroy_read_struct(&png_ptr, &info_ptr,
  1769. (png_infopp)NULL);
  1770. return (ERROR);
  1771. }
  1772. /* This one's new also. Simply give it a chunk
  1773. of data from the file stream (in order, of
  1774. course). On machines with segmented memory
  1775. models machines, don't give it any more than
  1776. 64K. The library seems to run fine with sizes
  1777. of 4K. Although you can give it much less if
  1778. necessary (I assume you can give it chunks of
  1779. 1 byte, I haven't tried less then 256 bytes
  1780. yet). When this function returns, you may
  1781. want to display any rows that were generated
  1782. in the row callback if you don't already do
  1783. so there.
  1784. */
  1785. png_process_data(png_ptr, info_ptr, buffer, length);
  1786. /* At this point you can call png_process_data_skip if
  1787. you want to handle data the library will skip yourself;
  1788. it simply returns the number of bytes to skip (and stops
  1789. libpng skipping that number of bytes on the next
  1790. png_process_data call).
  1791. return 0;
  1792. }
  1793. /* This function is called (as set by
  1794. png_set_progressive_read_fn() above) when enough data
  1795. has been supplied so all of the header has been
  1796. read.
  1797. */
  1798. void
  1799. info_callback(png_structp png_ptr, png_infop info)
  1800. {
  1801. /* Do any setup here, including setting any of
  1802. the transformations mentioned in the Reading
  1803. PNG files section. For now, you _must_ call
  1804. either png_start_read_image() or
  1805. png_read_update_info() after all the
  1806. transformations are set (even if you don't set
  1807. any). You may start getting rows before
  1808. png_process_data() returns, so this is your
  1809. last chance to prepare for that.
  1810. This is where you turn on interlace handling,
  1811. assuming you don't want to do it yourself.
  1812. If you need to you can stop the processing of
  1813. your original input data at this point by calling
  1814. png_process_data_pause. This returns the number
  1815. of unprocessed bytes from the last png_process_data
  1816. call - it is up to you to ensure that the next call
  1817. sees these bytes again. If you don't want to bother
  1818. with this you can get libpng to cache the unread
  1819. bytes by setting the 'save' parameter (see png.h) but
  1820. then libpng will have to copy the data internally.
  1821. */
  1822. }
  1823. /* This function is called when each row of image
  1824. data is complete */
  1825. void
  1826. row_callback(png_structp png_ptr, png_bytep new_row,
  1827. png_uint_32 row_num, int pass)
  1828. {
  1829. /* If the image is interlaced, and you turned
  1830. on the interlace handler, this function will
  1831. be called for every row in every pass. Some
  1832. of these rows will not be changed from the
  1833. previous pass. When the row is not changed,
  1834. the new_row variable will be NULL. The rows
  1835. and passes are called in order, so you don't
  1836. really need the row_num and pass, but I'm
  1837. supplying them because it may make your life
  1838. easier.
  1839. If you did not turn on interlace handling then
  1840. the callback is called for each row of each
  1841. sub-image when the image is interlaced. In this
  1842. case 'row_num' is the row in the sub-image, not
  1843. the row in the output image as it is in all other
  1844. cases.
  1845. For the non-NULL rows of interlaced images when
  1846. you have switched on libpng interlace handling,
  1847. you must call png_progressive_combine_row()
  1848. passing in the row and the old row. You can
  1849. call this function for NULL rows (it will just
  1850. return) and for non-interlaced images (it just
  1851. does the memcpy for you) if it will make the
  1852. code easier. Thus, you can just do this for
  1853. all cases if you switch on interlace handling;
  1854. */
  1855. png_progressive_combine_row(png_ptr, old_row,
  1856. new_row);
  1857. /* where old_row is what was displayed for
  1858. previously for the row. Note that the first
  1859. pass (pass == 0, really) will completely cover
  1860. the old row, so the rows do not have to be
  1861. initialized. After the first pass (and only
  1862. for interlaced images), you will have to pass
  1863. the current row, and the function will combine
  1864. the old row and the new row.
  1865. You can also call png_process_data_pause in this
  1866. callback - see above.
  1867. */
  1868. }
  1869. void
  1870. end_callback(png_structp png_ptr, png_infop info)
  1871. {
  1872. /* This function is called after the whole image
  1873. has been read, including any chunks after the
  1874. image (up to and including the IEND). You
  1875. will usually have the same info chunk as you
  1876. had in the header, although some data may have
  1877. been added to the comments and time fields.
  1878. Most people won't do much here, perhaps setting
  1879. a flag that marks the image as finished.
  1880. */
  1881. }
  1882. IV. Writing
  1883. Much of this is very similar to reading. However, everything of
  1884. importance is repeated here, so you won't have to constantly look
  1885. back up in the reading section to understand writing.
  1886. Setup
  1887. You will want to do the I/O initialization before you get into libpng,
  1888. so if it doesn't work, you don't have anything to undo. If you are not
  1889. using the standard I/O functions, you will need to replace them with
  1890. custom writing functions. See the discussion under Customizing libpng.
  1891. FILE *fp = fopen(file_name, "wb");
  1892. if (!fp)
  1893. return (ERROR);
  1894. Next, png_struct and png_info need to be allocated and initialized.
  1895. As these can be both relatively large, you may not want to store these
  1896. on the stack, unless you have stack space to spare. Of course, you
  1897. will want to check if they return NULL. If you are also reading,
  1898. you won't want to name your read structure and your write structure
  1899. both "png_ptr"; you can call them anything you like, such as
  1900. "read_ptr" and "write_ptr". Look at pngtest.c, for example.
  1901. png_structp png_ptr = png_create_write_struct
  1902. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  1903. user_error_fn, user_warning_fn);
  1904. if (!png_ptr)
  1905. return (ERROR);
  1906. png_infop info_ptr = png_create_info_struct(png_ptr);
  1907. if (!info_ptr)
  1908. {
  1909. png_destroy_write_struct(&png_ptr,
  1910. (png_infopp)NULL);
  1911. return (ERROR);
  1912. }
  1913. If you want to use your own memory allocation routines,
  1914. define PNG_USER_MEM_SUPPORTED and use
  1915. png_create_write_struct_2() instead of png_create_write_struct():
  1916. png_structp png_ptr = png_create_write_struct_2
  1917. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  1918. user_error_fn, user_warning_fn, (png_voidp)
  1919. user_mem_ptr, user_malloc_fn, user_free_fn);
  1920. After you have these structures, you will need to set up the
  1921. error handling. When libpng encounters an error, it expects to
  1922. longjmp() back to your routine. Therefore, you will need to call
  1923. setjmp() and pass the png_jmpbuf(png_ptr). If you
  1924. write the file from different routines, you will need to update
  1925. the png_jmpbuf(png_ptr) every time you enter a new routine that will
  1926. call a png_*() function. See your documentation of setjmp/longjmp
  1927. for your compiler for more information on setjmp/longjmp. See
  1928. the discussion on libpng error handling in the Customizing Libpng
  1929. section below for more information on the libpng error handling.
  1930. if (setjmp(png_jmpbuf(png_ptr)))
  1931. {
  1932. png_destroy_write_struct(&png_ptr, &info_ptr);
  1933. fclose(fp);
  1934. return (ERROR);
  1935. }
  1936. ...
  1937. return;
  1938. If you would rather avoid the complexity of setjmp/longjmp issues,
  1939. you can compile libpng with PNG_NO_SETJMP, in which case
  1940. errors will result in a call to PNG_ABORT() which defaults to abort().
  1941. You can #define PNG_ABORT() to a function that does something
  1942. more useful than abort(), as long as your function does not
  1943. return.
  1944. Now you need to set up the output code. The default for libpng is to
  1945. use the C function fwrite(). If you use this, you will need to pass a
  1946. valid FILE * in the function png_init_io(). Be sure that the file is
  1947. opened in binary mode. Again, if you wish to handle writing data in
  1948. another way, see the discussion on libpng I/O handling in the Customizing
  1949. Libpng section below.
  1950. png_init_io(png_ptr, fp);
  1951. If you are embedding your PNG into a datastream such as MNG, and don't
  1952. want libpng to write the 8-byte signature, or if you have already
  1953. written the signature in your application, use
  1954. png_set_sig_bytes(png_ptr, 8);
  1955. to inform libpng that it should not write a signature.
  1956. Write callbacks
  1957. At this point, you can set up a callback function that will be
  1958. called after each row has been written, which you can use to control
  1959. a progress meter or the like. It's demonstrated in pngtest.c.
  1960. You must supply a function
  1961. void write_row_callback(png_structp png_ptr, png_uint_32 row,
  1962. int pass);
  1963. {
  1964. /* put your code here */
  1965. }
  1966. (You can give it another name that you like instead of "write_row_callback")
  1967. To inform libpng about your function, use
  1968. png_set_write_status_fn(png_ptr, write_row_callback);
  1969. When this function is called the row has already been completely processed and
  1970. it has also been written out. The 'row' and 'pass' refer to the next row to be
  1971. handled. For the
  1972. non-interlaced case the row that was just handled is simply one less than the
  1973. passed in row number, and pass will always be 0. For the interlaced case the
  1974. same applies unless the row value is 0, in which case the row just handled was
  1975. the last one from one of the preceding passes. Because interlacing may skip a
  1976. pass you cannot be sure that the preceding pass is just 'pass-1', if you really
  1977. need to know what the last pass is record (row,pass) from the callback and use
  1978. the last recorded value each time.
  1979. As with the user transform you can find the output row using the
  1980. PNG_ROW_FROM_PASS_ROW macro.
  1981. You now have the option of modifying how the compression library will
  1982. run. The following functions are mainly for testing, but may be useful
  1983. in some cases, like if you need to write PNG files extremely fast and
  1984. are willing to give up some compression, or if you want to get the
  1985. maximum possible compression at the expense of slower writing. If you
  1986. have no special needs in this area, let the library do what it wants by
  1987. not calling this function at all, as it has been tuned to deliver a good
  1988. speed/compression ratio. The second parameter to png_set_filter() is
  1989. the filter method, for which the only valid values are 0 (as of the
  1990. July 1999 PNG specification, version 1.2) or 64 (if you are writing
  1991. a PNG datastream that is to be embedded in a MNG datastream). The third
  1992. parameter is a flag that indicates which filter type(s) are to be tested
  1993. for each scanline. See the PNG specification for details on the specific
  1994. filter types.
  1995. /* turn on or off filtering, and/or choose
  1996. specific filters. You can use either a single
  1997. PNG_FILTER_VALUE_NAME or the bitwise OR of one
  1998. or more PNG_FILTER_NAME masks.
  1999. */
  2000. png_set_filter(png_ptr, 0,
  2001. PNG_FILTER_NONE | PNG_FILTER_VALUE_NONE |
  2002. PNG_FILTER_SUB | PNG_FILTER_VALUE_SUB |
  2003. PNG_FILTER_UP | PNG_FILTER_VALUE_UP |
  2004. PNG_FILTER_AVG | PNG_FILTER_VALUE_AVG |
  2005. PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH|
  2006. PNG_ALL_FILTERS);
  2007. If an application wants to start and stop using particular filters during
  2008. compression, it should start out with all of the filters (to ensure that
  2009. the previous row of pixels will be stored in case it's needed later),
  2010. and then add and remove them after the start of compression.
  2011. If you are writing a PNG datastream that is to be embedded in a MNG
  2012. datastream, the second parameter can be either 0 or 64.
  2013. The png_set_compression_*() functions interface to the zlib compression
  2014. library, and should mostly be ignored unless you really know what you are
  2015. doing. The only generally useful call is png_set_compression_level()
  2016. which changes how much time zlib spends on trying to compress the image
  2017. data. See the Compression Library (zlib.h and algorithm.txt, distributed
  2018. with zlib) for details on the compression levels.
  2019. #include zlib.h
  2020. /* Set the zlib compression level */
  2021. png_set_compression_level(png_ptr,
  2022. Z_BEST_COMPRESSION);
  2023. /* Set other zlib parameters for compressing IDAT */
  2024. png_set_compression_mem_level(png_ptr, 8);
  2025. png_set_compression_strategy(png_ptr,
  2026. Z_DEFAULT_STRATEGY);
  2027. png_set_compression_window_bits(png_ptr, 15);
  2028. png_set_compression_method(png_ptr, 8);
  2029. png_set_compression_buffer_size(png_ptr, 8192)
  2030. /* Set zlib parameters for text compression
  2031. * If you don't call these, the parameters
  2032. * fall back on those defined for IDAT chunks
  2033. */
  2034. png_set_text_compression_mem_level(png_ptr, 8);
  2035. png_set_text_compression_strategy(png_ptr,
  2036. Z_DEFAULT_STRATEGY);
  2037. png_set_text_compression_window_bits(png_ptr, 15);
  2038. png_set_text_compression_method(png_ptr, 8);
  2039. Setting the contents of info for output
  2040. You now need to fill in the png_info structure with all the data you
  2041. wish to write before the actual image. Note that the only thing you
  2042. are allowed to write after the image is the text chunks and the time
  2043. chunk (as of PNG Specification 1.2, anyway). See png_write_end() and
  2044. the latest PNG specification for more information on that. If you
  2045. wish to write them before the image, fill them in now, and flag that
  2046. data as being valid. If you want to wait until after the data, don't
  2047. fill them until png_write_end(). For all the fields in png_info and
  2048. their data types, see png.h. For explanations of what the fields
  2049. contain, see the PNG specification.
  2050. Some of the more important parts of the png_info are:
  2051. png_set_IHDR(png_ptr, info_ptr, width, height,
  2052. bit_depth, color_type, interlace_type,
  2053. compression_type, filter_method)
  2054. width - holds the width of the image
  2055. in pixels (up to 2^31).
  2056. height - holds the height of the image
  2057. in pixels (up to 2^31).
  2058. bit_depth - holds the bit depth of one of the
  2059. image channels.
  2060. (valid values are 1, 2, 4, 8, 16
  2061. and depend also on the
  2062. color_type. See also significant
  2063. bits (sBIT) below).
  2064. color_type - describes which color/alpha
  2065. channels are present.
  2066. PNG_COLOR_TYPE_GRAY
  2067. (bit depths 1, 2, 4, 8, 16)
  2068. PNG_COLOR_TYPE_GRAY_ALPHA
  2069. (bit depths 8, 16)
  2070. PNG_COLOR_TYPE_PALETTE
  2071. (bit depths 1, 2, 4, 8)
  2072. PNG_COLOR_TYPE_RGB
  2073. (bit_depths 8, 16)
  2074. PNG_COLOR_TYPE_RGB_ALPHA
  2075. (bit_depths 8, 16)
  2076. PNG_COLOR_MASK_PALETTE
  2077. PNG_COLOR_MASK_COLOR
  2078. PNG_COLOR_MASK_ALPHA
  2079. interlace_type - PNG_INTERLACE_NONE or
  2080. PNG_INTERLACE_ADAM7
  2081. compression_type - (must be
  2082. PNG_COMPRESSION_TYPE_DEFAULT)
  2083. filter_method - (must be PNG_FILTER_TYPE_DEFAULT
  2084. or, if you are writing a PNG to
  2085. be embedded in a MNG datastream,
  2086. can also be
  2087. PNG_INTRAPIXEL_DIFFERENCING)
  2088. If you call png_set_IHDR(), the call must appear before any of the
  2089. other png_set_*() functions, because they might require access to some of
  2090. the IHDR settings. The remaining png_set_*() functions can be called
  2091. in any order.
  2092. If you wish, you can reset the compression_type, interlace_type, or
  2093. filter_method later by calling png_set_IHDR() again; if you do this, the
  2094. width, height, bit_depth, and color_type must be the same in each call.
  2095. png_set_PLTE(png_ptr, info_ptr, palette,
  2096. num_palette);
  2097. palette - the palette for the file
  2098. (array of png_color)
  2099. num_palette - number of entries in the palette
  2100. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  2101. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  2102. file_gamma - the gamma at which the image was
  2103. created (PNG_INFO_gAMA)
  2104. int_file_gamma - 100,000 times the gamma at which
  2105. the image was created
  2106. png_set_cHRM(png_ptr, info_ptr, white_x, white_y, red_x, red_y,
  2107. green_x, green_y, blue_x, blue_y)
  2108. png_set_cHRM_XYZ(png_ptr, info_ptr, red_X, red_Y, red_Z, green_X,
  2109. green_Y, green_Z, blue_X, blue_Y, blue_Z)
  2110. png_set_cHRM_fixed(png_ptr, info_ptr, int_white_x, int_white_y,
  2111. int_red_x, int_red_y, int_green_x, int_green_y,
  2112. int_blue_x, int_blue_y)
  2113. png_set_cHRM_XYZ_fixed(png_ptr, info_ptr, int_red_X, int_red_Y,
  2114. int_red_Z, int_green_X, int_green_Y, int_green_Z,
  2115. int_blue_X, int_blue_Y, int_blue_Z)
  2116. {white,red,green,blue}_{x,y}
  2117. A color space encoding specified using the chromaticities
  2118. of the end points and the white point.
  2119. {red,green,blue}_{X,Y,Z}
  2120. A color space encoding specified using the encoding end
  2121. points - the CIE tristimulus specification of the intended
  2122. color of the red, green and blue channels in the PNG RGB
  2123. data. The white point is simply the sum of the three end
  2124. points.
  2125. png_set_sRGB(png_ptr, info_ptr, srgb_intent);
  2126. srgb_intent - the rendering intent
  2127. (PNG_INFO_sRGB) The presence of
  2128. the sRGB chunk means that the pixel
  2129. data is in the sRGB color space.
  2130. This chunk also implies specific
  2131. values of gAMA and cHRM. Rendering
  2132. intent is the CSS-1 property that
  2133. has been defined by the International
  2134. Color Consortium
  2135. (http://www.color.org).
  2136. It can be one of
  2137. PNG_sRGB_INTENT_SATURATION,
  2138. PNG_sRGB_INTENT_PERCEPTUAL,
  2139. PNG_sRGB_INTENT_ABSOLUTE, or
  2140. PNG_sRGB_INTENT_RELATIVE.
  2141. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
  2142. srgb_intent);
  2143. srgb_intent - the rendering intent
  2144. (PNG_INFO_sRGB) The presence of the
  2145. sRGB chunk means that the pixel
  2146. data is in the sRGB color space.
  2147. This function also causes gAMA and
  2148. cHRM chunks with the specific values
  2149. that are consistent with sRGB to be
  2150. written.
  2151. png_set_iCCP(png_ptr, info_ptr, name, compression_type,
  2152. profile, proflen);
  2153. name - The profile name.
  2154. compression_type - The compression type; always
  2155. PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
  2156. You may give NULL to this argument to
  2157. ignore it.
  2158. profile - International Color Consortium color
  2159. profile data. May contain NULs.
  2160. proflen - length of profile data in bytes.
  2161. png_set_sBIT(png_ptr, info_ptr, sig_bit);
  2162. sig_bit - the number of significant bits for
  2163. (PNG_INFO_sBIT) each of the gray, red,
  2164. green, and blue channels, whichever are
  2165. appropriate for the given color type
  2166. (png_color_16)
  2167. png_set_tRNS(png_ptr, info_ptr, trans_alpha,
  2168. num_trans, trans_color);
  2169. trans_alpha - array of alpha (transparency)
  2170. entries for palette (PNG_INFO_tRNS)
  2171. num_trans - number of transparent entries
  2172. (PNG_INFO_tRNS)
  2173. trans_color - graylevel or color sample values
  2174. (in order red, green, blue) of the
  2175. single transparent color for
  2176. non-paletted images (PNG_INFO_tRNS)
  2177. png_set_hIST(png_ptr, info_ptr, hist);
  2178. hist - histogram of palette (array of
  2179. png_uint_16) (PNG_INFO_hIST)
  2180. png_set_tIME(png_ptr, info_ptr, mod_time);
  2181. mod_time - time image was last modified
  2182. (PNG_VALID_tIME)
  2183. png_set_bKGD(png_ptr, info_ptr, background);
  2184. background - background color (of type
  2185. png_color_16p) (PNG_VALID_bKGD)
  2186. png_set_text(png_ptr, info_ptr, text_ptr, num_text);
  2187. text_ptr - array of png_text holding image
  2188. comments
  2189. text_ptr[i].compression - type of compression used
  2190. on "text" PNG_TEXT_COMPRESSION_NONE
  2191. PNG_TEXT_COMPRESSION_zTXt
  2192. PNG_ITXT_COMPRESSION_NONE
  2193. PNG_ITXT_COMPRESSION_zTXt
  2194. text_ptr[i].key - keyword for comment. Must contain
  2195. 1-79 characters.
  2196. text_ptr[i].text - text comments for current
  2197. keyword. Can be NULL or empty.
  2198. text_ptr[i].text_length - length of text string,
  2199. after decompression, 0 for iTXt
  2200. text_ptr[i].itxt_length - length of itxt string,
  2201. after decompression, 0 for tEXt/zTXt
  2202. text_ptr[i].lang - language of comment (NULL or
  2203. empty for unknown).
  2204. text_ptr[i].translated_keyword - keyword in UTF-8 (NULL
  2205. or empty for unknown).
  2206. Note that the itxt_length, lang, and lang_key
  2207. members of the text_ptr structure only exist when the
  2208. library is built with iTXt chunk support. Prior to
  2209. libpng-1.4.0 the library was built by default without
  2210. iTXt support. Also note that when iTXt is supported,
  2211. they contain NULL pointers when the "compression"
  2212. field contains PNG_TEXT_COMPRESSION_NONE or
  2213. PNG_TEXT_COMPRESSION_zTXt.
  2214. num_text - number of comments
  2215. png_set_sPLT(png_ptr, info_ptr, &palette_ptr,
  2216. num_spalettes);
  2217. palette_ptr - array of png_sPLT_struct structures
  2218. to be added to the list of palettes
  2219. in the info structure.
  2220. num_spalettes - number of palette structures to be
  2221. added.
  2222. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
  2223. unit_type);
  2224. offset_x - positive offset from the left
  2225. edge of the screen
  2226. offset_y - positive offset from the top
  2227. edge of the screen
  2228. unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
  2229. png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
  2230. unit_type);
  2231. res_x - pixels/unit physical resolution
  2232. in x direction
  2233. res_y - pixels/unit physical resolution
  2234. in y direction
  2235. unit_type - PNG_RESOLUTION_UNKNOWN,
  2236. PNG_RESOLUTION_METER
  2237. png_set_sCAL(png_ptr, info_ptr, unit, width, height)
  2238. unit - physical scale units (an integer)
  2239. width - width of a pixel in physical scale units
  2240. height - height of a pixel in physical scale units
  2241. (width and height are doubles)
  2242. png_set_sCAL_s(png_ptr, info_ptr, unit, width, height)
  2243. unit - physical scale units (an integer)
  2244. width - width of a pixel in physical scale units
  2245. expressed as a string
  2246. height - height of a pixel in physical scale units
  2247. (width and height are strings like "2.54")
  2248. png_set_unknown_chunks(png_ptr, info_ptr, &unknowns,
  2249. num_unknowns)
  2250. unknowns - array of png_unknown_chunk
  2251. structures holding unknown chunks
  2252. unknowns[i].name - name of unknown chunk
  2253. unknowns[i].data - data of unknown chunk
  2254. unknowns[i].size - size of unknown chunk's data
  2255. unknowns[i].location - position to write chunk in file
  2256. 0: do not write chunk
  2257. PNG_HAVE_IHDR: before PLTE
  2258. PNG_HAVE_PLTE: before IDAT
  2259. PNG_AFTER_IDAT: after IDAT
  2260. The "location" member is set automatically according to
  2261. what part of the output file has already been written.
  2262. You can change its value after calling png_set_unknown_chunks()
  2263. as demonstrated in pngtest.c. Within each of the "locations",
  2264. the chunks are sequenced according to their position in the
  2265. structure (that is, the value of "i", which is the order in which
  2266. the chunk was either read from the input file or defined with
  2267. png_set_unknown_chunks).
  2268. A quick word about text and num_text. text is an array of png_text
  2269. structures. num_text is the number of valid structures in the array.
  2270. Each png_text structure holds a language code, a keyword, a text value,
  2271. and a compression type.
  2272. The compression types have the same valid numbers as the compression
  2273. types of the image data. Currently, the only valid number is zero.
  2274. However, you can store text either compressed or uncompressed, unlike
  2275. images, which always have to be compressed. So if you don't want the
  2276. text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
  2277. Because tEXt and zTXt chunks don't have a language field, if you
  2278. specify PNG_TEXT_COMPRESSION_NONE or PNG_TEXT_COMPRESSION_zTXt
  2279. any language code or translated keyword will not be written out.
  2280. Until text gets around a few hundred bytes, it is not worth compressing it.
  2281. After the text has been written out to the file, the compression type
  2282. is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
  2283. so that it isn't written out again at the end (in case you are calling
  2284. png_write_end() with the same struct).
  2285. The keywords that are given in the PNG Specification are:
  2286. Title Short (one line) title or
  2287. caption for image
  2288. Author Name of image's creator
  2289. Description Description of image (possibly long)
  2290. Copyright Copyright notice
  2291. Creation Time Time of original image creation
  2292. (usually RFC 1123 format, see below)
  2293. Software Software used to create the image
  2294. Disclaimer Legal disclaimer
  2295. Warning Warning of nature of content
  2296. Source Device used to create the image
  2297. Comment Miscellaneous comment; conversion
  2298. from other image format
  2299. The keyword-text pairs work like this. Keywords should be short
  2300. simple descriptions of what the comment is about. Some typical
  2301. keywords are found in the PNG specification, as is some recommendations
  2302. on keywords. You can repeat keywords in a file. You can even write
  2303. some text before the image and some after. For example, you may want
  2304. to put a description of the image before the image, but leave the
  2305. disclaimer until after, so viewers working over modem connections
  2306. don't have to wait for the disclaimer to go over the modem before
  2307. they start seeing the image. Finally, keywords should be full
  2308. words, not abbreviations. Keywords and text are in the ISO 8859-1
  2309. (Latin-1) character set (a superset of regular ASCII) and can not
  2310. contain NUL characters, and should not contain control or other
  2311. unprintable characters. To make the comments widely readable, stick
  2312. with basic ASCII, and avoid machine specific character set extensions
  2313. like the IBM-PC character set. The keyword must be present, but
  2314. you can leave off the text string on non-compressed pairs.
  2315. Compressed pairs must have a text string, as only the text string
  2316. is compressed anyway, so the compression would be meaningless.
  2317. PNG supports modification time via the png_time structure. Two
  2318. conversion routines are provided, png_convert_from_time_t() for
  2319. time_t and png_convert_from_struct_tm() for struct tm. The
  2320. time_t routine uses gmtime(). You don't have to use either of
  2321. these, but if you wish to fill in the png_time structure directly,
  2322. you should provide the time in universal time (GMT) if possible
  2323. instead of your local time. Note that the year number is the full
  2324. year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and
  2325. that months start with 1.
  2326. If you want to store the time of the original image creation, you should
  2327. use a plain tEXt chunk with the "Creation Time" keyword. This is
  2328. necessary because the "creation time" of a PNG image is somewhat vague,
  2329. depending on whether you mean the PNG file, the time the image was
  2330. created in a non-PNG format, a still photo from which the image was
  2331. scanned, or possibly the subject matter itself. In order to facilitate
  2332. machine-readable dates, it is recommended that the "Creation Time"
  2333. tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"),
  2334. although this isn't a requirement. Unlike the tIME chunk, the
  2335. "Creation Time" tEXt chunk is not expected to be automatically changed
  2336. by the software. To facilitate the use of RFC 1123 dates, a function
  2337. png_convert_to_rfc1123(png_timep) is provided to convert from PNG
  2338. time to an RFC 1123 format string.
  2339. Writing unknown chunks
  2340. You can use the png_set_unknown_chunks function to queue up chunks
  2341. for writing. You give it a chunk name, raw data, and a size; that's
  2342. all there is to it. The chunks will be written by the next following
  2343. png_write_info_before_PLTE, png_write_info, or png_write_end function.
  2344. Any chunks previously read into the info structure's unknown-chunk
  2345. list will also be written out in a sequence that satisfies the PNG
  2346. specification's ordering rules.
  2347. The high-level write interface
  2348. At this point there are two ways to proceed; through the high-level
  2349. write interface, or through a sequence of low-level write operations.
  2350. You can use the high-level interface if your image data is present
  2351. in the info structure. All defined output
  2352. transformations are permitted, enabled by the following masks.
  2353. PNG_TRANSFORM_IDENTITY No transformation
  2354. PNG_TRANSFORM_PACKING Pack 1, 2 and 4-bit samples
  2355. PNG_TRANSFORM_PACKSWAP Change order of packed
  2356. pixels to LSB first
  2357. PNG_TRANSFORM_INVERT_MONO Invert monochrome images
  2358. PNG_TRANSFORM_SHIFT Normalize pixels to the
  2359. sBIT depth
  2360. PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
  2361. to BGRA
  2362. PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
  2363. to AG
  2364. PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
  2365. to transparency
  2366. PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
  2367. PNG_TRANSFORM_STRIP_FILLER Strip out filler
  2368. bytes (deprecated).
  2369. PNG_TRANSFORM_STRIP_FILLER_BEFORE Strip out leading
  2370. filler bytes
  2371. PNG_TRANSFORM_STRIP_FILLER_AFTER Strip out trailing
  2372. filler bytes
  2373. If you have valid image data in the info structure (you can use
  2374. png_set_rows() to put image data in the info structure), simply do this:
  2375. png_write_png(png_ptr, info_ptr, png_transforms, NULL)
  2376. where png_transforms is an integer containing the bitwise OR of some set of
  2377. transformation flags. This call is equivalent to png_write_info(),
  2378. followed the set of transformations indicated by the transform mask,
  2379. then png_write_image(), and finally png_write_end().
  2380. (The final parameter of this call is not yet used. Someday it might point
  2381. to transformation parameters required by some future output transform.)
  2382. You must use png_transforms and not call any png_set_transform() functions
  2383. when you use png_write_png().
  2384. The low-level write interface
  2385. If you are going the low-level route instead, you are now ready to
  2386. write all the file information up to the actual image data. You do
  2387. this with a call to png_write_info().
  2388. png_write_info(png_ptr, info_ptr);
  2389. Note that there is one transformation you may need to do before
  2390. png_write_info(). In PNG files, the alpha channel in an image is the
  2391. level of opacity. If your data is supplied as a level of transparency,
  2392. you can invert the alpha channel before you write it, so that 0 is
  2393. fully transparent and 255 (in 8-bit or paletted images) or 65535
  2394. (in 16-bit images) is fully opaque, with
  2395. png_set_invert_alpha(png_ptr);
  2396. This must appear before png_write_info() instead of later with the
  2397. other transformations because in the case of paletted images the tRNS
  2398. chunk data has to be inverted before the tRNS chunk is written. If
  2399. your image is not a paletted image, the tRNS data (which in such cases
  2400. represents a single color to be rendered as transparent) won't need to
  2401. be changed, and you can safely do this transformation after your
  2402. png_write_info() call.
  2403. If you need to write a private chunk that you want to appear before
  2404. the PLTE chunk when PLTE is present, you can write the PNG info in
  2405. two steps, and insert code to write your own chunk between them:
  2406. png_write_info_before_PLTE(png_ptr, info_ptr);
  2407. png_set_unknown_chunks(png_ptr, info_ptr, ...);
  2408. png_write_info(png_ptr, info_ptr);
  2409. After you've written the file information, you can set up the library
  2410. to handle any special transformations of the image data. The various
  2411. ways to transform the data will be described in the order that they
  2412. should occur. This is important, as some of these change the color
  2413. type and/or bit depth of the data, and some others only work on
  2414. certain color types and bit depths. Even though each transformation
  2415. checks to see if it has data that it can do something with, you should
  2416. make sure to only enable a transformation if it will be valid for the
  2417. data. For example, don't swap red and blue on grayscale data.
  2418. PNG files store RGB pixels packed into 3 or 6 bytes. This code tells
  2419. the library to strip input data that has 4 or 8 bytes per pixel down
  2420. to 3 or 6 bytes (or strip 2 or 4-byte grayscale+filler data to 1 or 2
  2421. bytes per pixel).
  2422. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  2423. where the 0 is unused, and the location is either PNG_FILLER_BEFORE or
  2424. PNG_FILLER_AFTER, depending upon whether the filler byte in the pixel
  2425. is stored XRGB or RGBX.
  2426. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  2427. they can, resulting in, for example, 8 pixels per byte for 1 bit files.
  2428. If the data is supplied at 1 pixel per byte, use this code, which will
  2429. correctly pack the pixels into a single byte:
  2430. png_set_packing(png_ptr);
  2431. PNG files reduce possible bit depths to 1, 2, 4, 8, and 16. If your
  2432. data is of another bit depth, you can write an sBIT chunk into the
  2433. file so that decoders can recover the original data if desired.
  2434. /* Set the true bit depth of the image data */
  2435. if (color_type & PNG_COLOR_MASK_COLOR)
  2436. {
  2437. sig_bit.red = true_bit_depth;
  2438. sig_bit.green = true_bit_depth;
  2439. sig_bit.blue = true_bit_depth;
  2440. }
  2441. else
  2442. {
  2443. sig_bit.gray = true_bit_depth;
  2444. }
  2445. if (color_type & PNG_COLOR_MASK_ALPHA)
  2446. {
  2447. sig_bit.alpha = true_bit_depth;
  2448. }
  2449. png_set_sBIT(png_ptr, info_ptr, &sig_bit);
  2450. If the data is stored in the row buffer in a bit depth other than
  2451. one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG),
  2452. this will scale the values to appear to be the correct bit depth as
  2453. is required by PNG.
  2454. png_set_shift(png_ptr, &sig_bit);
  2455. PNG files store 16-bit pixels in network byte order (big-endian,
  2456. ie. most significant bits first). This code would be used if they are
  2457. supplied the other way (little-endian, i.e. least significant bits
  2458. first, the way PCs store them):
  2459. if (bit_depth > 8)
  2460. png_set_swap(png_ptr);
  2461. If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
  2462. need to change the order the pixels are packed into bytes, you can use:
  2463. if (bit_depth < 8)
  2464. png_set_packswap(png_ptr);
  2465. PNG files store 3 color pixels in red, green, blue order. This code
  2466. would be used if they are supplied as blue, green, red:
  2467. png_set_bgr(png_ptr);
  2468. PNG files describe monochrome as black being zero and white being
  2469. one. This code would be used if the pixels are supplied with this reversed
  2470. (black being one and white being zero):
  2471. png_set_invert_mono(png_ptr);
  2472. Finally, you can write your own transformation function if none of
  2473. the existing ones meets your needs. This is done by setting a callback
  2474. with
  2475. png_set_write_user_transform_fn(png_ptr,
  2476. write_transform_fn);
  2477. You must supply the function
  2478. void write_transform_fn(png_structp png_ptr, png_row_infop
  2479. row_info, png_bytep data)
  2480. See pngtest.c for a working example. Your function will be called
  2481. before any of the other transformations are processed. If supported
  2482. libpng also supplies an information routine that may be called from
  2483. your callback:
  2484. png_get_current_row_number(png_ptr);
  2485. png_get_current_pass_number(png_ptr);
  2486. This returns the current row passed to the transform. With interlaced
  2487. images the value returned is the row in the input sub-image image. Use
  2488. PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
  2489. find the output pixel (x,y) given an interlaced sub-image pixel (row,col,pass).
  2490. The discussion of interlace handling above contains more information on how to
  2491. use these values.
  2492. You can also set up a pointer to a user structure for use by your
  2493. callback function.
  2494. png_set_user_transform_info(png_ptr, user_ptr, 0, 0);
  2495. The user_channels and user_depth parameters of this function are ignored
  2496. when writing; you can set them to zero as shown.
  2497. You can retrieve the pointer via the function png_get_user_transform_ptr().
  2498. For example:
  2499. voidp write_user_transform_ptr =
  2500. png_get_user_transform_ptr(png_ptr);
  2501. It is possible to have libpng flush any pending output, either manually,
  2502. or automatically after a certain number of lines have been written. To
  2503. flush the output stream a single time call:
  2504. png_write_flush(png_ptr);
  2505. and to have libpng flush the output stream periodically after a certain
  2506. number of scanlines have been written, call:
  2507. png_set_flush(png_ptr, nrows);
  2508. Note that the distance between rows is from the last time png_write_flush()
  2509. was called, or the first row of the image if it has never been called.
  2510. So if you write 50 lines, and then png_set_flush 25, it will flush the
  2511. output on the next scanline, and every 25 lines thereafter, unless
  2512. png_write_flush() is called before 25 more lines have been written.
  2513. If nrows is too small (less than about 10 lines for a 640 pixel wide
  2514. RGB image) the image compression may decrease noticeably (although this
  2515. may be acceptable for real-time applications). Infrequent flushing will
  2516. only degrade the compression performance by a few percent over images
  2517. that do not use flushing.
  2518. Writing the image data
  2519. That's it for the transformations. Now you can write the image data.
  2520. The simplest way to do this is in one function call. If you have the
  2521. whole image in memory, you can just call png_write_image() and libpng
  2522. will write the image. You will need to pass in an array of pointers to
  2523. each row. This function automatically handles interlacing, so you don't
  2524. need to call png_set_interlace_handling() or call this function multiple
  2525. times, or any of that other stuff necessary with png_write_rows().
  2526. png_write_image(png_ptr, row_pointers);
  2527. where row_pointers is:
  2528. png_byte *row_pointers[height];
  2529. You can point to void or char or whatever you use for pixels.
  2530. If you don't want to write the whole image at once, you can
  2531. use png_write_rows() instead. If the file is not interlaced,
  2532. this is simple:
  2533. png_write_rows(png_ptr, row_pointers,
  2534. number_of_rows);
  2535. row_pointers is the same as in the png_write_image() call.
  2536. If you are just writing one row at a time, you can do this with
  2537. a single row_pointer instead of an array of row_pointers:
  2538. png_bytep row_pointer = row;
  2539. png_write_row(png_ptr, row_pointer);
  2540. When the file is interlaced, things can get a good deal more complicated.
  2541. The only currently (as of the PNG Specification version 1.2, dated July
  2542. 1999) defined interlacing scheme for PNG files is the "Adam7" interlace
  2543. scheme, that breaks down an image into seven smaller images of varying
  2544. size. libpng will build these images for you, or you can do them
  2545. yourself. If you want to build them yourself, see the PNG specification
  2546. for details of which pixels to write when.
  2547. If you don't want libpng to handle the interlacing details, just
  2548. use png_set_interlace_handling() and call png_write_rows() the
  2549. correct number of times to write all the sub-images
  2550. (png_set_interlace_handling() returns the number of sub-images.)
  2551. If you want libpng to build the sub-images, call this before you start
  2552. writing any rows:
  2553. number_of_passes = png_set_interlace_handling(png_ptr);
  2554. This will return the number of passes needed. Currently, this is seven,
  2555. but may change if another interlace type is added.
  2556. Then write the complete image number_of_passes times.
  2557. png_write_rows(png_ptr, row_pointers, number_of_rows);
  2558. Think carefully before you write an interlaced image. Typically code that
  2559. reads such images reads all the image data into memory, uncompressed, before
  2560. doing any processing. Only code that can display an image on the fly can
  2561. take advantage of the interlacing and even then the image has to be exactly
  2562. the correct size for the output device, because scaling an image requires
  2563. adjacent pixels and these are not available until all the passes have been
  2564. read.
  2565. If you do write an interlaced image you will hardly ever need to handle
  2566. the interlacing yourself. Call png_set_interlace_handling() and use the
  2567. approach described above.
  2568. The only time it is conceivable that you will really need to write an
  2569. interlaced image pass-by-pass is when you have read one pass by pass and
  2570. made some pixel-by-pixel transformation to it, as described in the read
  2571. code above. In this case use the PNG_PASS_ROWS and PNG_PASS_COLS macros
  2572. to determine the size of each sub-image in turn and simply write the rows
  2573. you obtained from the read code.
  2574. Finishing a sequential write
  2575. After you are finished writing the image, you should finish writing
  2576. the file. If you are interested in writing comments or time, you should
  2577. pass an appropriately filled png_info pointer. If you are not interested,
  2578. you can pass NULL.
  2579. png_write_end(png_ptr, info_ptr);
  2580. When you are done, you can free all memory used by libpng like this:
  2581. png_destroy_write_struct(&png_ptr, &info_ptr);
  2582. It is also possible to individually free the info_ptr members that
  2583. point to libpng-allocated storage with the following function:
  2584. png_free_data(png_ptr, info_ptr, mask, seq)
  2585. mask - identifies data to be freed, a mask
  2586. containing the bitwise OR of one or
  2587. more of
  2588. PNG_FREE_PLTE, PNG_FREE_TRNS,
  2589. PNG_FREE_HIST, PNG_FREE_ICCP,
  2590. PNG_FREE_PCAL, PNG_FREE_ROWS,
  2591. PNG_FREE_SCAL, PNG_FREE_SPLT,
  2592. PNG_FREE_TEXT, PNG_FREE_UNKN,
  2593. or simply PNG_FREE_ALL
  2594. seq - sequence number of item to be freed
  2595. (-1 for all items)
  2596. This function may be safely called when the relevant storage has
  2597. already been freed, or has not yet been allocated, or was allocated
  2598. by the user and not by libpng, and will in those cases do nothing.
  2599. The "seq" parameter is ignored if only one item of the selected data
  2600. type, such as PLTE, is allowed. If "seq" is not -1, and multiple items
  2601. are allowed for the data type identified in the mask, such as text or
  2602. sPLT, only the n'th item in the structure is freed, where n is "seq".
  2603. If you allocated data such as a palette that you passed in to libpng
  2604. with png_set_*, you must not free it until just before the call to
  2605. png_destroy_write_struct().
  2606. The default behavior is only to free data that was allocated internally
  2607. by libpng. This can be changed, so that libpng will not free the data,
  2608. or so that it will free data that was allocated by the user with png_malloc()
  2609. or png_zalloc() and passed in via a png_set_*() function, with
  2610. png_data_freer(png_ptr, info_ptr, freer, mask)
  2611. freer - one of
  2612. PNG_DESTROY_WILL_FREE_DATA
  2613. PNG_SET_WILL_FREE_DATA
  2614. PNG_USER_WILL_FREE_DATA
  2615. mask - which data elements are affected
  2616. same choices as in png_free_data()
  2617. For example, to transfer responsibility for some data from a read structure
  2618. to a write structure, you could use
  2619. png_data_freer(read_ptr, read_info_ptr,
  2620. PNG_USER_WILL_FREE_DATA,
  2621. PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
  2622. png_data_freer(write_ptr, write_info_ptr,
  2623. PNG_DESTROY_WILL_FREE_DATA,
  2624. PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
  2625. thereby briefly reassigning responsibility for freeing to the user but
  2626. immediately afterwards reassigning it once more to the write_destroy
  2627. function. Having done this, it would then be safe to destroy the read
  2628. structure and continue to use the PLTE, tRNS, and hIST data in the write
  2629. structure.
  2630. This function only affects data that has already been allocated.
  2631. You can call this function before calling after the png_set_*() functions
  2632. to control whether the user or png_destroy_*() is supposed to free the data.
  2633. When the user assumes responsibility for libpng-allocated data, the
  2634. application must use
  2635. png_free() to free it, and when the user transfers responsibility to libpng
  2636. for data that the user has allocated, the user must have used png_malloc()
  2637. or png_zalloc() to allocate it.
  2638. If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
  2639. separately, do not transfer responsibility for freeing text_ptr to libpng,
  2640. because when libpng fills a png_text structure it combines these members with
  2641. the key member, and png_free_data() will free only text_ptr.key. Similarly,
  2642. if you transfer responsibility for free'ing text_ptr from libpng to your
  2643. application, your application must not separately free those members.
  2644. For a more compact example of writing a PNG image, see the file example.c.
  2645. V. Modifying/Customizing libpng:
  2646. There are two issues here. The first is changing how libpng does
  2647. standard things like memory allocation, input/output, and error handling.
  2648. The second deals with more complicated things like adding new chunks,
  2649. adding new transformations, and generally changing how libpng works.
  2650. Both of those are compile-time issues; that is, they are generally
  2651. determined at the time the code is written, and there is rarely a need
  2652. to provide the user with a means of changing them.
  2653. Memory allocation, input/output, and error handling
  2654. All of the memory allocation, input/output, and error handling in libpng
  2655. goes through callbacks that are user-settable. The default routines are
  2656. in pngmem.c, pngrio.c, pngwio.c, and pngerror.c, respectively. To change
  2657. these functions, call the appropriate png_set_*_fn() function.
  2658. Memory allocation is done through the functions png_malloc(), png_calloc(),
  2659. and png_free(). These currently just call the standard C functions.
  2660. png_calloc() calls png_malloc() and then clears the newly
  2661. allocated memory to zero. There is limited support for certain systems
  2662. with segmented memory architectures and the types of pointers declared by
  2663. png.h match this; you will have to use appropriate pointers in your
  2664. application. Since it is
  2665. unlikely that the method of handling memory allocation on a platform
  2666. will change between applications, these functions must be modified in
  2667. the library at compile time. If you prefer to use a different method
  2668. of allocating and freeing data, you can use png_create_read_struct_2() or
  2669. png_create_write_struct_2() to register your own functions as described
  2670. above. These functions also provide a void pointer that can be retrieved
  2671. via
  2672. mem_ptr=png_get_mem_ptr(png_ptr);
  2673. Your replacement memory functions must have prototypes as follows:
  2674. png_voidp malloc_fn(png_structp png_ptr,
  2675. png_alloc_size_t size);
  2676. void free_fn(png_structp png_ptr, png_voidp ptr);
  2677. Your malloc_fn() must return NULL in case of failure. The png_malloc()
  2678. function will normally call png_error() if it receives a NULL from the
  2679. system memory allocator or from your replacement malloc_fn().
  2680. Your free_fn() will never be called with a NULL ptr, since libpng's
  2681. png_free() checks for NULL before calling free_fn().
  2682. Input/Output in libpng is done through png_read() and png_write(),
  2683. which currently just call fread() and fwrite(). The FILE * is stored in
  2684. png_struct and is initialized via png_init_io(). If you wish to change
  2685. the method of I/O, the library supplies callbacks that you can set
  2686. through the function png_set_read_fn() and png_set_write_fn() at run
  2687. time, instead of calling the png_init_io() function. These functions
  2688. also provide a void pointer that can be retrieved via the function
  2689. png_get_io_ptr(). For example:
  2690. png_set_read_fn(png_structp read_ptr,
  2691. voidp read_io_ptr, png_rw_ptr read_data_fn)
  2692. png_set_write_fn(png_structp write_ptr,
  2693. voidp write_io_ptr, png_rw_ptr write_data_fn,
  2694. png_flush_ptr output_flush_fn);
  2695. voidp read_io_ptr = png_get_io_ptr(read_ptr);
  2696. voidp write_io_ptr = png_get_io_ptr(write_ptr);
  2697. The replacement I/O functions must have prototypes as follows:
  2698. void user_read_data(png_structp png_ptr,
  2699. png_bytep data, png_size_t length);
  2700. void user_write_data(png_structp png_ptr,
  2701. png_bytep data, png_size_t length);
  2702. void user_flush_data(png_structp png_ptr);
  2703. The user_read_data() function is responsible for detecting and
  2704. handling end-of-data errors.
  2705. Supplying NULL for the read, write, or flush functions sets them back
  2706. to using the default C stream functions, which expect the io_ptr to
  2707. point to a standard *FILE structure. It is probably a mistake
  2708. to use NULL for one of write_data_fn and output_flush_fn but not both
  2709. of them, unless you have built libpng with PNG_NO_WRITE_FLUSH defined.
  2710. It is an error to read from a write stream, and vice versa.
  2711. Error handling in libpng is done through png_error() and png_warning().
  2712. Errors handled through png_error() are fatal, meaning that png_error()
  2713. should never return to its caller. Currently, this is handled via
  2714. setjmp() and longjmp() (unless you have compiled libpng with
  2715. PNG_NO_SETJMP, in which case it is handled via PNG_ABORT()),
  2716. but you could change this to do things like exit() if you should wish,
  2717. as long as your function does not return.
  2718. On non-fatal errors, png_warning() is called
  2719. to print a warning message, and then control returns to the calling code.
  2720. By default png_error() and png_warning() print a message on stderr via
  2721. fprintf() unless the library is compiled with PNG_NO_CONSOLE_IO defined
  2722. (because you don't want the messages) or PNG_NO_STDIO defined (because
  2723. fprintf() isn't available). If you wish to change the behavior of the error
  2724. functions, you will need to set up your own message callbacks. These
  2725. functions are normally supplied at the time that the png_struct is created.
  2726. It is also possible to redirect errors and warnings to your own replacement
  2727. functions after png_create_*_struct() has been called by calling:
  2728. png_set_error_fn(png_structp png_ptr,
  2729. png_voidp error_ptr, png_error_ptr error_fn,
  2730. png_error_ptr warning_fn);
  2731. png_voidp error_ptr = png_get_error_ptr(png_ptr);
  2732. If NULL is supplied for either error_fn or warning_fn, then the libpng
  2733. default function will be used, calling fprintf() and/or longjmp() if a
  2734. problem is encountered. The replacement error functions should have
  2735. parameters as follows:
  2736. void user_error_fn(png_structp png_ptr,
  2737. png_const_charp error_msg);
  2738. void user_warning_fn(png_structp png_ptr,
  2739. png_const_charp warning_msg);
  2740. The motivation behind using setjmp() and longjmp() is the C++ throw and
  2741. catch exception handling methods. This makes the code much easier to write,
  2742. as there is no need to check every return code of every function call.
  2743. However, there are some uncertainties about the status of local variables
  2744. after a longjmp, so the user may want to be careful about doing anything
  2745. after setjmp returns non-zero besides returning itself. Consult your
  2746. compiler documentation for more details. For an alternative approach, you
  2747. may wish to use the "cexcept" facility (see http://cexcept.sourceforge.net),
  2748. which is illustrated in pngvalid.c and in contrib/visupng.
  2749. Custom chunks
  2750. If you need to read or write custom chunks, you may need to get deeper
  2751. into the libpng code. The library now has mechanisms for storing
  2752. and writing chunks of unknown type; you can even declare callbacks
  2753. for custom chunks. However, this may not be good enough if the
  2754. library code itself needs to know about interactions between your
  2755. chunk and existing `intrinsic' chunks.
  2756. If you need to write a new intrinsic chunk, first read the PNG
  2757. specification. Acquire a first level of understanding of how it works.
  2758. Pay particular attention to the sections that describe chunk names,
  2759. and look at how other chunks were designed, so you can do things
  2760. similarly. Second, check out the sections of libpng that read and
  2761. write chunks. Try to find a chunk that is similar to yours and use
  2762. it as a template. More details can be found in the comments inside
  2763. the code. It is best to handle private or unknown chunks in a generic method,
  2764. via callback functions, instead of by modifying libpng functions. This
  2765. is illustrated in pngtest.c, which uses a callback function to handle a
  2766. private "vpAg" chunk and the new "sTER" chunk, which are both unknown to
  2767. libpng.
  2768. If you wish to write your own transformation for the data, look through
  2769. the part of the code that does the transformations, and check out some of
  2770. the simpler ones to get an idea of how they work. Try to find a similar
  2771. transformation to the one you want to add and copy off of it. More details
  2772. can be found in the comments inside the code itself.
  2773. Configuring for 16-bit platforms
  2774. You will want to look into zconf.h to tell zlib (and thus libpng) that
  2775. it cannot allocate more then 64K at a time. Even if you can, the memory
  2776. won't be accessible. So limit zlib and libpng to 64K by defining MAXSEG_64K.
  2777. Configuring for DOS
  2778. For DOS users who only have access to the lower 640K, you will
  2779. have to limit zlib's memory usage via a png_set_compression_mem_level()
  2780. call. See zlib.h or zconf.h in the zlib library for more information.
  2781. Configuring for Medium Model
  2782. Libpng's support for medium model has been tested on most of the popular
  2783. compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
  2784. defined, and FAR gets defined to far in pngconf.h, and you should be
  2785. all set. Everything in the library (except for zlib's structure) is
  2786. expecting far data. You must use the typedefs with the p or pp on
  2787. the end for pointers (or at least look at them and be careful). Make
  2788. note that the rows of data are defined as png_bytepp, which is
  2789. an "unsigned char far * far *".
  2790. Configuring for gui/windowing platforms:
  2791. You will need to write new error and warning functions that use the GUI
  2792. interface, as described previously, and set them to be the error and
  2793. warning functions at the time that png_create_*_struct() is called,
  2794. in order to have them available during the structure initialization.
  2795. They can be changed later via png_set_error_fn(). On some compilers,
  2796. you may also have to change the memory allocators (png_malloc, etc.).
  2797. Configuring for compiler xxx:
  2798. All includes for libpng are in pngconf.h. If you need to add, change
  2799. or delete an include, this is the place to do it.
  2800. The includes that are not needed outside libpng are placed in pngpriv.h,
  2801. which is only used by the routines inside libpng itself.
  2802. The files in libpng proper only include pngpriv.h and png.h, which
  2803. in turn includes pngconf.h and, as of libpng-1.5.0, pnglibconf.h.
  2804. As of libpng-1.5.0, pngpriv.h also includes three other private header
  2805. files, pngstruct.h, pnginfo.h, and pngdebug.h, which contain material
  2806. that previously appeared in the public headers.
  2807. Configuring zlib:
  2808. There are special functions to configure the compression. Perhaps the
  2809. most useful one changes the compression level, which currently uses
  2810. input compression values in the range 0 - 9. The library normally
  2811. uses the default compression level (Z_DEFAULT_COMPRESSION = 6). Tests
  2812. have shown that for a large majority of images, compression values in
  2813. the range 3-6 compress nearly as well as higher levels, and do so much
  2814. faster. For online applications it may be desirable to have maximum speed
  2815. (Z_BEST_SPEED = 1). With versions of zlib after v0.99, you can also
  2816. specify no compression (Z_NO_COMPRESSION = 0), but this would create
  2817. files larger than just storing the raw bitmap. You can specify the
  2818. compression level by calling:
  2819. #include zlib.h
  2820. png_set_compression_level(png_ptr, level);
  2821. Another useful one is to reduce the memory level used by the library.
  2822. The memory level defaults to 8, but it can be lowered if you are
  2823. short on memory (running DOS, for example, where you only have 640K).
  2824. Note that the memory level does have an effect on compression; among
  2825. other things, lower levels will result in sections of incompressible
  2826. data being emitted in smaller stored blocks, with a correspondingly
  2827. larger relative overhead of up to 15% in the worst case.
  2828. #include zlib.h
  2829. png_set_compression_mem_level(png_ptr, level);
  2830. The other functions are for configuring zlib. They are not recommended
  2831. for normal use and may result in writing an invalid PNG file. See
  2832. zlib.h for more information on what these mean.
  2833. #include zlib.h
  2834. png_set_compression_strategy(png_ptr,
  2835. strategy);
  2836. png_set_compression_window_bits(png_ptr,
  2837. window_bits);
  2838. png_set_compression_method(png_ptr, method);
  2839. png_set_compression_buffer_size(png_ptr, size);
  2840. As of libpng version 1.5.4, additional APIs became
  2841. available to set these separately for non-IDAT
  2842. compressed chunks such as zTXt, iTXt, and iCCP:
  2843. #include zlib.h
  2844. #if PNG_LIBPNG_VER <= 10504
  2845. png_set_text_compression_level(png_ptr, level);
  2846. png_set_text_compression_mem_level(png_ptr, level);
  2847. png_set_text_compression_strategy(png_ptr,
  2848. strategy);
  2849. png_set_text_compression_window_bits(png_ptr,
  2850. window_bits);
  2851. png_set_text_compression_method(png_ptr, method);
  2852. #endif
  2853. Controlling row filtering
  2854. If you want to control whether libpng uses filtering or not, which
  2855. filters are used, and how it goes about picking row filters, you
  2856. can call one of these functions. The selection and configuration
  2857. of row filters can have a significant impact on the size and
  2858. encoding speed and a somewhat lesser impact on the decoding speed
  2859. of an image. Filtering is enabled by default for RGB and grayscale
  2860. images (with and without alpha), but not for paletted images nor
  2861. for any images with bit depths less than 8 bits/pixel.
  2862. The 'method' parameter sets the main filtering method, which is
  2863. currently only '0' in the PNG 1.2 specification. The 'filters'
  2864. parameter sets which filter(s), if any, should be used for each
  2865. scanline. Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
  2866. to turn filtering on and off, respectively.
  2867. Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
  2868. PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
  2869. ORed together with '|' to specify one or more filters to use.
  2870. These filters are described in more detail in the PNG specification.
  2871. If you intend to change the filter type during the course of writing
  2872. the image, you should start with flags set for all of the filters
  2873. you intend to use so that libpng can initialize its internal
  2874. structures appropriately for all of the filter types. (Note that this
  2875. means the first row must always be adaptively filtered, because libpng
  2876. currently does not allocate the filter buffers until png_write_row()
  2877. is called for the first time.)
  2878. filters = PNG_FILTER_NONE | PNG_FILTER_SUB
  2879. PNG_FILTER_UP | PNG_FILTER_AVG |
  2880. PNG_FILTER_PAETH | PNG_ALL_FILTERS;
  2881. png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
  2882. filters);
  2883. The second parameter can also be
  2884. PNG_INTRAPIXEL_DIFFERENCING if you are
  2885. writing a PNG to be embedded in a MNG
  2886. datastream. This parameter must be the
  2887. same as the value of filter_method used
  2888. in png_set_IHDR().
  2889. It is also possible to influence how libpng chooses from among the
  2890. available filters. This is done in one or both of two ways - by
  2891. telling it how important it is to keep the same filter for successive
  2892. rows, and by telling it the relative computational costs of the filters.
  2893. double weights[3] = {1.5, 1.3, 1.1},
  2894. costs[PNG_FILTER_VALUE_LAST] =
  2895. {1.0, 1.3, 1.3, 1.5, 1.7};
  2896. png_set_filter_heuristics(png_ptr,
  2897. PNG_FILTER_HEURISTIC_WEIGHTED, 3,
  2898. weights, costs);
  2899. The weights are multiplying factors that indicate to libpng that the
  2900. row filter should be the same for successive rows unless another row filter
  2901. is that many times better than the previous filter. In the above example,
  2902. if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
  2903. "sum of absolute differences" 1.5 x 1.3 times higher than other filters
  2904. and still be chosen, while the NONE filter could have a sum 1.1 times
  2905. higher than other filters and still be chosen. Unspecified weights are
  2906. taken to be 1.0, and the specified weights should probably be declining
  2907. like those above in order to emphasize recent filters over older filters.
  2908. The filter costs specify for each filter type a relative decoding cost
  2909. to be considered when selecting row filters. This means that filters
  2910. with higher costs are less likely to be chosen over filters with lower
  2911. costs, unless their "sum of absolute differences" is that much smaller.
  2912. The costs do not necessarily reflect the exact computational speeds of
  2913. the various filters, since this would unduly influence the final image
  2914. size.
  2915. Note that the numbers above were invented purely for this example and
  2916. are given only to help explain the function usage. Little testing has
  2917. been done to find optimum values for either the costs or the weights.
  2918. Removing unwanted object code
  2919. There are a bunch of #define's in pngconf.h that control what parts of
  2920. libpng are compiled. All the defines end in _SUPPORTED. If you are
  2921. never going to use a capability, you can change the #define to #undef
  2922. before recompiling libpng and save yourself code and data space, or
  2923. you can turn off individual capabilities with defines that begin with
  2924. PNG_NO_.
  2925. In libpng-1.5.0 and later, the #define's are in pnglibconf.h instead.
  2926. You can also turn all of the transforms and ancillary chunk capabilities
  2927. off en masse with compiler directives that define
  2928. PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS,
  2929. or all four,
  2930. along with directives to turn on any of the capabilities that you do
  2931. want. The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable the extra
  2932. transformations but still leave the library fully capable of reading
  2933. and writing PNG files with all known public chunks. Use of the
  2934. PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive produces a library
  2935. that is incapable of reading or writing ancillary chunks. If you are
  2936. not using the progressive reading capability, you can turn that off
  2937. with PNG_NO_PROGRESSIVE_READ (don't confuse this with the INTERLACING
  2938. capability, which you'll still have).
  2939. All the reading and writing specific code are in separate files, so the
  2940. linker should only grab the files it needs. However, if you want to
  2941. make sure, or if you are building a stand alone library, all the
  2942. reading files start with "pngr" and all the writing files start with "pngw".
  2943. The files that don't match either (like png.c, pngtrans.c, etc.)
  2944. are used for both reading and writing, and always need to be included.
  2945. The progressive reader is in pngpread.c
  2946. If you are creating or distributing a dynamically linked library (a .so
  2947. or DLL file), you should not remove or disable any parts of the library,
  2948. as this will cause applications linked with different versions of the
  2949. library to fail if they call functions not available in your library.
  2950. The size of the library itself should not be an issue, because only
  2951. those sections that are actually used will be loaded into memory.
  2952. Requesting debug printout
  2953. The macro definition PNG_DEBUG can be used to request debugging
  2954. printout. Set it to an integer value in the range 0 to 3. Higher
  2955. numbers result in increasing amounts of debugging information. The
  2956. information is printed to the "stderr" file, unless another file
  2957. name is specified in the PNG_DEBUG_FILE macro definition.
  2958. When PNG_DEBUG > 0, the following functions (macros) become available:
  2959. png_debug(level, message)
  2960. png_debug1(level, message, p1)
  2961. png_debug2(level, message, p1, p2)
  2962. in which "level" is compared to PNG_DEBUG to decide whether to print
  2963. the message, "message" is the formatted string to be printed,
  2964. and p1 and p2 are parameters that are to be embedded in the string
  2965. according to printf-style formatting directives. For example,
  2966. png_debug1(2, "foo=%d\n", foo);
  2967. is expanded to
  2968. if (PNG_DEBUG > 2)
  2969. fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
  2970. When PNG_DEBUG is defined but is zero, the macros aren't defined, but you
  2971. can still use PNG_DEBUG to control your own debugging:
  2972. #ifdef PNG_DEBUG
  2973. fprintf(stderr, ...
  2974. #endif
  2975. When PNG_DEBUG = 1, the macros are defined, but only png_debug statements
  2976. having level = 0 will be printed. There aren't any such statements in
  2977. this version of libpng, but if you insert some they will be printed.
  2978. VI. MNG support
  2979. The MNG specification (available at http://www.libpng.org/pub/mng) allows
  2980. certain extensions to PNG for PNG images that are embedded in MNG datastreams.
  2981. Libpng can support some of these extensions. To enable them, use the
  2982. png_permit_mng_features() function:
  2983. feature_set = png_permit_mng_features(png_ptr, mask)
  2984. mask is a png_uint_32 containing the bitwise OR of the
  2985. features you want to enable. These include
  2986. PNG_FLAG_MNG_EMPTY_PLTE
  2987. PNG_FLAG_MNG_FILTER_64
  2988. PNG_ALL_MNG_FEATURES
  2989. feature_set is a png_uint_32 that is the bitwise AND of
  2990. your mask with the set of MNG features that is
  2991. supported by the version of libpng that you are using.
  2992. It is an error to use this function when reading or writing a standalone
  2993. PNG file with the PNG 8-byte signature. The PNG datastream must be wrapped
  2994. in a MNG datastream. As a minimum, it must have the MNG 8-byte signature
  2995. and the MHDR and MEND chunks. Libpng does not provide support for these
  2996. or any other MNG chunks; your application must provide its own support for
  2997. them. You may wish to consider using libmng (available at
  2998. http://www.libmng.com) instead.
  2999. VII. Changes to Libpng from version 0.88
  3000. It should be noted that versions of libpng later than 0.96 are not
  3001. distributed by the original libpng author, Guy Schalnat, nor by
  3002. Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
  3003. distributed versions 0.89 through 0.96, but rather by another member
  3004. of the original PNG Group, Glenn Randers-Pehrson. Guy and Andreas are
  3005. still alive and well, but they have moved on to other things.
  3006. The old libpng functions png_read_init(), png_write_init(),
  3007. png_info_init(), png_read_destroy(), and png_write_destroy() have been
  3008. moved to PNG_INTERNAL in version 0.95 to discourage their use. These
  3009. functions will be removed from libpng version 1.4.0.
  3010. The preferred method of creating and initializing the libpng structures is
  3011. via the png_create_read_struct(), png_create_write_struct(), and
  3012. png_create_info_struct() because they isolate the size of the structures
  3013. from the application, allow version error checking, and also allow the
  3014. use of custom error handling routines during the initialization, which
  3015. the old functions do not. The functions png_read_destroy() and
  3016. png_write_destroy() do not actually free the memory that libpng
  3017. allocated for these structs, but just reset the data structures, so they
  3018. can be used instead of png_destroy_read_struct() and
  3019. png_destroy_write_struct() if you feel there is too much system overhead
  3020. allocating and freeing the png_struct for each image read.
  3021. Setting the error callbacks via png_set_message_fn() before
  3022. png_read_init() as was suggested in libpng-0.88 is no longer supported
  3023. because this caused applications that do not use custom error functions
  3024. to fail if the png_ptr was not initialized to zero. It is still possible
  3025. to set the error callbacks AFTER png_read_init(), or to change them with
  3026. png_set_error_fn(), which is essentially the same function, but with a new
  3027. name to force compilation errors with applications that try to use the old
  3028. method.
  3029. Starting with version 1.0.7, you can find out which version of the library
  3030. you are using at run-time:
  3031. png_uint_32 libpng_vn = png_access_version_number();
  3032. The number libpng_vn is constructed from the major version, minor
  3033. version with leading zero, and release number with leading zero,
  3034. (e.g., libpng_vn for version 1.0.7 is 10007).
  3035. Note that this function does not take a png_ptr, so you can call it
  3036. before you've created one.
  3037. You can also check which version of png.h you used when compiling your
  3038. application:
  3039. png_uint_32 application_vn = PNG_LIBPNG_VER;
  3040. VIII. Changes to Libpng from version 1.0.x to 1.2.x
  3041. Support for user memory management was enabled by default. To
  3042. accomplish this, the functions png_create_read_struct_2(),
  3043. png_create_write_struct_2(), png_set_mem_fn(), png_get_mem_ptr(),
  3044. png_malloc_default(), and png_free_default() were added.
  3045. Support for the iTXt chunk has been enabled by default as of
  3046. version 1.2.41.
  3047. Support for certain MNG features was enabled.
  3048. Support for numbered error messages was added. However, we never got
  3049. around to actually numbering the error messages. The function
  3050. png_set_strip_error_numbers() was added (Note: the prototype for this
  3051. function was inadvertently removed from png.h in PNG_NO_ASSEMBLER_CODE
  3052. builds of libpng-1.2.15. It was restored in libpng-1.2.36).
  3053. The png_malloc_warn() function was added at libpng-1.2.3. This issues
  3054. a png_warning and returns NULL instead of aborting when it fails to
  3055. acquire the requested memory allocation.
  3056. Support for setting user limits on image width and height was enabled
  3057. by default. The functions png_set_user_limits(), png_get_user_width_max(),
  3058. and png_get_user_height_max() were added at libpng-1.2.6.
  3059. The png_set_add_alpha() function was added at libpng-1.2.7.
  3060. The function png_set_expand_gray_1_2_4_to_8() was added at libpng-1.2.9.
  3061. Unlike png_set_gray_1_2_4_to_8(), the new function does not expand the
  3062. tRNS chunk to alpha. The png_set_gray_1_2_4_to_8() function is
  3063. deprecated.
  3064. A number of macro definitions in support of runtime selection of
  3065. assembler code features (especially Intel MMX code support) were
  3066. added at libpng-1.2.0:
  3067. PNG_ASM_FLAG_MMX_SUPPORT_COMPILED
  3068. PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU
  3069. PNG_ASM_FLAG_MMX_READ_COMBINE_ROW
  3070. PNG_ASM_FLAG_MMX_READ_INTERLACE
  3071. PNG_ASM_FLAG_MMX_READ_FILTER_SUB
  3072. PNG_ASM_FLAG_MMX_READ_FILTER_UP
  3073. PNG_ASM_FLAG_MMX_READ_FILTER_AVG
  3074. PNG_ASM_FLAG_MMX_READ_FILTER_PAETH
  3075. PNG_ASM_FLAGS_INITIALIZED
  3076. PNG_MMX_READ_FLAGS
  3077. PNG_MMX_FLAGS
  3078. PNG_MMX_WRITE_FLAGS
  3079. PNG_MMX_FLAGS
  3080. We added the following functions in support of runtime
  3081. selection of assembler code features:
  3082. png_get_mmx_flagmask()
  3083. png_set_mmx_thresholds()
  3084. png_get_asm_flags()
  3085. png_get_mmx_bitdepth_threshold()
  3086. png_get_mmx_rowbytes_threshold()
  3087. png_set_asm_flags()
  3088. We replaced all of these functions with simple stubs in libpng-1.2.20,
  3089. when the Intel assembler code was removed due to a licensing issue.
  3090. These macros are deprecated:
  3091. PNG_READ_TRANSFORMS_NOT_SUPPORTED
  3092. PNG_PROGRESSIVE_READ_NOT_SUPPORTED
  3093. PNG_NO_SEQUENTIAL_READ_SUPPORTED
  3094. PNG_WRITE_TRANSFORMS_NOT_SUPPORTED
  3095. PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED
  3096. PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED
  3097. They have been replaced, respectively, by:
  3098. PNG_NO_READ_TRANSFORMS
  3099. PNG_NO_PROGRESSIVE_READ
  3100. PNG_NO_SEQUENTIAL_READ
  3101. PNG_NO_WRITE_TRANSFORMS
  3102. PNG_NO_READ_ANCILLARY_CHUNKS
  3103. PNG_NO_WRITE_ANCILLARY_CHUNKS
  3104. PNG_MAX_UINT was replaced with PNG_UINT_31_MAX. It has been
  3105. deprecated since libpng-1.0.16 and libpng-1.2.6.
  3106. The function
  3107. png_check_sig(sig, num)
  3108. was replaced with
  3109. !png_sig_cmp(sig, 0, num)
  3110. It has been deprecated since libpng-0.90.
  3111. The function
  3112. png_set_gray_1_2_4_to_8()
  3113. which also expands tRNS to alpha was replaced with
  3114. png_set_expand_gray_1_2_4_to_8()
  3115. which does not. It has been deprecated since libpng-1.0.18 and 1.2.9.
  3116. IX. Changes to Libpng from version 1.0.x/1.2.x to 1.4.x
  3117. Private libpng prototypes and macro definitions were moved from
  3118. png.h and pngconf.h into a new pngpriv.h header file.
  3119. Functions png_set_benign_errors(), png_benign_error(), and
  3120. png_chunk_benign_error() were added.
  3121. Support for setting the maximum amount of memory that the application
  3122. will allocate for reading chunks was added, as a security measure.
  3123. The functions png_set_chunk_cache_max() and png_get_chunk_cache_max()
  3124. were added to the library.
  3125. We implemented support for I/O states by adding png_ptr member io_state
  3126. and functions png_get_io_chunk_name() and png_get_io_state() in pngget.c
  3127. We added PNG_TRANSFORM_GRAY_TO_RGB to the available high-level
  3128. input transforms.
  3129. Checking for and reporting of errors in the IHDR chunk is more thorough.
  3130. Support for global arrays was removed, to improve thread safety.
  3131. Some obsolete/deprecated macros and functions have been removed.
  3132. Typecasted NULL definitions such as
  3133. #define png_voidp_NULL (png_voidp)NULL
  3134. were eliminated. If you used these in your application, just use
  3135. NULL instead.
  3136. The png_struct and info_struct members "trans" and "trans_values" were
  3137. changed to "trans_alpha" and "trans_color", respectively.
  3138. The obsolete, unused pnggccrd.c and pngvcrd.c files and related makefiles
  3139. were removed.
  3140. The PNG_1_0_X and PNG_1_2_X macros were eliminated.
  3141. The PNG_LEGACY_SUPPORTED macro was eliminated.
  3142. Many WIN32_WCE #ifdefs were removed.
  3143. The functions png_read_init(info_ptr), png_write_init(info_ptr),
  3144. png_info_init(info_ptr), png_read_destroy(), and png_write_destroy()
  3145. have been removed. They have been deprecated since libpng-0.95.
  3146. The png_permit_empty_plte() was removed. It has been deprecated
  3147. since libpng-1.0.9. Use png_permit_mng_features() instead.
  3148. We removed the obsolete stub functions png_get_mmx_flagmask(),
  3149. png_set_mmx_thresholds(), png_get_asm_flags(),
  3150. png_get_mmx_bitdepth_threshold(), png_get_mmx_rowbytes_threshold(),
  3151. png_set_asm_flags(), and png_mmx_supported()
  3152. We removed the obsolete png_check_sig(), png_memcpy_check(), and
  3153. png_memset_check() functions. Instead use !png_sig_cmp(), memcpy(),
  3154. and memset(), respectively.
  3155. The function png_set_gray_1_2_4_to_8() was removed. It has been
  3156. deprecated since libpng-1.0.18 and 1.2.9, when it was replaced with
  3157. png_set_expand_gray_1_2_4_to_8() because the former function also
  3158. expanded any tRNS chunk to an alpha channel.
  3159. Macros for png_get_uint_16, png_get_uint_32, and png_get_int_32
  3160. were added and are used by default instead of the corresponding
  3161. functions. Unfortunately,
  3162. from libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
  3163. function) incorrectly returned a value of type png_uint_32.
  3164. We changed the prototype for png_malloc() from
  3165. png_malloc(png_structp png_ptr, png_uint_32 size)
  3166. to
  3167. png_malloc(png_structp png_ptr, png_alloc_size_t size)
  3168. This also applies to the prototype for the user replacement malloc_fn().
  3169. The png_calloc() function was added and is used in place of
  3170. of "png_malloc(); memset();" except in the case in png_read_png()
  3171. where the array consists of pointers; in this case a "for" loop is used
  3172. after the png_malloc() to set the pointers to NULL, to give robust.
  3173. behavior in case the application runs out of memory part-way through
  3174. the process.
  3175. We changed the prototypes of png_get_compression_buffer_size() and
  3176. png_set_compression_buffer_size() to work with png_size_t instead of
  3177. png_uint_32.
  3178. Support for numbered error messages was removed by default, since we
  3179. never got around to actually numbering the error messages. The function
  3180. png_set_strip_error_numbers() was removed from the library by default.
  3181. The png_zalloc() and png_zfree() functions are no longer exported.
  3182. The png_zalloc() function no longer zeroes out the memory that it
  3183. allocates.
  3184. Support for dithering was disabled by default in libpng-1.4.0, because
  3185. it has not been well tested and doesn't actually "dither".
  3186. The code was not
  3187. removed, however, and could be enabled by building libpng with
  3188. PNG_READ_DITHER_SUPPORTED defined. In libpng-1.4.2, this support
  3189. was reenabled, but the function was renamed png_set_quantize() to
  3190. reflect more accurately what it actually does. At the same time,
  3191. the PNG_DITHER_[RED,GREEN_BLUE]_BITS macros were also renamed to
  3192. PNG_QUANTIZE_[RED,GREEN,BLUE]_BITS, and PNG_READ_DITHER_SUPPORTED
  3193. was renamed to PNG_READ_QUANTIZE_SUPPORTED.
  3194. We removed the trailing '.' from the warning and error messages.
  3195. X. Changes to Libpng from version 1.4.x to 1.5.x
  3196. From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
  3197. function) incorrectly returned a value of type png_uint_32.
  3198. A. Changes that affect users of libpng
  3199. There are no substantial API changes between the non-deprecated parts of
  3200. the 1.4.5 API and the 1.5.0 API, however the ability to directly access
  3201. the main libpng control structures, png_struct and png_info, deprecated
  3202. in earlier versions of libpng, has been completely removed from
  3203. libpng 1.5.
  3204. We no longer include zlib.h in png.h. Applications that need access
  3205. to information in zlib.h will need to add the '#include "zlib.h"'
  3206. directive. It does not matter whether it is placed prior to or after
  3207. the '"#include png.h"' directive.
  3208. We moved the png_strcpy(), png_strncpy(), png_strlen(), png_memcpy(),
  3209. png_memcmp(), png_sprintf, and png_memcpy() macros into a private
  3210. header file (pngpriv.h) that is not accessible to applications.
  3211. In png_get_iCCP, the type of "profile" was changed from png_charpp
  3212. to png_bytepp, and in png_set_iCCP, from png_charp to png_const_bytep.
  3213. There are changes of form in png.h, including new and changed macros to
  3214. declare parts of the API. Some API functions with arguments that are
  3215. pointers to data not modified within the function have been corrected to
  3216. declare these arguments with PNG_CONST.
  3217. Much of the internal use of C macros to control the library build has also
  3218. changed and some of this is visible in the exported header files, in
  3219. particular the use of macros to control data and API elements visible
  3220. during application compilation may require significant revision to
  3221. application code. (It is extremely rare for an application to do this.)
  3222. Any program that compiled against libpng 1.4 and did not use deprecated
  3223. features or access internal library structures should compile and work
  3224. against libpng 1.5, except for the change in the prototype for
  3225. png_get_iCCP() and png_set_iCCP() API functions mentioned above.
  3226. libpng 1.5.0 adds PNG_ PASS macros to help in the reading and writing of
  3227. interlaced images. The macros return the number of rows and columns in
  3228. each pass and information that can be used to de-interlace and (if
  3229. absolutely necessary) interlace an image.
  3230. libpng 1.5.0 adds an API png_longjmp(png_ptr, value). This API calls
  3231. the application-provided png_longjmp_ptr on the internal, but application
  3232. initialized, longjmp buffer. It is provided as a convenience to avoid
  3233. the need to use the png_jmpbuf macro, which had the unnecessary side
  3234. effect of resetting the internal png_longjmp_ptr value.
  3235. libpng 1.5.0 includes a complete fixed point API. By default this is
  3236. present along with the corresponding floating point API. In general the
  3237. fixed point API is faster and smaller than the floating point one because
  3238. the PNG file format used fixed point, not floating point. This applies
  3239. even if the library uses floating point in internal calculations. A new
  3240. macro, PNG_FLOATING_ARITHMETIC_SUPPORTED, reveals whether the library
  3241. uses floating point arithmetic (the default) or fixed point arithmetic
  3242. internally for performance critical calculations such as gamma correction.
  3243. In some cases, the gamma calculations may produce slightly different
  3244. results. This has changed the results in png_rgb_to_gray and in alpha
  3245. composition (png_set_background for example). This applies even if the
  3246. original image was already linear (gamma == 1.0) and, therefore, it is
  3247. not necessary to linearize the image. This is because libpng has *not*
  3248. been changed to optimize that case correctly, yet.
  3249. Fixed point support for the sCAL chunk comes with an important caveat;
  3250. the sCAL specification uses a decimal encoding of floating point values
  3251. and the accuracy of PNG fixed point values is insufficient for
  3252. representation of these values. Consequently a "string" API
  3253. (png_get_sCAL_s and png_set_sCAL_s) is the only reliable way of reading
  3254. arbitrary sCAL chunks in the absence of either the floating point API or
  3255. internal floating point calculations.
  3256. Applications no longer need to include the optional distribution header
  3257. file pngusr.h or define the corresponding macros during application
  3258. build in order to see the correct variant of the libpng API. From 1.5.0
  3259. application code can check for the corresponding _SUPPORTED macro:
  3260. #ifdef PNG_INCH_CONVERSIONS_SUPPORTED
  3261. /* code that uses the inch conversion APIs. */
  3262. #endif
  3263. This macro will only be defined if the inch conversion functions have been
  3264. compiled into libpng. The full set of macros, and whether or not support
  3265. has been compiled in, are available in the header file pnglibconf.h.
  3266. This header file is specific to the libpng build. Notice that prior to
  3267. 1.5.0 the _SUPPORTED macros would always have the default definition unless
  3268. reset by pngusr.h or by explicit settings on the compiler command line.
  3269. These settings may produce compiler warnings or errors in 1.5.0 because
  3270. of macro redefinition.
  3271. From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
  3272. function) incorrectly returned a value of type png_uint_32. libpng 1.5.0
  3273. is consistent with the implementation in 1.4.5 and 1.2.x (where the macro
  3274. did not exist.)
  3275. Applications can now choose whether to use these macros or to call the
  3276. corresponding function by defining PNG_USE_READ_MACROS or
  3277. PNG_NO_USE_READ_MACROS before including png.h. Notice that this is
  3278. only supported from 1.5.0 -defining PNG_NO_USE_READ_MACROS prior to 1.5.0
  3279. will lead to a link failure.
  3280. Prior to libpng-1.5.4, the zlib compressor used the same set of parameters
  3281. when compressing the IDAT data and textual data such as zTXt and iCCP.
  3282. In libpng-1.5.4 we reinitialized the zlib stream for each type of data.
  3283. We added five png_set_text_*() functions for setting the parameters to
  3284. use with textual data.
  3285. Prior to libpng-1.5.4, the PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  3286. option was off by default, and slightly inaccurate scaling occurred.
  3287. This option can no longer be turned off, and the choice of accurate
  3288. or inaccurate 16-to-8 scaling is by using the new png_set_scale_16_to_8()
  3289. API for accurate scaling or the old png_set_strip_16_to_8() API for simple
  3290. chopping.
  3291. Prior to libpng-1.5.4, the png_set_user_limits() function could only be
  3292. used to reduce the width and height limits from the value of
  3293. PNG_USER_WIDTH_MAX and PNG_USER_HEIGHT_MAX, although this document said
  3294. that it could be used to override them. Now this function will reduce or
  3295. increase the limits.
  3296. B. Changes to the build and configuration of libpng
  3297. Details of internal changes to the library code can be found in the CHANGES
  3298. file and in the GIT repository logs. These will be of no concern to the vast
  3299. majority of library users or builders, however the few who configure libpng
  3300. to a non-default feature set may need to change how this is done.
  3301. There should be no need for library builders to alter build scripts if
  3302. these use the distributed build support - configure or the makefiles -
  3303. however users of the makefiles may care to update their build scripts
  3304. to build pnglibconf.h where the corresponding makefile does not do so.
  3305. Building libpng with a non-default configuration has changed completely.
  3306. The old method using pngusr.h should still work correctly even though the
  3307. way pngusr.h is used in the build has been changed; however, library
  3308. builders will probably want to examine the changes to take advantage of
  3309. new capabilities and to simplify their build system.
  3310. B.1 Specific changes to library configuration capabilities
  3311. The library now supports a complete fixed point implementation and can
  3312. thus be used on systems that have no floating point support or very
  3313. limited or slow support. Previously gamma correction, an essential part
  3314. of complete PNG support, required reasonably fast floating point.
  3315. As part of this the choice of internal implementation has been made
  3316. independent of the choice of fixed versus floating point APIs and all the
  3317. missing fixed point APIs have been implemented.
  3318. The exact mechanism used to control attributes of API functions has
  3319. changed. A single set of operating system independent macro definitions
  3320. is used and operating system specific directives are defined in
  3321. pnglibconf.h
  3322. As part of this the mechanism used to choose procedure call standards on
  3323. those systems that allow a choice has been changed. At present this only
  3324. affects certain Microsoft (DOS, Windows) and IBM (OS/2) operating systems
  3325. running on Intel processors. As before, PNGAPI is defined where required
  3326. to control the exported API functions; however, two new macros, PNGCBAPI
  3327. and PNGCAPI, are used instead for callback functions (PNGCBAPI) and
  3328. (PNGCAPI) for functions that must match a C library prototype (currently
  3329. only png_longjmp_ptr, which must match the C longjmp function.) The new
  3330. approach is documented in pngconf.h
  3331. Despite these changes, libpng 1.5.0 only supports the native C function
  3332. calling standard on those platforms tested so far (__cdecl on Microsoft
  3333. Windows). This is because the support requirements for alternative
  3334. calling conventions seem to no longer exist. Developers who find it
  3335. necessary to set PNG_API_RULE to 1 should advise the mailing list
  3336. (png-mng-implement) of this and library builders who use Openwatcom and
  3337. therefore set PNG_API_RULE to 2 should also contact the mailing list.
  3338. A new test program, pngvalid, is provided in addition to pngtest.
  3339. pngvalid validates the arithmetic accuracy of the gamma correction
  3340. calculations and includes a number of validations of the file format.
  3341. A subset of the full range of tests is run when "make check" is done
  3342. (in the 'configure' build.) pngvalid also allows total allocated memory
  3343. usage to be evaluated and performs additional memory overwrite validation.
  3344. Many changes to individual feature macros have been made. The following
  3345. are the changes most likely to be noticed by library builders who
  3346. configure libpng:
  3347. 1) All feature macros now have consistent naming:
  3348. #define PNG_NO_feature turns the feature off
  3349. #define PNG_feature_SUPPORTED turns the feature on
  3350. pnglibconf.h contains one line for each feature macro which is either:
  3351. #define PNG_feature_SUPPORTED
  3352. if the feature is supported or:
  3353. /*#undef PNG_feature_SUPPORTED*/
  3354. if it is not. Library code consistently checks for the 'SUPPORTED' macro.
  3355. It does not, and libpng applications should not, check for the 'NO' macro
  3356. which will not normally be defined even if the feature is not supported.
  3357. The 'NO' macros are only used internally for setting or not setting the
  3358. corresponding 'SUPPORTED' macros.
  3359. Compatibility with the old names is provided as follows:
  3360. PNG_INCH_CONVERSIONS turns on PNG_INCH_CONVERSIONS_SUPPORTED
  3361. And the following definitions disable the corresponding feature:
  3362. PNG_SETJMP_NOT_SUPPORTED disables SETJMP
  3363. PNG_READ_TRANSFORMS_NOT_SUPPORTED disables READ_TRANSFORMS
  3364. PNG_NO_READ_COMPOSITED_NODIV disables READ_COMPOSITE_NODIV
  3365. PNG_WRITE_TRANSFORMS_NOT_SUPPORTED disables WRITE_TRANSFORMS
  3366. PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED disables READ_ANCILLARY_CHUNKS
  3367. PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED disables WRITE_ANCILLARY_CHUNKS
  3368. Library builders should remove use of the above, inconsistent, names.
  3369. 2) Warning and error message formatting was previously conditional on
  3370. the STDIO feature. The library has been changed to use the
  3371. CONSOLE_IO feature instead. This means that if CONSOLE_IO is disabled
  3372. the library no longer uses the printf(3) functions, even though the
  3373. default read/write implementations use (FILE) style stdio.h functions.
  3374. 3) Three feature macros now control the fixed/floating point decisions:
  3375. PNG_FLOATING_POINT_SUPPORTED enables the floating point APIs
  3376. PNG_FIXED_POINT_SUPPORTED enables the fixed point APIs; however, in
  3377. practice these are normally required internally anyway (because the PNG
  3378. file format is fixed point), therefore in most cases PNG_NO_FIXED_POINT
  3379. merely stops the function from being exported.
  3380. PNG_FLOATING_ARITHMETIC_SUPPORTED chooses between the internal floating
  3381. point implementation or the fixed point one. Typically the fixed point
  3382. implementation is larger and slower than the floating point implementation
  3383. on a system that supports floating point, however it may be faster on a
  3384. system which lacks floating point hardware and therefore uses a software
  3385. emulation.
  3386. 4) Added PNG_{READ,WRITE}_INT_FUNCTIONS_SUPPORTED. This allows the
  3387. functions to read and write ints to be disabled independently of
  3388. PNG_USE_READ_MACROS, which allows libpng to be built with the functions
  3389. even though the default is to use the macros - this allows applications
  3390. to choose at app buildtime whether or not to use macros (previously
  3391. impossible because the functions weren't in the default build.)
  3392. B.2 Changes to the configuration mechanism
  3393. Prior to libpng-1.5.0 library builders who needed to configure libpng
  3394. had either to modify the exported pngconf.h header file to add system
  3395. specific configuration or had to write feature selection macros into
  3396. pngusr.h and cause this to be included into pngconf.h by defining
  3397. PNG_USER_CONFIG. The latter mechanism had the disadvantage that an
  3398. application built without PNG_USER_CONFIG defined would see the
  3399. unmodified, default, libpng API and thus would probably fail to link.
  3400. These mechanisms still work in the configure build and in any makefile
  3401. build that builds pnglibconf.h, although the feature selection macros
  3402. have changed somewhat as described above. In 1.5.0, however, pngusr.h is
  3403. processed only once, when the exported header file pnglibconf.h is built.
  3404. pngconf.h no longer includes pngusr.h, therefore pngusr.h is ignored after the
  3405. build of pnglibconf.h and it is never included in an application build.
  3406. The rarely used alternative of adding a list of feature macros to the
  3407. CFLAGS setting in the build also still works, however the macros will be
  3408. copied to pnglibconf.h and this may produce macro redefinition warnings
  3409. when the individual C files are compiled.
  3410. All configuration now only works if pnglibconf.h is built from
  3411. scripts/pnglibconf.dfa. This requires the program awk. Brian Kernighan
  3412. (the original author of awk) maintains C source code of that awk and this
  3413. and all known later implementations (often called by subtly different
  3414. names - nawk and gawk for example) are adequate to build pnglibconf.h.
  3415. The Sun Microsystems (now Oracle) program 'awk' is an earlier version
  3416. and does not work; this may also apply to other systems that have a
  3417. functioning awk called 'nawk'.
  3418. Configuration options are now documented in scripts/pnglibconf.dfa. This
  3419. file also includes dependency information that ensures a configuration is
  3420. consistent; that is, if a feature is switched off dependent features are
  3421. also removed. As a recommended alternative to using feature macros in
  3422. pngusr.h a system builder may also define equivalent options in pngusr.dfa
  3423. (or, indeed, any file) and add that to the configuration by setting
  3424. DFA_XTRA to the file name. The makefiles in contrib/pngminim illustrate
  3425. how to do this, and a case where pngusr.h is still required.
  3426. XI. Detecting libpng
  3427. The png_get_io_ptr() function has been present since libpng-0.88, has never
  3428. changed, and is unaffected by conditional compilation macros. It is the
  3429. best choice for use in configure scripts for detecting the presence of any
  3430. libpng version since 0.88. In an autoconf "configure.in" you could use
  3431. AC_CHECK_LIB(png, png_get_io_ptr, ...
  3432. XII. Source code repository
  3433. Since about February 2009, version 1.2.34, libpng has been under "git" source
  3434. control. The git repository was built from old libpng-x.y.z.tar.gz files
  3435. going back to version 0.70. You can access the git repository (read only)
  3436. at
  3437. git://libpng.git.sourceforge.net/gitroot/libpng
  3438. or you can browse it via "gitweb" at
  3439. http://libpng.git.sourceforge.net/git/gitweb.cgi?p=libpng
  3440. Patches can be sent to glennrp at users.sourceforge.net or to
  3441. png-mng-implement at lists.sourceforge.net or you can upload them to
  3442. the libpng bug tracker at
  3443. http://libpng.sourceforge.net
  3444. We also accept patches built from the tar or zip distributions, and
  3445. simple verbal discriptions of bug fixes, reported either to the
  3446. SourceForge bug tracker, to the png-mng-implement at lists.sf.net
  3447. mailing list, or directly to glennrp.
  3448. XIII. Coding style
  3449. Our coding style is similar to the "Allman" style, with curly
  3450. braces on separate lines:
  3451. if (condition)
  3452. {
  3453. action;
  3454. }
  3455. else if (another condition)
  3456. {
  3457. another action;
  3458. }
  3459. The braces can be omitted from simple one-line actions:
  3460. if (condition)
  3461. return (0);
  3462. We use 3-space indentation, except for continued statements which
  3463. are usually indented the same as the first line of the statement
  3464. plus four more spaces.
  3465. For macro definitions we use 2-space indentation, always leaving the "#"
  3466. in the first column.
  3467. #ifndef PNG_NO_FEATURE
  3468. # ifndef PNG_FEATURE_SUPPORTED
  3469. # define PNG_FEATURE_SUPPORTED
  3470. # endif
  3471. #endif
  3472. Comments appear with the leading "/*" at the same indentation as
  3473. the statement that follows the comment:
  3474. /* Single-line comment */
  3475. statement;
  3476. /* This is a multiple-line
  3477. * comment.
  3478. */
  3479. statement;
  3480. Very short comments can be placed after the end of the statement
  3481. to which they pertain:
  3482. statement; /* comment */
  3483. We don't use C++ style ("//") comments. We have, however,
  3484. used them in the past in some now-abandoned MMX assembler
  3485. code.
  3486. Functions and their curly braces are not indented, and
  3487. exported functions are marked with PNGAPI:
  3488. /* This is a public function that is visible to
  3489. * application programmers. It does thus-and-so.
  3490. */
  3491. void PNGAPI
  3492. png_exported_function(png_ptr, png_info, foo)
  3493. {
  3494. body;
  3495. }
  3496. The prototypes for all exported functions appear in png.h,
  3497. above the comment that says
  3498. /* Maintainer: Put new public prototypes here ... */
  3499. We mark all non-exported functions with "/* PRIVATE */"":
  3500. void /* PRIVATE */
  3501. png_non_exported_function(png_ptr, png_info, foo)
  3502. {
  3503. body;
  3504. }
  3505. The prototypes for non-exported functions (except for those in
  3506. pngtest) appear in
  3507. pngpriv.h
  3508. above the comment that says
  3509. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  3510. To avoid polluting the global namespace, the names of all exported
  3511. functions and variables begin with "png_", and all publicly visible C
  3512. preprocessor macros begin with "PNG_". We request that applications that
  3513. use libpng *not* begin any of their own symbols with either of these strings.
  3514. We put a space after each comma and after each semicolon
  3515. in "for" statements, and we put spaces before and after each
  3516. C binary operator and after "for" or "while", and before
  3517. "?". We don't put a space between a typecast and the expression
  3518. being cast, nor do we put one between a function name and the
  3519. left parenthesis that follows it:
  3520. for (i = 2; i > 0; --i)
  3521. y[i] = a(x) + (int)b;
  3522. We prefer #ifdef and #ifndef to #if defined() and if !defined()
  3523. when there is only one macro being tested.
  3524. We prefer to express integers that are used as bit masks in hex format,
  3525. with an even number of lower-case hex digits (e.g., 0x00, 0xff, 0x0100).
  3526. We do not use the TAB character for indentation in the C sources.
  3527. Lines do not exceed 80 characters.
  3528. Other rules can be inferred by inspecting the libpng source.
  3529. XIV. Y2K Compliance in libpng
  3530. February 18, 2012
  3531. Since the PNG Development group is an ad-hoc body, we can't make
  3532. an official declaration.
  3533. This is your unofficial assurance that libpng from version 0.71 and
  3534. upward through 1.5.9 are Y2K compliant. It is my belief that earlier
  3535. versions were also Y2K compliant.
  3536. Libpng only has three year fields. One is a 2-byte unsigned integer that
  3537. will hold years up to 65535. The other two hold the date in text
  3538. format, and will hold years up to 9999.
  3539. The integer is
  3540. "png_uint_16 year" in png_time_struct.
  3541. The strings are
  3542. "png_charp time_buffer" in png_struct and
  3543. "near_time_buffer", which is a local character string in png.c.
  3544. There are seven time-related functions:
  3545. png_convert_to_rfc_1123() in png.c
  3546. (formerly png_convert_to_rfc_1152() in error)
  3547. png_convert_from_struct_tm() in pngwrite.c, called
  3548. in pngwrite.c
  3549. png_convert_from_time_t() in pngwrite.c
  3550. png_get_tIME() in pngget.c
  3551. png_handle_tIME() in pngrutil.c, called in pngread.c
  3552. png_set_tIME() in pngset.c
  3553. png_write_tIME() in pngwutil.c, called in pngwrite.c
  3554. All appear to handle dates properly in a Y2K environment. The
  3555. png_convert_from_time_t() function calls gmtime() to convert from system
  3556. clock time, which returns (year - 1900), which we properly convert to
  3557. the full 4-digit year. There is a possibility that applications using
  3558. libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  3559. function, or that they are incorrectly passing only a 2-digit year
  3560. instead of "year - 1900" into the png_convert_from_struct_tm() function,
  3561. but this is not under our control. The libpng documentation has always
  3562. stated that it works with 4-digit years, and the APIs have been
  3563. documented as such.
  3564. The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  3565. integer to hold the year, and can hold years as large as 65535.
  3566. zlib, upon which libpng depends, is also Y2K compliant. It contains
  3567. no date-related code.
  3568. Glenn Randers-Pehrson
  3569. libpng maintainer
  3570. PNG Development Group