Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4214 lines
171 KiB

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