PageRenderTime 85ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/cabalistic/ogredeps/
Plain Text | 1513 lines | 1227 code | 286 blank | 0 comment | 0 complexity | ffa7eb01a237d2219f0020e029830427 MD5 | raw file
Possible License(s): LGPL-3.0, BSD-3-Clause, CPL-1.0, Unlicense, GPL-2.0, GPL-3.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, BSD-2-Clause, LGPL-2.1
  1. libpng.txt - A description on how to use and modify libpng
  2. libpng version 1.2.41 - December 3, 2009
  3. Updated and distributed by Glenn Randers-Pehrson
  4. <glennrp at users.sourceforge.net>
  5. Copyright (c) 1998-2009 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.2.41 - December 3, 2009
  11. Updated and distributed by Glenn Randers-Pehrson
  12. Copyright (c) 1998-2009 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. The first, png_struct, is an internal structure that
  81. will not, for the most part, be used by a user except as the first
  82. variable passed to every libpng function call.
  83. The png_info structure is designed to provide information about the
  84. PNG file. At one time, the fields of png_info were intended to be
  85. directly accessible to the user. However, this tended to cause problems
  86. with applications using dynamically loaded libraries, and as a result
  87. a set of interface functions for png_info (the png_get_*() and png_set_*()
  88. functions) was developed. The fields of png_info are still available for
  89. older applications, but it is suggested that applications use the new
  90. interfaces if at all possible.
  91. Applications that do make direct access to the members of png_struct (except
  92. for png_ptr->jmpbuf) must be recompiled whenever the library is updated,
  93. and applications that make direct access to the members of png_info must
  94. be recompiled if they were compiled or loaded with libpng version 1.0.6,
  95. in which the members were in a different order. In version 1.0.7, the
  96. members of the png_info structure reverted to the old order, as they were
  97. in versions 0.97c through 1.0.5. Starting with version 2.0.0, both
  98. structures are going to be hidden, and the contents of the structures will
  99. only be accessible through the png_get/png_set functions.
  100. The png.h header file is an invaluable reference for programming with libpng.
  101. And while I'm on the topic, make sure you include the libpng header file:
  102. #include <png.h>
  103. III. Reading
  104. We'll now walk you through the possible functions to call when reading
  105. in a PNG file sequentially, briefly explaining the syntax and purpose
  106. of each one. See example.c and png.h for more detail. While
  107. progressive reading is covered in the next section, you will still
  108. need some of the functions discussed in this section to read a PNG
  109. file.
  110. Setup
  111. You will want to do the I/O initialization(*) before you get into libpng,
  112. so if it doesn't work, you don't have much to undo. Of course, you
  113. will also want to insure that you are, in fact, dealing with a PNG
  114. file. Libpng provides a simple check to see if a file is a PNG file.
  115. To use it, pass in the first 1 to 8 bytes of the file to the function
  116. png_sig_cmp(), and it will return 0 (false) if the bytes match the
  117. corresponding bytes of the PNG signature, or nonzero (true) otherwise.
  118. Of course, the more bytes you pass in, the greater the accuracy of the
  119. prediction.
  120. If you are intending to keep the file pointer open for use in libpng,
  121. you must ensure you don't read more than 8 bytes from the beginning
  122. of the file, and you also have to make a call to png_set_sig_bytes_read()
  123. with the number of bytes you read from the beginning. Libpng will
  124. then only check the bytes (if any) that your program didn't read.
  125. (*): If you are not using the standard I/O functions, you will need
  126. to replace them with custom functions. See the discussion under
  127. Customizing libpng.
  128. FILE *fp = fopen(file_name, "rb");
  129. if (!fp)
  130. {
  131. return (ERROR);
  132. }
  133. fread(header, 1, number, fp);
  134. is_png = !png_sig_cmp(header, 0, number);
  135. if (!is_png)
  136. {
  137. return (NOT_PNG);
  138. }
  139. Next, png_struct and png_info need to be allocated and initialized. In
  140. order to ensure that the size of these structures is correct even with a
  141. dynamically linked libpng, there are functions to initialize and
  142. allocate the structures. We also pass the library version, optional
  143. pointers to error handling functions, and a pointer to a data struct for
  144. use by the error functions, if necessary (the pointer and functions can
  145. be NULL if the default error handlers are to be used). See the section
  146. on Changes to Libpng below regarding the old initialization functions.
  147. The structure allocation functions quietly return NULL if they fail to
  148. create the structure, so your application should check for that.
  149. png_structp png_ptr = png_create_read_struct
  150. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  151. user_error_fn, user_warning_fn);
  152. if (!png_ptr)
  153. return (ERROR);
  154. png_infop info_ptr = png_create_info_struct(png_ptr);
  155. if (!info_ptr)
  156. {
  157. png_destroy_read_struct(&png_ptr,
  158. (png_infopp)NULL, (png_infopp)NULL);
  159. return (ERROR);
  160. }
  161. png_infop end_info = png_create_info_struct(png_ptr);
  162. if (!end_info)
  163. {
  164. png_destroy_read_struct(&png_ptr, &info_ptr,
  165. (png_infopp)NULL);
  166. return (ERROR);
  167. }
  168. If you want to use your own memory allocation routines,
  169. define PNG_USER_MEM_SUPPORTED and use
  170. png_create_read_struct_2() instead of png_create_read_struct():
  171. png_structp png_ptr = png_create_read_struct_2
  172. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  173. user_error_fn, user_warning_fn, (png_voidp)
  174. user_mem_ptr, user_malloc_fn, user_free_fn);
  175. The error handling routines passed to png_create_read_struct()
  176. and the memory alloc/free routines passed to png_create_struct_2()
  177. are only necessary if you are not using the libpng supplied error
  178. handling and memory alloc/free functions.
  179. When libpng encounters an error, it expects to longjmp back
  180. to your routine. Therefore, you will need to call setjmp and pass
  181. your png_jmpbuf(png_ptr). If you read the file from different
  182. routines, you will need to update the jmpbuf field every time you enter
  183. a new routine that will call a png_*() function.
  184. See your documentation of setjmp/longjmp for your compiler for more
  185. information on setjmp/longjmp. See the discussion on libpng error
  186. handling in the Customizing Libpng section below for more information
  187. on the libpng error handling. If an error occurs, and libpng longjmp's
  188. back to your setjmp, you will want to call png_destroy_read_struct() to
  189. free any memory.
  190. if (setjmp(png_jmpbuf(png_ptr)))
  191. {
  192. png_destroy_read_struct(&png_ptr, &info_ptr,
  193. &end_info);
  194. fclose(fp);
  195. return (ERROR);
  196. }
  197. If you would rather avoid the complexity of setjmp/longjmp issues,
  198. you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case
  199. errors will result in a call to PNG_ABORT() which defaults to abort().
  200. Now you need to set up the input code. The default for libpng is to
  201. use the C function fread(). If you use this, you will need to pass a
  202. valid FILE * in the function png_init_io(). Be sure that the file is
  203. opened in binary mode. If you wish to handle reading data in another
  204. way, you need not call the png_init_io() function, but you must then
  205. implement the libpng I/O methods discussed in the Customizing Libpng
  206. section below.
  207. png_init_io(png_ptr, fp);
  208. If you had previously opened the file and read any of the signature from
  209. the beginning in order to see if this was a PNG file, you need to let
  210. libpng know that there are some bytes missing from the start of the file.
  211. png_set_sig_bytes(png_ptr, number);
  212. Setting up callback code
  213. You can set up a callback function to handle any unknown chunks in the
  214. input stream. You must supply the function
  215. read_chunk_callback(png_ptr ptr,
  216. png_unknown_chunkp chunk);
  217. {
  218. /* The unknown chunk structure contains your
  219. chunk data, along with similar data for any other
  220. unknown chunks: */
  221. png_byte name[5];
  222. png_byte *data;
  223. png_size_t size;
  224. /* Note that libpng has already taken care of
  225. the CRC handling */
  226. /* put your code here. Search for your chunk in the
  227. unknown chunk structure, process it, and return one
  228. of the following: */
  229. return (-n); /* chunk had an error */
  230. return (0); /* did not recognize */
  231. return (n); /* success */
  232. }
  233. (You can give your function another name that you like instead of
  234. "read_chunk_callback")
  235. To inform libpng about your function, use
  236. png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr,
  237. read_chunk_callback);
  238. This names not only the callback function, but also a user pointer that
  239. you can retrieve with
  240. png_get_user_chunk_ptr(png_ptr);
  241. If you call the png_set_read_user_chunk_fn() function, then all unknown
  242. chunks will be saved when read, in case your callback function will need
  243. one or more of them. This behavior can be changed with the
  244. png_set_keep_unknown_chunks() function, described below.
  245. At this point, you can set up a callback function that will be
  246. called after each row has been read, which you can use to control
  247. a progress meter or the like. It's demonstrated in pngtest.c.
  248. You must supply a function
  249. void read_row_callback(png_ptr ptr, png_uint_32 row,
  250. int pass);
  251. {
  252. /* put your code here */
  253. }
  254. (You can give it another name that you like instead of "read_row_callback")
  255. To inform libpng about your function, use
  256. png_set_read_status_fn(png_ptr, read_row_callback);
  257. Unknown-chunk handling
  258. Now you get to set the way the library processes unknown chunks in the
  259. input PNG stream. Both known and unknown chunks will be read. Normal
  260. behavior is that known chunks will be parsed into information in
  261. various info_ptr members while unknown chunks will be discarded. This
  262. behavior can be wasteful if your application will never use some known
  263. chunk types. To change this, you can call:
  264. png_set_keep_unknown_chunks(png_ptr, keep,
  265. chunk_list, num_chunks);
  266. keep - 0: default unknown chunk handling
  267. 1: ignore; do not keep
  268. 2: keep only if safe-to-copy
  269. 3: keep even if unsafe-to-copy
  270. You can use these definitions:
  271. PNG_HANDLE_CHUNK_AS_DEFAULT 0
  272. PNG_HANDLE_CHUNK_NEVER 1
  273. PNG_HANDLE_CHUNK_IF_SAFE 2
  274. PNG_HANDLE_CHUNK_ALWAYS 3
  275. chunk_list - list of chunks affected (a byte string,
  276. five bytes per chunk, NULL or '\0' if
  277. num_chunks is 0)
  278. num_chunks - number of chunks affected; if 0, all
  279. unknown chunks are affected. If nonzero,
  280. only the chunks in the list are affected
  281. Unknown chunks declared in this way will be saved as raw data onto a
  282. list of png_unknown_chunk structures. If a chunk that is normally
  283. known to libpng is named in the list, it will be handled as unknown,
  284. according to the "keep" directive. If a chunk is named in successive
  285. instances of png_set_keep_unknown_chunks(), the final instance will
  286. take precedence. The IHDR and IEND chunks should not be named in
  287. chunk_list; if they are, libpng will process them normally anyway.
  288. Here is an example of the usage of png_set_keep_unknown_chunks(),
  289. where the private "vpAg" chunk will later be processed by a user chunk
  290. callback function:
  291. png_byte vpAg[5]={118, 112, 65, 103, (png_byte) '\0'};
  292. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  293. png_byte unused_chunks[]=
  294. {
  295. 104, 73, 83, 84, (png_byte) '\0', /* hIST */
  296. 105, 84, 88, 116, (png_byte) '\0', /* iTXt */
  297. 112, 67, 65, 76, (png_byte) '\0', /* pCAL */
  298. 115, 67, 65, 76, (png_byte) '\0', /* sCAL */
  299. 115, 80, 76, 84, (png_byte) '\0', /* sPLT */
  300. 116, 73, 77, 69, (png_byte) '\0', /* tIME */
  301. };
  302. #endif
  303. ...
  304. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  305. /* ignore all unknown chunks: */
  306. png_set_keep_unknown_chunks(read_ptr, 1, NULL, 0);
  307. /* except for vpAg: */
  308. png_set_keep_unknown_chunks(read_ptr, 2, vpAg, 1);
  309. /* also ignore unused known chunks: */
  310. png_set_keep_unknown_chunks(read_ptr, 1, unused_chunks,
  311. (int)sizeof(unused_chunks)/5);
  312. #endif
  313. User limits
  314. The PNG specification allows the width and height of an image to be as
  315. large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.
  316. Since very few applications really need to process such large images,
  317. we have imposed an arbitrary 1-million limit on rows and columns.
  318. Larger images will be rejected immediately with a png_error() call. If
  319. you wish to override this limit, you can use
  320. png_set_user_limits(png_ptr, width_max, height_max);
  321. to set your own limits, or use width_max = height_max = 0x7fffffffL
  322. to allow all valid dimensions (libpng may reject some very large images
  323. anyway because of potential buffer overflow conditions).
  324. You should put this statement after you create the PNG structure and
  325. before calling png_read_info(), png_read_png(), or png_process_data().
  326. If you need to retrieve the limits that are being applied, use
  327. width_max = png_get_user_width_max(png_ptr);
  328. height_max = png_get_user_height_max(png_ptr);
  329. The PNG specification sets no limit on the number of ancillary chunks
  330. allowed in a PNG datastream. You can impose a limit on the total number
  331. of sPLT, tEXt, iTXt, zTXt, and unknown chunks that will be stored, with
  332. png_set_chunk_cache_max(png_ptr, user_chunk_cache_max);
  333. where 0x7fffffffL means unlimited. You can retrieve this limit with
  334. chunk_cache_max = png_get_chunk_cache_max(png_ptr);
  335. This limit also applies to the number of buffers that can be allocated
  336. by png_decompress_chunk() while decompressing iTXt, zTXt, and iCCP chunks.
  337. The high-level read interface
  338. At this point there are two ways to proceed; through the high-level
  339. read interface, or through a sequence of low-level read operations.
  340. You can use the high-level interface if (a) you are willing to read
  341. the entire image into memory, and (b) the input transformations
  342. you want to do are limited to the following set:
  343. PNG_TRANSFORM_IDENTITY No transformation
  344. PNG_TRANSFORM_STRIP_16 Strip 16-bit samples to
  345. 8 bits
  346. PNG_TRANSFORM_STRIP_ALPHA Discard the alpha channel
  347. PNG_TRANSFORM_PACKING Expand 1, 2 and 4-bit
  348. samples to bytes
  349. PNG_TRANSFORM_PACKSWAP Change order of packed
  350. pixels to LSB first
  351. PNG_TRANSFORM_EXPAND Perform set_expand()
  352. PNG_TRANSFORM_INVERT_MONO Invert monochrome images
  353. PNG_TRANSFORM_SHIFT Normalize pixels to the
  354. sBIT depth
  355. PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
  356. to BGRA
  357. PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
  358. to AG
  359. PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
  360. to transparency
  361. PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
  362. PNG_TRANSFORM_GRAY_TO_RGB Expand grayscale samples
  363. to RGB (or GA to RGBA)
  364. (This excludes setting a background color, doing gamma transformation,
  365. dithering, and setting filler.) If this is the case, simply do this:
  366. png_read_png(png_ptr, info_ptr, png_transforms, NULL)
  367. where png_transforms is an integer containing the bitwise OR of some
  368. set of transformation flags. This call is equivalent to png_read_info(),
  369. followed the set of transformations indicated by the transform mask,
  370. then png_read_image(), and finally png_read_end().
  371. (The final parameter of this call is not yet used. Someday it might point
  372. to transformation parameters required by some future input transform.)
  373. You must use png_transforms and not call any png_set_transform() functions
  374. when you use png_read_png().
  375. After you have called png_read_png(), you can retrieve the image data
  376. with
  377. row_pointers = png_get_rows(png_ptr, info_ptr);
  378. where row_pointers is an array of pointers to the pixel data for each row:
  379. png_bytep row_pointers[height];
  380. If you know your image size and pixel size ahead of time, you can allocate
  381. row_pointers prior to calling png_read_png() with
  382. if (height > PNG_UINT_32_MAX/png_sizeof(png_byte))
  383. png_error (png_ptr,
  384. "Image is too tall to process in memory");
  385. if (width > PNG_UINT_32_MAX/pixel_size)
  386. png_error (png_ptr,
  387. "Image is too wide to process in memory");
  388. row_pointers = png_malloc(png_ptr,
  389. height*png_sizeof(png_bytep));
  390. for (int i=0; i<height, i++)
  391. row_pointers[i]=NULL; /* security precaution */
  392. for (int i=0; i<height, i++)
  393. row_pointers[i]=png_malloc(png_ptr,
  394. width*pixel_size);
  395. png_set_rows(png_ptr, info_ptr, &row_pointers);
  396. Alternatively you could allocate your image in one big block and define
  397. row_pointers[i] to point into the proper places in your block.
  398. If you use png_set_rows(), the application is responsible for freeing
  399. row_pointers (and row_pointers[i], if they were separately allocated).
  400. If you don't allocate row_pointers ahead of time, png_read_png() will
  401. do it, and it'll be free'ed when you call png_destroy_*().
  402. The low-level read interface
  403. If you are going the low-level route, you are now ready to read all
  404. the file information up to the actual image data. You do this with a
  405. call to png_read_info().
  406. png_read_info(png_ptr, info_ptr);
  407. This will process all chunks up to but not including the image data.
  408. Querying the info structure
  409. Functions are used to get the information from the info_ptr once it
  410. has been read. Note that these fields may not be completely filled
  411. in until png_read_end() has read the chunk data following the image.
  412. png_get_IHDR(png_ptr, info_ptr, &width, &height,
  413. &bit_depth, &color_type, &interlace_type,
  414. &compression_type, &filter_method);
  415. width - holds the width of the image
  416. in pixels (up to 2^31).
  417. height - holds the height of the image
  418. in pixels (up to 2^31).
  419. bit_depth - holds the bit depth of one of the
  420. image channels. (valid values are
  421. 1, 2, 4, 8, 16 and depend also on
  422. the color_type. See also
  423. significant bits (sBIT) below).
  424. color_type - describes which color/alpha channels
  425. are present.
  426. PNG_COLOR_TYPE_GRAY
  427. (bit depths 1, 2, 4, 8, 16)
  428. PNG_COLOR_TYPE_GRAY_ALPHA
  429. (bit depths 8, 16)
  430. PNG_COLOR_TYPE_PALETTE
  431. (bit depths 1, 2, 4, 8)
  432. PNG_COLOR_TYPE_RGB
  433. (bit_depths 8, 16)
  434. PNG_COLOR_TYPE_RGB_ALPHA
  435. (bit_depths 8, 16)
  436. PNG_COLOR_MASK_PALETTE
  437. PNG_COLOR_MASK_COLOR
  438. PNG_COLOR_MASK_ALPHA
  439. filter_method - (must be PNG_FILTER_TYPE_BASE
  440. for PNG 1.0, and can also be
  441. PNG_INTRAPIXEL_DIFFERENCING if
  442. the PNG datastream is embedded in
  443. a MNG-1.0 datastream)
  444. compression_type - (must be PNG_COMPRESSION_TYPE_BASE
  445. for PNG 1.0)
  446. interlace_type - (PNG_INTERLACE_NONE or
  447. PNG_INTERLACE_ADAM7)
  448. Any or all of interlace_type, compression_type, or
  449. filter_method can be NULL if you are
  450. not interested in their values.
  451. Note that png_get_IHDR() returns 32-bit data into
  452. the application's width and height variables.
  453. This is an unsafe situation if these are 16-bit
  454. variables. In such situations, the
  455. png_get_image_width() and png_get_image_height()
  456. functions described below are safer.
  457. width = png_get_image_width(png_ptr,
  458. info_ptr);
  459. height = png_get_image_height(png_ptr,
  460. info_ptr);
  461. bit_depth = png_get_bit_depth(png_ptr,
  462. info_ptr);
  463. color_type = png_get_color_type(png_ptr,
  464. info_ptr);
  465. filter_method = png_get_filter_type(png_ptr,
  466. info_ptr);
  467. compression_type = png_get_compression_type(png_ptr,
  468. info_ptr);
  469. interlace_type = png_get_interlace_type(png_ptr,
  470. info_ptr);
  471. channels = png_get_channels(png_ptr, info_ptr);
  472. channels - number of channels of info for the
  473. color type (valid values are 1 (GRAY,
  474. PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
  475. 4 (RGB_ALPHA or RGB + filler byte))
  476. rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  477. rowbytes - number of bytes needed to hold a row
  478. signature = png_get_signature(png_ptr, info_ptr);
  479. signature - holds the signature read from the
  480. file (if any). The data is kept in
  481. the same offset it would be if the
  482. whole signature were read (i.e. if an
  483. application had already read in 4
  484. bytes of signature before starting
  485. libpng, the remaining 4 bytes would
  486. be in signature[4] through signature[7]
  487. (see png_set_sig_bytes())).
  488. These are also important, but their validity depends on whether the chunk
  489. has been read. The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
  490. png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
  491. data has been read, or zero if it is missing. The parameters to the
  492. png_get_<chunk> are set directly if they are simple data types, or a
  493. pointer into the info_ptr is returned for any complex types.
  494. png_get_PLTE(png_ptr, info_ptr, &palette,
  495. &num_palette);
  496. palette - the palette for the file
  497. (array of png_color)
  498. num_palette - number of entries in the palette
  499. png_get_gAMA(png_ptr, info_ptr, &gamma);
  500. gamma - the gamma the file is written
  501. at (PNG_INFO_gAMA)
  502. png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
  503. srgb_intent - the rendering intent (PNG_INFO_sRGB)
  504. The presence of the sRGB chunk
  505. means that the pixel data is in the
  506. sRGB color space. This chunk also
  507. implies specific values of gAMA and
  508. cHRM.
  509. png_get_iCCP(png_ptr, info_ptr, &name,
  510. &compression_type, &profile, &proflen);
  511. name - The profile name.
  512. compression - The compression type; always
  513. PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
  514. You may give NULL to this argument to
  515. ignore it.
  516. profile - International Color Consortium color
  517. profile data. May contain NULs.
  518. proflen - length of profile data in bytes.
  519. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  520. sig_bit - the number of significant bits for
  521. (PNG_INFO_sBIT) each of the gray,
  522. red, green, and blue channels,
  523. whichever are appropriate for the
  524. given color type (png_color_16)
  525. png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
  526. &trans_values);
  527. trans - array of transparent
  528. entries for palette (PNG_INFO_tRNS)
  529. trans_values - graylevel or color sample values of
  530. the single transparent color for
  531. non-paletted images (PNG_INFO_tRNS)
  532. num_trans - number of transparent entries
  533. (PNG_INFO_tRNS)
  534. png_get_hIST(png_ptr, info_ptr, &hist);
  535. (PNG_INFO_hIST)
  536. hist - histogram of palette (array of
  537. png_uint_16)
  538. png_get_tIME(png_ptr, info_ptr, &mod_time);
  539. mod_time - time image was last modified
  540. (PNG_VALID_tIME)
  541. png_get_bKGD(png_ptr, info_ptr, &background);
  542. background - background color (PNG_VALID_bKGD)
  543. valid 16-bit red, green and blue
  544. values, regardless of color_type
  545. num_comments = png_get_text(png_ptr, info_ptr,
  546. &text_ptr, &num_text);
  547. num_comments - number of comments
  548. text_ptr - array of png_text holding image
  549. comments
  550. text_ptr[i].compression - type of compression used
  551. on "text" PNG_TEXT_COMPRESSION_NONE
  552. PNG_TEXT_COMPRESSION_zTXt
  553. PNG_ITXT_COMPRESSION_NONE
  554. PNG_ITXT_COMPRESSION_zTXt
  555. text_ptr[i].key - keyword for comment. Must contain
  556. 1-79 characters.
  557. text_ptr[i].text - text comments for current
  558. keyword. Can be empty.
  559. text_ptr[i].text_length - length of text string,
  560. after decompression, 0 for iTXt
  561. text_ptr[i].itxt_length - length of itxt string,
  562. after decompression, 0 for tEXt/zTXt
  563. text_ptr[i].lang - language of comment (empty
  564. string for unknown).
  565. text_ptr[i].lang_key - keyword in UTF-8
  566. (empty string for unknown).
  567. Note that the itxt_length, lang, and lang_key
  568. members of the text_ptr structure only exist
  569. when the library is built with iTXt chunk support.
  570. num_text - number of comments (same as
  571. num_comments; you can put NULL here
  572. to avoid the duplication)
  573. Note while png_set_text() will accept text, language,
  574. and translated keywords that can be NULL pointers, the
  575. structure returned by png_get_text will always contain
  576. regular zero-terminated C strings. They might be
  577. empty strings but they will never be NULL pointers.
  578. num_spalettes = png_get_sPLT(png_ptr, info_ptr,
  579. &palette_ptr);
  580. palette_ptr - array of palette structures holding
  581. contents of one or more sPLT chunks
  582. read.
  583. num_spalettes - number of sPLT chunks read.
  584. png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
  585. &unit_type);
  586. offset_x - positive offset from the left edge
  587. of the screen
  588. offset_y - positive offset from the top edge
  589. of the screen
  590. unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
  591. png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
  592. &unit_type);
  593. res_x - pixels/unit physical resolution in
  594. x direction
  595. res_y - pixels/unit physical resolution in
  596. x direction
  597. unit_type - PNG_RESOLUTION_UNKNOWN,
  598. PNG_RESOLUTION_METER
  599. png_get_sCAL(png_ptr, info_ptr, &unit, &width,
  600. &height)
  601. unit - physical scale units (an integer)
  602. width - width of a pixel in physical scale units
  603. height - height of a pixel in physical scale units
  604. (width and height are doubles)
  605. png_get_sCAL_s(png_ptr, info_ptr, &unit, &width,
  606. &height)
  607. unit - physical scale units (an integer)
  608. width - width of a pixel in physical scale units
  609. height - height of a pixel in physical scale units
  610. (width and height are strings like "2.54")
  611. num_unknown_chunks = png_get_unknown_chunks(png_ptr,
  612. info_ptr, &unknowns)
  613. unknowns - array of png_unknown_chunk
  614. structures holding unknown chunks
  615. unknowns[i].name - name of unknown chunk
  616. unknowns[i].data - data of unknown chunk
  617. unknowns[i].size - size of unknown chunk's data
  618. unknowns[i].location - position of chunk in file
  619. The value of "i" corresponds to the order in which the
  620. chunks were read from the PNG file or inserted with the
  621. png_set_unknown_chunks() function.
  622. The data from the pHYs chunk can be retrieved in several convenient
  623. forms:
  624. res_x = png_get_x_pixels_per_meter(png_ptr,
  625. info_ptr)
  626. res_y = png_get_y_pixels_per_meter(png_ptr,
  627. info_ptr)
  628. res_x_and_y = png_get_pixels_per_meter(png_ptr,
  629. info_ptr)
  630. res_x = png_get_x_pixels_per_inch(png_ptr,
  631. info_ptr)
  632. res_y = png_get_y_pixels_per_inch(png_ptr,
  633. info_ptr)
  634. res_x_and_y = png_get_pixels_per_inch(png_ptr,
  635. info_ptr)
  636. aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
  637. info_ptr)
  638. (Each of these returns 0 [signifying "unknown"] if
  639. the data is not present or if res_x is 0;
  640. res_x_and_y is 0 if res_x != res_y)
  641. The data from the oFFs chunk can be retrieved in several convenient
  642. forms:
  643. x_offset = png_get_x_offset_microns(png_ptr, info_ptr);
  644. y_offset = png_get_y_offset_microns(png_ptr, info_ptr);
  645. x_offset = png_get_x_offset_inches(png_ptr, info_ptr);
  646. y_offset = png_get_y_offset_inches(png_ptr, info_ptr);
  647. (Each of these returns 0 [signifying "unknown" if both
  648. x and y are 0] if the data is not present or if the
  649. chunk is present but the unit is the pixel)
  650. For more information, see the png_info definition in png.h and the
  651. PNG specification for chunk contents. Be careful with trusting
  652. rowbytes, as some of the transformations could increase the space
  653. needed to hold a row (expand, filler, gray_to_rgb, etc.).
  654. See png_read_update_info(), below.
  655. A quick word about text_ptr and num_text. PNG stores comments in
  656. keyword/text pairs, one pair per chunk, with no limit on the number
  657. of text chunks, and a 2^31 byte limit on their size. While there are
  658. suggested keywords, there is no requirement to restrict the use to these
  659. strings. It is strongly suggested that keywords and text be sensible
  660. to humans (that's the point), so don't use abbreviations. Non-printing
  661. symbols are not allowed. See the PNG specification for more details.
  662. There is also no requirement to have text after the keyword.
  663. Keywords should be limited to 79 Latin-1 characters without leading or
  664. trailing spaces, but non-consecutive spaces are allowed within the
  665. keyword. It is possible to have the same keyword any number of times.
  666. The text_ptr is an array of png_text structures, each holding a
  667. pointer to a language string, a pointer to a keyword and a pointer to
  668. a text string. The text string, language code, and translated
  669. keyword may be empty or NULL pointers. The keyword/text
  670. pairs are put into the array in the order that they are received.
  671. However, some or all of the text chunks may be after the image, so, to
  672. make sure you have read all the text chunks, don't mess with these
  673. until after you read the stuff after the image. This will be
  674. mentioned again below in the discussion that goes with png_read_end().
  675. Input transformations
  676. After you've read the header information, you can set up the library
  677. to handle any special transformations of the image data. The various
  678. ways to transform the data will be described in the order that they
  679. should occur. This is important, as some of these change the color
  680. type and/or bit depth of the data, and some others only work on
  681. certain color types and bit depths. Even though each transformation
  682. checks to see if it has data that it can do something with, you should
  683. make sure to only enable a transformation if it will be valid for the
  684. data. For example, don't swap red and blue on grayscale data.
  685. The colors used for the background and transparency values should be
  686. supplied in the same format/depth as the current image data. They
  687. are stored in the same format/depth as the image data in a bKGD or tRNS
  688. chunk, so this is what libpng expects for this data. The colors are
  689. transformed to keep in sync with the image data when an application
  690. calls the png_read_update_info() routine (see below).
  691. Data will be decoded into the supplied row buffers packed into bytes
  692. unless the library has been told to transform it into another format.
  693. For example, 4 bit/pixel paletted or grayscale data will be returned
  694. 2 pixels/byte with the leftmost pixel in the high-order bits of the
  695. byte, unless png_set_packing() is called. 8-bit RGB data will be stored
  696. in RGB RGB RGB format unless png_set_filler() or png_set_add_alpha()
  697. is called to insert filler bytes, either before or after each RGB triplet.
  698. 16-bit RGB data will be returned RRGGBB RRGGBB, with the most significant
  699. byte of the color value first, unless png_set_strip_16() is called to
  700. transform it to regular RGB RGB triplets, or png_set_filler() or
  701. png_set_add alpha() is called to insert filler bytes, either before or
  702. after each RRGGBB triplet. Similarly, 8-bit or 16-bit grayscale data can
  703. be modified with
  704. png_set_filler(), png_set_add_alpha(), or png_set_strip_16().
  705. The following code transforms grayscale images of less than 8 to 8 bits,
  706. changes paletted images to RGB, and adds a full alpha channel if there is
  707. transparency information in a tRNS chunk. This is most useful on
  708. grayscale images with bit depths of 2 or 4 or if there is a multiple-image
  709. viewing application that wishes to treat all images in the same way.
  710. if (color_type == PNG_COLOR_TYPE_PALETTE)
  711. png_set_palette_to_rgb(png_ptr);
  712. if (color_type == PNG_COLOR_TYPE_GRAY &&
  713. bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png_ptr);
  714. if (png_get_valid(png_ptr, info_ptr,
  715. PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
  716. These three functions are actually aliases for png_set_expand(), added
  717. in libpng version 1.0.4, with the function names expanded to improve code
  718. readability. In some future version they may actually do different
  719. things.
  720. As of libpng version 1.2.9, png_set_expand_gray_1_2_4_to_8() was
  721. added. It expands the sample depth without changing tRNS to alpha.
  722. As of libpng version 1.2.41, not all possible expansions are supported.
  723. In the following table, the 01 means grayscale with depth<8, 31 means
  724. indexed with depth<8, other numerals represent the color type, "T" means
  725. the tRNS chunk is present, A means an alpha channel is present, and O
  726. means tRNS or alpha is present but all pixels in the image are opaque.
  727. FROM 01 31 0 0T 0O 2 2T 2O 3 3T 3O 4A 4O 6A 6O
  728. TO
  729. 01 -
  730. 31 -
  731. 0 1 -
  732. 0T -
  733. 0O -
  734. 2 GX -
  735. 2T -
  736. 2O -
  737. 3 1 -
  738. 3T -
  739. 3O -
  740. 4A T -
  741. 4O -
  742. 6A GX TX TX -
  743. 6O GX TX -
  744. Within the matrix,
  745. "-" means the transformation is not supported.
  746. "X" means the transformation is obtained by png_set_expand().
  747. "1" means the transformation is obtained by
  748. png_set_expand_gray_1_2_4_to_8
  749. "G" means the transformation is obtained by
  750. png_set_gray_to_rgb().
  751. "P" means the transformation is obtained by
  752. png_set_expand_palette_to_rgb().
  753. "T" means the transformation is obtained by
  754. png_set_tRNS_to_alpha().
  755. PNG can have files with 16 bits per channel. If you only can handle
  756. 8 bits per channel, this will strip the pixels down to 8 bit.
  757. if (bit_depth == 16)
  758. png_set_strip_16(png_ptr);
  759. If, for some reason, you don't need the alpha channel on an image,
  760. and you want to remove it rather than combining it with the background
  761. (but the image author certainly had in mind that you *would* combine
  762. it with the background, so that's what you should probably do):
  763. if (color_type & PNG_COLOR_MASK_ALPHA)
  764. png_set_strip_alpha(png_ptr);
  765. In PNG files, the alpha channel in an image
  766. is the level of opacity. If you need the alpha channel in an image to
  767. be the level of transparency instead of opacity, you can invert the
  768. alpha channel (or the tRNS chunk data) after it's read, so that 0 is
  769. fully opaque and 255 (in 8-bit or paletted images) or 65535 (in 16-bit
  770. images) is fully transparent, with
  771. png_set_invert_alpha(png_ptr);
  772. The PNG format only supports pixels with postmultiplied alpha.
  773. If you want to replace the pixels, after reading them, with pixels
  774. that have premultiplied color samples, you can do this with
  775. png_set_premultiply_alpha(png_ptr);
  776. If you do this, any input with a tRNS chunk will be expanded to
  777. have an alpha channel.
  778. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  779. they can, resulting in, for example, 8 pixels per byte for 1 bit
  780. files. This code expands to 1 pixel per byte without changing the
  781. values of the pixels:
  782. if (bit_depth < 8)
  783. png_set_packing(png_ptr);
  784. PNG files have possible bit depths of 1, 2, 4, 8, and 16. All pixels
  785. stored in a PNG image have been "scaled" or "shifted" up to the next
  786. higher possible bit depth (e.g. from 5 bits/sample in the range [0,31]
  787. to 8 bits/sample in the range [0, 255]). However, it is also possible
  788. to convert the PNG pixel data back to the original bit depth of the
  789. image. This call reduces the pixels back down to the original bit depth:
  790. png_color_8p sig_bit;
  791. if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
  792. png_set_shift(png_ptr, sig_bit);
  793. PNG files store 3-color pixels in red, green, blue order. This code
  794. changes the storage of the pixels to blue, green, red:
  795. if (color_type == PNG_COLOR_TYPE_RGB ||
  796. color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  797. png_set_bgr(png_ptr);
  798. PNG files store RGB pixels packed into 3 or 6 bytes. This code expands them
  799. into 4 or 8 bytes for windowing systems that need them in this format:
  800. if (color_type == PNG_COLOR_TYPE_RGB)
  801. png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
  802. where "filler" is the 8 or 16-bit number to fill with, and the location is
  803. either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
  804. you want the filler before the RGB or after. This transformation
  805. does not affect images that already have full alpha channels. To add an
  806. opaque alpha channel, use filler=0xff or 0xffff and PNG_FILLER_AFTER which
  807. will generate RGBA pixels.
  808. Note that png_set_filler() does not change the color type. If you want
  809. to do that, you can add a true alpha channel with
  810. if (color_type == PNG_COLOR_TYPE_RGB ||
  811. color_type == PNG_COLOR_TYPE_GRAY)
  812. png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER);
  813. where "filler" contains the alpha value to assign to each pixel.
  814. This function was added in libpng-1.2.7.
  815. If you are reading an image with an alpha channel, and you need the
  816. data as ARGB instead of the normal PNG format RGBA:
  817. if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  818. png_set_swap_alpha(png_ptr);
  819. For some uses, you may want a grayscale image to be represented as
  820. RGB. This code will do that conversion:
  821. if (color_type == PNG_COLOR_TYPE_GRAY ||
  822. color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  823. png_set_gray_to_rgb(png_ptr);
  824. Conversely, you can convert an RGB or RGBA image to grayscale or grayscale
  825. with alpha.
  826. if (color_type == PNG_COLOR_TYPE_RGB ||
  827. color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  828. png_set_rgb_to_gray_fixed(png_ptr, error_action,
  829. int red_weight, int green_weight);
  830. error_action = 1: silently do the conversion
  831. error_action = 2: issue a warning if the original
  832. image has any pixel where
  833. red != green or red != blue
  834. error_action = 3: issue an error and abort the
  835. conversion if the original
  836. image has any pixel where
  837. red != green or red != blue
  838. red_weight: weight of red component times 100000
  839. green_weight: weight of green component times 100000
  840. If either weight is negative, default
  841. weights (21268, 71514) are used.
  842. If you have set error_action = 1 or 2, you can
  843. later check whether the image really was gray, after processing
  844. the image rows, with the png_get_rgb_to_gray_status(png_ptr) function.
  845. It will return a png_byte that is zero if the image was gray or
  846. 1 if there were any non-gray pixels. bKGD and sBIT data
  847. will be silently converted to grayscale, using the green channel
  848. data, regardless of the error_action setting.
  849. With red_weight+green_weight<=100000,
  850. the normalized graylevel is computed:
  851. int rw = red_weight * 65536;
  852. int gw = green_weight * 65536;
  853. int bw = 65536 - (rw + gw);
  854. gray = (rw*red + gw*green + bw*blue)/65536;
  855. The default values approximate those recommended in the Charles
  856. Poynton's Color FAQ, <http://www.inforamp.net/~poynton/>
  857. Copyright (c) 1998-01-04 Charles Poynton <poynton at inforamp.net>
  858. Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  859. Libpng approximates this with
  860. Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  861. which can be expressed with integers as
  862. Y = (6969 * R + 23434 * G + 2365 * B)/32768
  863. The calculation is done in a linear colorspace, if the image gamma
  864. is known.
  865. If you have a grayscale and you are using png_set_expand_depth(),
  866. png_set_expand(), or png_set_gray_to_rgb to change to truecolor or to
  867. a higher bit-depth, you must either supply the background color as a gray
  868. value at the original file bit-depth (need_expand = 1) or else supply the
  869. background color as an RGB triplet at the final, expanded bit depth
  870. (need_expand = 0). Similarly, if you are reading a paletted image, you
  871. must either supply the background color as a palette index (need_expand = 1)
  872. or as an RGB triplet that may or may not be in the palette (need_expand = 0).
  873. png_color_16 my_background;
  874. png_color_16p image_background;
  875. if (png_get_bKGD(png_ptr, info_ptr, &image_background))
  876. png_set_background(png_ptr, image_background,
  877. PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
  878. else
  879. png_set_background(png_ptr, &my_background,
  880. PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
  881. The png_set_background() function tells libpng to composite images
  882. with alpha or simple transparency against the supplied background
  883. color. If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
  884. you may use this color, or supply another color more suitable for
  885. the current display (e.g., the background color from a web page). You
  886. need to tell libpng whether the color is in the gamma space of the
  887. display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
  888. (PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
  889. that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
  890. know why anyone would use this, but it's here).
  891. To properly display PNG images on any kind of system, the application needs
  892. to know what the display gamma is. Ideally, the user will know this, and
  893. the application will allow them to set it. One method of allowing the user
  894. to set the display gamma separately for each system is to check for a
  895. SCREEN_GAMMA or DISPLAY_GAMMA environment variable, which will hopefully be
  896. correctly set.
  897. Note that display_gamma is the overall gamma correction required to produce
  898. pleasing results, which depends on the lighting conditions in the surrounding
  899. environment. In a dim or brightly lit room, no compensation other than
  900. the physical gamma exponent of the monitor is needed, while in a dark room
  901. a slightly smaller exponent is better.
  902. double gamma, screen_gamma;
  903. if (/* We have a user-defined screen
  904. gamma value */)
  905. {
  906. screen_gamma = user_defined_screen_gamma;
  907. }
  908. /* One way that applications can share the same
  909. screen gamma value */
  910. else if ((gamma_str = getenv("SCREEN_GAMMA"))
  911. != NULL)
  912. {
  913. screen_gamma = (double)atof(gamma_str);
  914. }
  915. /* If we don't have another value */
  916. else
  917. {
  918. screen_gamma = 2.2; /* A good guess for a
  919. PC monitor in a bright office or a dim room */
  920. screen_gamma = 2.0; /* A good guess for a
  921. PC monitor in a dark room */
  922. screen_gamma = 1.7 or 1.0; /* A good
  923. guess for Mac systems */
  924. }
  925. The png_set_gamma() function handles gamma transformations of the data.
  926. Pass both the file gamma and the current screen_gamma. If the file does
  927. not have a gamma value, you can pass one anyway if you have an idea what
  928. it is (usually 0.45455 is a good guess for GIF images on PCs). Note
  929. that file gammas are inverted from screen gammas. See the discussions
  930. on gamma in the PNG specification for an excellent description of what
  931. gamma is, and why all applications should support it. It is strongly
  932. recommended that PNG viewers support gamma correction.
  933. if (png_get_gAMA(png_ptr, info_ptr, &gamma))
  934. png_set_gamma(png_ptr, screen_gamma, gamma);
  935. else
  936. png_set_gamma(png_ptr, screen_gamma, 0.45455);
  937. If you need to reduce an RGB file to a paletted file, or if a paletted
  938. file has more entries then will fit on your screen, png_set_dither()
  939. will do that. Note that this is a simple match dither that merely
  940. finds the closest color available. This should work fairly well with
  941. optimized palettes, and fairly badly with linear color cubes. If you
  942. pass a palette that is larger then maximum_colors, the file will
  943. reduce the number of colors in the palette so it will fit into
  944. maximum_colors. If there is a histogram, it will use it to make
  945. more intelligent choices when reducing the palette. If there is no
  946. histogram, it may not do as good a job.
  947. if (color_type & PNG_COLOR_MASK_COLOR)
  948. {
  949. if (png_get_valid(png_ptr, info_ptr,
  950. PNG_INFO_PLTE))
  951. {
  952. png_uint_16p histogram = NULL;
  953. png_get_hIST(png_ptr, info_ptr,
  954. &histogram);
  955. png_set_dither(png_ptr, palette, num_palette,
  956. max_screen_colors, histogram, 1);
  957. }
  958. else
  959. {
  960. png_color std_color_cube[MAX_SCREEN_COLORS] =
  961. { ... colors ... };
  962. png_set_dither(png_ptr, std_color_cube,
  963. MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
  964. NULL,0);
  965. }
  966. }
  967. PNG files describe monochrome as black being zero and white being one.
  968. The following code will reverse this (make black be one and white be
  969. zero):
  970. if (bit_depth == 1 && color_type == PNG_COLOR_TYPE_GRAY)
  971. png_set_invert_mono(png_ptr);
  972. This function can also be used to invert grayscale and gray-alpha images:
  973. if (color_type == PNG_COLOR_TYPE_GRAY ||
  974. color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  975. png_set_invert_mono(png_ptr);
  976. PNG files store 16 bit pixels in network byte order (big-endian,
  977. ie. most significant bits first). This code changes the storage to the
  978. other way (little-endian, i.e. least significant bits first, the
  979. way PCs store them):
  980. if (bit_depth == 16)
  981. png_set_swap(png_ptr);
  982. If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
  983. need to change the order the pixels are packed into bytes, you can use:
  984. if (bit_depth < 8)
  985. png_set_packswap(png_ptr);
  986. Finally, you can write your own transformation function if none of
  987. the existing ones meets your needs. This is done by setting a callback
  988. with
  989. png_set_read_user_transform_fn(png_ptr,
  990. read_transform_fn);
  991. You must supply the function
  992. void read_transform_fn(png_ptr ptr, row_info_ptr
  993. row_info, png_bytep data)
  994. See pngtest.c for a working example. Your function will be called
  995. after all of the other transformations have been processed.
  996. You can also set up a pointer to a user structure for use by your
  997. callback function, and you can inform libpng that your transform
  998. function will change the number of channels or bit depth with the
  999. function
  1000. png_set_user_transform_info(png_ptr, user_ptr,
  1001. user_depth, user_channels);
  1002. The user's application, not libpng, is responsible for allocating and
  1003. freeing any memory required for the user structure.
  1004. You can retrieve the pointer via the function
  1005. png_get_user_transform_ptr(). For example:
  1006. voidp read_user_transform_ptr =
  1007. png_get_user_transform_ptr(png_ptr);
  1008. The last thing to handle is interlacing; this is covered in detail below,
  1009. but you must call the function here if you want libpng to handle expansion
  1010. of the interlaced image.
  1011. number_of_passes = png_set_interlace_handling(png_ptr);
  1012. After setting the transformations, libpng can update your png_info
  1013. structure to reflect any transformations you've requested with this
  1014. call. This is most useful to update the info structure's rowbytes
  1015. field so you can use it to allocate your image memory. This function
  1016. will also update your palette with the correct screen_gamma and
  1017. background if these have been given with the calls above.
  1018. png_read_update_info(png_ptr, info_ptr);
  1019. After you call png_read_update_info(), you can allocate any
  1020. memory you need to hold the image. The row data is simply
  1021. raw byte data for all forms of images. As the actual allocation
  1022. varies among applications, no example will be given. If you
  1023. are allocating one large chunk, you will need to build an
  1024. array of pointers to each row, as it will be needed for some
  1025. of the functions below.
  1026. Reading image data
  1027. After you've allocated memory, you can read the image data.
  1028. The simplest way to do this is in one function call. If you are
  1029. allocating enough memory to hold the whole image, you can just
  1030. call png_read_image() and libpng will read in all the image data
  1031. and put it in the memory area supplied. You will need to pass in
  1032. an array of pointers to each row.
  1033. This function automatically handles interlacing, so you don't need
  1034. to call png_set_interlace_handling() or call this function multiple
  1035. times, or any of that other stuff necessary with png_read_rows().
  1036. png_read_image(png_ptr, row_pointers);
  1037. where row_pointers is:
  1038. png_bytep row_pointers[height];
  1039. You can point to void or char or whatever you use for pixels.
  1040. If you don't want to read in the whole image at once, you can
  1041. use png_read_rows() instead. If there is no interlacing (check
  1042. interlace_type == PNG_INTERLACE_NONE), this is simple:
  1043. png_read_rows(png_ptr, row_pointers, NULL,
  1044. number_of_rows);
  1045. where row_pointers is the same as in the png_read_image() call.
  1046. If you are doing this just one row at a time, you can do this with
  1047. a single row_pointer instead of an array of row_pointers:
  1048. png_bytep row_pointer = row;
  1049. png_read_row(png_ptr, row_pointer, NULL);
  1050. If the file is interlaced (interlace_type != 0 in the IHDR chunk), things
  1051. get somewhat harder. The only current (PNG Specification version 1.2)
  1052. interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7)
  1053. is a somewhat complicated 2D interlace scheme, known as Adam7, that
  1054. breaks down an image into seven smaller images of varying size, based
  1055. on an 8x8 grid.
  1056. libpng can fill out those images or it can give them to you "as is".
  1057. If you want them filled out, there are two ways to do that. The one
  1058. mentioned in the PNG specification is to expand each pixel to cover
  1059. those pixels that have not been read yet (the "rectangle" method).
  1060. This results in a blocky image for the first pass, which gradually
  1061. smooths out as more pixels are read. The other method is the "sparkle"
  1062. method, where pixels are drawn only in their final locations, with the
  1063. rest of the image remaining whatever colors they were initialized to
  1064. before the start of the read. The first method usually looks better,
  1065. but tends to be slower, as there are more pixels to put in the rows.
  1066. If you don't want libpng to handle the interlacing details, just call
  1067. png_read_rows() seven times to read in all seven images. Each of the
  1068. images is a valid image by itself, or they can all be combined on an
  1069. 8x8 grid to form a single image (although if you intend to combine them
  1070. you would be far better off using the libpng interlace handling).
  1071. The first pass will return an image 1/8 as wide as the entire image
  1072. (every 8th column starting in column 0) and 1/8 as high as the original
  1073. (every 8th row starting in row 0), the second will be 1/8 as wide
  1074. (starting in column 4) and 1/8 as high (also starting in row 0). The
  1075. third pass will be 1/4 as wide (every 4th pixel starting in column 0) and
  1076. 1/8 as high (every 8th row starting in row 4), and the fourth pass will
  1077. be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
  1078. and every 4th row starting in row 0). The fifth pass will return an
  1079. image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
  1080. while the sixth pass will be 1/2 as wide and 1/2 as high as the original
  1081. (starting in column 1 and row 0). The seventh and final pass will be as
  1082. wide as the original, and 1/2 as high, containing all of the odd
  1083. numbered scanlines. Phew!
  1084. If you want libpng to expand the images, call this before calling
  1085. png_start_read_image() or png_read_update_info():
  1086. if (interlace_type == PNG_INTERLACE_ADAM7)
  1087. number_of_passes
  1088. = png_set_interlace_handling(png_ptr);
  1089. This will return the number of passes needed. Currently, this
  1090. is seven, but may change if another interlace type is added.
  1091. This function can be called even if the file is not interlaced,
  1092. where it will return one pass.
  1093. If you are not going to display the image after each pass, but are
  1094. going to wait until the entire image is read in, use the sparkle
  1095. effect. This effect is faster and the end result of either method
  1096. is exactly the same. If you are planning on displaying the image
  1097. after each pass, the "rectangle" effect is generally considered the
  1098. better looking one.
  1099. If you only want the "sparkle" effect, just call png_read_rows() as
  1100. normal, with the third parameter NULL. Make sure you make pass over
  1101. the image number_of_passes times, and you don't change the data in the
  1102. rows between calls. You can change the locations of the data, just
  1103. not the data. Each pass only writes the pixels appropriate for that
  1104. pass, and assumes the data from previous passes is still valid.
  1105. png_read_rows(png_ptr, row_pointers, NULL,
  1106. number_of_rows);
  1107. If you only want the first effect (the rectangles), do the same as
  1108. before except pass the row buffer in the third parameter, and leave
  1109. the second parameter NULL.
  1110. png_read_rows(png_ptr, NULL, row_pointers,
  1111. number_of_rows);
  1112. Finishing a sequential read
  1113. After you are finished reading the image through the
  1114. low-level interface, you can finish reading the file. If you are
  1115. interested in comments or time, which may be stored either before or
  1116. after the image data, you should pass the separate png_info struct if
  1117. you want to keep the comments from before and after the image
  1118. separate. If you are not interested, you can pass NULL.
  1119. png_read_end(png_ptr, end_info);
  1120. When you are done, you can free all memory allocated by libpng like this:
  1121. png_destroy_read_struct(&png_ptr, &info_ptr,
  1122. &end_info);
  1123. It is also possible to individually free the info_ptr members that
  1124. point to libpng-allocated storage with the following function:
  1125. png_free_data(png_ptr, info_ptr, mask, seq)
  1126. mask - identifies data to be freed, a mask
  1127. containing the bitwise OR of one or
  1128. more of
  1129. PNG_FREE_PLTE, PNG_FREE_TRNS,
  1130. PNG_FREE_HIST, PNG_FREE_ICCP,
  1131. PNG_FREE_PCAL, PNG_FREE_ROWS,
  1132. PNG_FREE_SCAL, PNG_FREE_SPLT,
  1133. PNG_FREE_TEXT, PNG_FREE_UNKN,
  1134. or simply PNG_FREE_ALL
  1135. seq - sequence number of item to be freed
  1136. (-1 for all items)
  1137. This function may be safely called when the relevant storage has
  1138. already been freed, or has not yet been allocated, or was allocated
  1139. by the user and not by libpng, and will in those cases do nothing.
  1140. The "seq" parameter is ignored if only one item of the selected data
  1141. type, such as PLTE, is allowed. If "seq" is not -1, and multiple items
  1142. are allowed for the data type identified in the mask, such as text or
  1143. sPLT, only the n'th item in the structure is freed, where n is "seq".
  1144. The default behavior is only to free data that was allocated internally
  1145. by libpng. This can be changed, so that libpng will not free the data,
  1146. or so that it will free data that was allocated by the user with png_malloc()
  1147. or png_zalloc() and passed in via a png_set_*() function, with
  1148. png_data_freer(png_ptr, info_ptr, freer, mask)
  1149. mask - which data elements are affected
  1150. same choices as in png_free_data()
  1151. freer - one of
  1152. PNG_DESTROY_WILL_FREE_DATA
  1153. PNG_SET_WILL_FREE_DATA
  1154. PNG_USER_WILL_FREE_DATA
  1155. This function only affects data that has already been allocated.
  1156. You can call this function after reading the PNG data but before calling
  1157. any png_set_*() functions, to control whether the user or the png_set_*()
  1158. function is responsible for freeing any existing data that might be present,
  1159. and again after the png_set_*() functions to control whether the user
  1160. or png_destroy_*() is supposed to free the data. When the user assumes
  1161. responsibility for libpng-allocated data, the application must use
  1162. png_free() to free it, and when the user transfers responsibility to libpng
  1163. for data that the user has allocated, the user must have used png_malloc()
  1164. or png_zalloc() to allocate it.
  1165. If you allocated your row_pointers in a single block, as suggested above in
  1166. the description of the high level read interface, you must not transfer
  1167. responsibility for freeing it to the png_set_rows or png_read_destroy function,
  1168. because they would also try to free the individual row_pointers[i].
  1169. If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
  1170. separately, do not transfer responsibility for freeing text_ptr to libpng,
  1171. because when libpng fills a png_text structure it combines these members with
  1172. the key member, and png_free_data() will free only text_ptr.key. Similarly,
  1173. if you transfer responsibility for free'ing text_ptr from libpng to your
  1174. application, your application must not separately free those members.
  1175. The png_free_data() function will turn off the "valid" flag for anything
  1176. it frees. If you need to turn the flag off for a chunk that was freed by
  1177. your application instead of by libpng, you can use
  1178. png_set_invalid(png_ptr, info_ptr, mask);
  1179. mask - identifies the chunks to be made invalid,
  1180. containing the bitwise OR of one or
  1181. more of
  1182. PNG_INFO_gAMA, PNG_INFO_sBIT,
  1183. PNG_INFO_cHRM, PNG_INFO_PLTE,
  1184. PNG_INFO_tRNS, PNG_INFO_bKGD,
  1185. PNG_INFO_hIST, PNG_INFO_pHYs,
  1186. PNG_INFO_oFFs, PNG_INFO_tIME,
  1187. PNG_INFO_pCAL, PNG_INFO_sRGB,
  1188. PNG_INFO_iCCP, PNG_INFO_sPLT,
  1189. PNG_INFO_sCAL, PNG_INFO_IDAT
  1190. For a more compact example of reading a PNG image, see the file example.c.
  1191. Reading PNG files progressively
  1192. The progressive reader is slightly different then the non-progressive
  1193. reader. Instead of calling png_read_info(), png_read_rows(), and
  1194. png_read_end(), you make one call to png_process_data(), which calls
  1195. callbacks when it has the info, a row, or the end of the image. You
  1196. set up these callbacks with png_set_progressive_read_fn(). You don't
  1197. have to worry about the input/output functions of libpng, as you are
  1198. giving the library the data directly in png_process_data(). I will
  1199. assume that you have read the section on reading PNG files above,
  1200. so I will only highlight the differences (although I will show
  1201. all of the code).
  1202. png_structp png_ptr;
  1203. png_infop info_ptr;
  1204. /* An example code fragment of how you would
  1205. initialize the progressive reader in your
  1206. application. */
  1207. int
  1208. initialize_png_reader()
  1209. {
  1210. png_ptr = png_create_read_struct
  1211. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  1212. user_error_fn, user_warning_fn);
  1213. if (!png_ptr)
  1214. return (ERROR);
  1215. info_ptr = png_create_info_struct(png_ptr);
  1216. if (!info_ptr)
  1217. {
  1218. png_destroy_read_struct(&png_ptr, (png_infopp)NULL,
  1219. (png_infopp)NULL);
  1220. return (ERROR);
  1221. }
  1222. if (setjmp(png_jmpbuf(png_ptr)))
  1223. {
  1224. png_destroy_read_struct(&png_ptr, &info_ptr,
  1225. (png_infopp)NULL);
  1226. return (ERROR);
  1227. }