libpng.txt 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  1. libpng.txt - a description on how to use and modify libpng
  2. libpng version 0.99b
  3. Updated and distributed by Glenn Randers-Pehrson <randeg@alumni.rpi.edu>
  4. Copyright (c) 1998, Glenn Randers-Pehrson
  5. February 3, 1998
  6. based on:
  7. libpng 1.0 beta 6 version 0.96
  8. Updated and distributed by Andreas Dilger
  9. Copyright (c) 1996, 1997 Andreas Dilger
  10. May 28, 1997
  11. libpng 1.0 beta 2 - version 0.88
  12. For conditions of distribution and use, see copyright notice in png.h
  13. Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  14. January 26, 1996
  15. Updated/rewritten per request in the libpng FAQ
  16. Copyright (c) 1995 Frank J. T. Wojcik
  17. December 18, 1995 && January 20, 1996
  18. I. Introduction
  19. This file describes how to use and modify the PNG reference library
  20. (known as libpng) for your own use. There are five sections to this
  21. file: introduction, structures, reading, writing, and modification and
  22. configuration notes for various special platforms. In addition to this
  23. file, example.c is a good starting point for using the library, as
  24. it is heavily commented and should include everything most people
  25. will need.
  26. Libpng was written as a companion to the PNG specification, as a way
  27. of reducing the amount of time and effort it takes to support the PNG
  28. file format in application programs. The PNG specification is available
  29. as RFC 2083 <ftp://ftp.uu.net/graphics/png/documents/> and as a
  30. W3C Recommendation <http://www.w3.org/pub/WWW/TR/REC.png.html>. Some
  31. additional chunks are described in the special-purpose public chunks
  32. documents at <ftp://ftp.uu.net/graphics/png/documents/>. Other information
  33. about PNG can be found at the PNG home page, <http://www.cdrom.com/pub/png/>.
  34. Most users will not have to modify the library significantly; advanced
  35. users may want to modify it more. All attempts were made to make it as
  36. complete as possible, while keeping the code easy to understand.
  37. Currently, this library only supports C. Support for other languages
  38. is being considered.
  39. Libpng has been designed to handle multiple sessions at one time,
  40. to be easily modifiable, to be portable to the vast majority of
  41. machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
  42. to use. The ultimate goal of libpng is to promote the acceptance of
  43. the PNG file format in whatever way possible. While there is still
  44. work to be done (see the TODO file), libpng should cover the
  45. majority of the needs of its users.
  46. Libpng uses zlib for its compression and decompression of PNG files.
  47. The zlib compression utility is a general purpose utility that is
  48. useful for more than PNG files, and can be used without libpng.
  49. See the documentation delivered with zlib for more details.
  50. You can usually find the source files for the zlib utility wherever you
  51. find the libpng source files.
  52. Libpng is thread safe, provided the threads are using different
  53. instances of the structures. Each thread should have its own
  54. png_struct and png_info instances, and thus its own image.
  55. Libpng does not protect itself against two threads using the
  56. same instance of a structure.
  57. II. Structures
  58. There are two main structures that are important to libpng, png_struct
  59. and png_info. The first, png_struct, is an internal structure that
  60. will not, for the most part, be used by a user except as the first
  61. variable passed to every libpng function call. It is not actually
  62. used in many of the functions; do not be alarmed about compiler
  63. warnings that say something to the effect that "png_ptr is not used."
  64. The png_info structure is designed to provide information about the
  65. PNG file. At one time, the fields of png_info were intended to be
  66. directly accessible to the user. However, this tended to cause problems
  67. with applications using dynamically loaded libraries, and as a result
  68. a set of interface functions for png_info was developed. The fields
  69. of png_info are still available for older applications, but it is
  70. suggested that applications use the new interfaces if at all possible.
  71. The png.h header file is an invaluable reference for programming with libpng.
  72. And while I'm on the topic, make sure you include the libpng header file:
  73. #include <png.h>
  74. III. Reading
  75. Reading PNG files:
  76. We'll now walk you through the possible functions to call when reading
  77. in a PNG file, briefly explaining the syntax and purpose of each one.
  78. See example.c and png.h for more detail. While Progressive reading
  79. is covered in the next section, you will still need some of the
  80. functions discussed in this section to read a PNG file.
  81. You will want to do the I/O initialization(*) before you get into libpng,
  82. so if it doesn't work, you don't have much to undo. Of course, you
  83. will also want to insure that you are, in fact, dealing with a PNG
  84. file. Libpng provides a simple check to see if a file is a PNG file.
  85. To use it, pass in the first 1 to 8 bytes of the file, and it will
  86. return true or false (1 or 0) depending on whether the bytes could be
  87. part of a PNG file. Of course, the more bytes you pass in, the
  88. greater the accuracy of the prediction.
  89. If you are intending to keep the file pointer open for use in libpng,
  90. you must ensure you don't read more than 8 bytes from the beginning
  91. of the file, and you also have to make a call to png_set_sig_bytes_read()
  92. with the number of bytes you read from the beginning. Libpng will
  93. then only check the bytes (if any) that your program didn't read.
  94. (*): If you are not using the standard I/O functions, you will need
  95. to replace them with custom functions. See the discussion under
  96. Customizing libpng.
  97. FILE *fp = fopen(file_name, "rb");
  98. if (!fp)
  99. {
  100. return;
  101. }
  102. fread(header, 1, number, fp);
  103. is_png = png_check_sig(header, 0, number);
  104. if (!is_png)
  105. {
  106. return;
  107. }
  108. Next, png_struct and png_info need to be allocated and initialized. In
  109. order to ensure that the size of these structures is correct even with a
  110. dynamically linked libpng, there are functions to initialize and
  111. allocate the structures. We also pass the library version, optional
  112. pointers to error handling functions, and a pointer to a data struct for
  113. use by the error functions, if necessary (the pointer and functions can
  114. be NULL if the default error handlers are to be used). See the section
  115. on Changes to Libpng below regarding the old initialization functions.
  116. png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  117. (void *)user_error_ptr, user_error_fn, user_warning_fn);
  118. if (!png_ptr)
  119. return;
  120. png_infop info_ptr = png_create_info_struct(png_ptr);
  121. if (!info_ptr)
  122. {
  123. png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
  124. return;
  125. }
  126. png_infop end_info = png_create_info_struct(png_ptr);
  127. if (!end_info)
  128. {
  129. png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  130. return;
  131. }
  132. The error handling routines passed to png_create_read_struct() are only
  133. necessary if you are not using the libpng supplied error handling
  134. functions. When libpng encounters an error, it expects to longjmp back
  135. to your routine. Therefore, you will need to call setjmp and pass the
  136. jmpbuf field of your png_struct. If you read the file from different
  137. routines, you will need to update the jmpbuf field every time you enter
  138. a new routine that will call a png_ function.
  139. See your documentation of setjmp/longjmp for your compiler for more
  140. information on setjmp/longjmp. See the discussion on libpng error
  141. handling in the Customizing Libpng section below for more information on
  142. the libpng error handling. If an error occurs, and libpng longjmp's
  143. back to your setjmp, you will want to call png_destroy_read_struct() to
  144. free any memory.
  145. if (setjmp(png_ptr->jmpbuf))
  146. {
  147. png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  148. fclose(fp);
  149. return;
  150. }
  151. Now you need to set up the input code. The default for libpng is to
  152. use the C function fread(). If you use this, you will need to pass a
  153. valid FILE * in the function png_init_io(). Be sure that the file is
  154. opened in binary mode. If you wish to handle reading data in another
  155. way, you need not call the png_init_io() function, but you must then
  156. implement the libpng I/O methods discussed in the Customizing Libpng
  157. section below.
  158. png_init_io(png_ptr, fp);
  159. If you had previously opened the file and read any of the signature from
  160. the beginning in order to see if this was a PNG file, you need to let
  161. libpng know that there are some bytes missing from the start of the file.
  162. png_set_sig_bytes(png_ptr, number);
  163. In PNG files, the alpha channel in an image is the level of opacity.
  164. If you need the alpha channel in an image to be the level of transparency
  165. instead of opacity, you can invert the alpha channel (or the tRNS chunk
  166. data) after it's read, so that 0 is fully opaque and 255 (in 8-bit or
  167. paletted images) or 65535 (in 16-bit images) is fully transparent, with
  168. png_set_invert_alpha(png_ptr);
  169. This has to appear here rather than later with the other transformations
  170. because the tRNS chunk data must be modified in the case of paletted images.
  171. If your image is not a paletted image, the tRNS data (which in such cases
  172. represents a single color to be rendered as transparent) won't be changed.
  173. You are now ready to read all the file information up to the actual
  174. image data. You do this with a call to png_read_info().
  175. png_read_info(png_ptr, info_ptr);
  176. Functions are used to get the information from the info_ptr:
  177. png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
  178. &interlace_type, &compression_type, &filter_type);
  179. width - holds the width of the image in pixels (up to 2^31).
  180. height - holds the height of the image in pixels (up to 2^31).
  181. bit_depth - holds the bit depth of one of the image channels.
  182. (valid values are 1, 2, 4, 8, 16 and depend also on the
  183. color_type. See also significant bits (sBIT) below).
  184. color_type - describes which color/alpha channels are present.
  185. PNG_COLOR_TYPE_GRAY (bit depths 1, 2, 4, 8, 16)
  186. PNG_COLOR_TYPE_GRAY_ALPHA (bit depths 8, 16)
  187. PNG_COLOR_TYPE_PALETTE (bit depths 1, 2, 4, 8)
  188. PNG_COLOR_TYPE_RGB (bit_depths 8, 16)
  189. PNG_COLOR_TYPE_RGB_ALPHA (bit_depths 8, 16)
  190. PNG_COLOR_MASK_PALETTE
  191. PNG_COLOR_MASK_COLOR
  192. PNG_COLOR_MASK_ALPHA
  193. filter_type - (must be PNG_FILTER_TYPE_BASE for PNG 1.0)
  194. compression_type - (must be PNG_COMPRESSION_TYPE_BASE for PNG 1.0)
  195. interlace_type - (PNG_INTERLACE_TYPE_NONE or PNG_INTERLACE_TYPE_ADAM7)
  196. Any or all of interlace_type, compression_type, of filter_type can be
  197. NULL if you are not interested in their values.
  198. channels = png_get_channels(png_ptr, info_ptr);
  199. channels - number of channels of info for the color type
  200. (valid values are 1 (GRAY, PALETTE), 2 (GRAY_ALPHA),
  201. 3 (RGB), 4 (RGB_ALPHA or RGB + filler byte))
  202. rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  203. rowbytes - number of bytes needed to hold a row
  204. signature = png_get_signature(png_ptr, info_ptr);
  205. signature - holds the signature read from the file (if any). The
  206. data is kept in the same offset it would be if the
  207. whole signature were read (ie if an application had
  208. already read in 4 bytes of signature before staring
  209. libpng, the remaining 4 bytes would be in signature[4]
  210. through signature[7] (see png_set_sig_bytes())).
  211. Information from each if the IHDR fields can be retrieve separately as well:
  212. width = png_get_image_width(png_ptr, info_ptr);
  213. height = png_get_image_height(png_ptr, info_ptr);
  214. bit_depth = png_get_bit_depth(png_ptr, info_ptr);
  215. color_type = png_get_color_type(png_ptr, info_ptr);
  216. filter_type = png_get_filter_type(png_ptr, info_ptr);
  217. compression_type = png_get_compression_type(png_ptr, info_ptr);
  218. interlace_type = png_get_interlace_type(png_ptr, info_ptr);
  219. These are also important, but their validity depends on whether the chunk
  220. has been read. The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
  221. png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
  222. data has been read, or zero if it is missing. The parameters to the
  223. png_get_<chunk> are set directly if they are simple data types, or a pointer
  224. into the info_ptr is returned for any complex types.
  225. png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
  226. palette - the palette for the file (array of png_color)
  227. num_palette - number of entries in the palette
  228. png_get_gAMA(png_ptr, info_ptr, &gamma);
  229. gamma - the gamma the file is written at (PNG_INFO_gAMA)
  230. png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
  231. srgb_intent - the rendering intent (PNG_INFO_sRGB)
  232. The presence of the sRGB chunk means that the pixel
  233. data is in the sRGB color space. This chunk also
  234. implies specific values of gAMA and cHRM.
  235. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  236. sig_bit - the number of significant bits for (PNG_INFO_sBIT)
  237. the gray, red, green, and blue channels, whichever
  238. are appropriate for the given color type (png_color_16)
  239. png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &trans_values);
  240. trans - array of transparent entries for palette (PNG_INFO_tRNS)
  241. trans_values - transparent pixel for non-paletted images (PNG_INFO_tRNS)
  242. num_trans - number of transparent entries (PNG_INFO_tRNS)
  243. png_get_hIST(png_ptr, info_ptr, &hist); (PNG_INFO_hIST)
  244. hist - histogram of palette (array of png_color_16)
  245. png_get_tIME(png_ptr, info_ptr, &mod_time);
  246. mod_time - time image was last modified (PNG_VALID_tIME)
  247. png_get_bKGD(png_ptr, info_ptr, &background);
  248. background - background color (PNG_VALID_bKGD)
  249. num_text = png_get_text(png_ptr, info_ptr, &text_ptr);
  250. text_ptr - array of png_text holding image comments
  251. text_ptr[i]->key - keyword for comment.
  252. text_ptr[i]->text - text comments for current keyword.
  253. text_ptr[i]->compression - type of compression used on "text"
  254. PNG_TEXT_COMPRESSION_NONE or
  255. PNG_TEXT_COMPRESSION_zTXt
  256. num_text - number of comments
  257. png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y, &unit_type);
  258. offset_x - positive offset from the left edge of the screen
  259. offset_y - positive offset from the top edge of the screen
  260. unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
  261. png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y, &unit_type);
  262. res_x - pixels/unit physical resolution in x direction
  263. res_y - pixels/unit physical resolution in x direction
  264. unit_type - PNG_RESOLUTION_UNKOWN, PNG_RESOLUTION_METER
  265. The data from the pHYs chunk can be retrieved in several convenient
  266. forms:
  267. res_x_and_y = png_get_pixels_per_meter(png_ptr, info_ptr)
  268. aspect_ratio = png_get_pixel_aspect_ratio(png_ptr, info_ptr)
  269. (Each of these returns 0 [signifying "unknown"] if the data is not
  270. present or if res_x is 0; res_x_and_y is 0 if res_x != res_y)
  271. For more information, see the png_info definition in png.h and the
  272. PNG specification for chunk contents. Be careful with trusting
  273. rowbytes, as some of the transformations could increase the space
  274. needed to hold a row (expand, filler, gray_to_rgb, etc.).
  275. See png_read_update_info(), below.
  276. A quick word about text_ptr and num_text. PNG stores comments in
  277. keyword/text pairs, one pair per chunk, with no limit on the number
  278. of text chunks, and a 2^31 byte limit on their size. While there are
  279. suggested keywords, there is no requirement to restrict the use to these
  280. strings. It is strongly suggested that keywords and text be sensible
  281. to humans (that's the point), so don't use abbreviations. Non-printing
  282. symbols are not allowed. See the PNG specification for more details.
  283. There is also no requirement to have text after the keyword.
  284. Keywords should be limited to 79 Latin-1 characters without leading or
  285. trailing spaces, but non-consecutive spaces are allowed within the
  286. keyword. It is possible to have the same keyword any number of times.
  287. The text_ptr is an array of png_text structures, each holding pointer
  288. to a keyword and a pointer to a text string. Only the text string may
  289. be null. The keyword/text pairs are put into the array in the order
  290. that they are received. However, some or all of the text chunks may be
  291. after the image, so, to make sure you have read all the text chunks,
  292. don't mess with these until after you read the stuff after the image.
  293. This will be mentioned again below in the discussion that goes with
  294. png_read_end().
  295. After you've read the header information, you can set up the library
  296. to handle any special transformations of the image data. The various
  297. ways to transform the data will be described in the order that they
  298. should occur. This is important, as some of these change the color
  299. type and/or bit depth of the data, and some others only work on
  300. certain color types and bit depths. Even though each transformation
  301. checks to see if it has data that it can do somthing with, you should
  302. make sure to only enable a transformation if it will be valid for the
  303. data. For example, don't swap red and blue on grayscale data.
  304. The colors used for the background and transparency values should be
  305. supplied in the same format/depth as the current image data. They
  306. are stored in the same format/depth as the image data in a bKGD or tRNS
  307. chunk, so this is what libpng expects for this data. The colors are
  308. transformed to keep in sync with the image data when an application
  309. calls the png_read_update_info() routine (see below).
  310. Data will be decoded into the supplied row buffers packed into bytes
  311. unless the library has been told to transform it into another format.
  312. For example, 4 bit/pixel paletted or grayscale data will be returned
  313. 2 pixels/byte with the leftmost pixel in the high-order bits of the
  314. byte, unless png_set_packing() is called. 8-bit RGB data will be stored
  315. in RGBRGBRGB format unless png_set_filler() is called to insert filler
  316. bytes, either before or after each RGB triplet. 16-bit RGB data will
  317. be returned RRGGBBRRGGBB, with the most significant byte of the color
  318. value first, unless png_set_strip_16() is called to transform it to
  319. regular RGBRGB triplets.
  320. The following code transforms grayscale images of less than 8 to 8 bits,
  321. changes paletted images to RGB, and adds a full alpha channel if there is
  322. transparency information in a tRNS chunk. This is most useful on
  323. grayscale images with bit depths of 2 or 4 or if there is a multiple-image
  324. viewing application that wishes to treat all images in the same way.
  325. if (color_type == PNG_COLOR_TYPE_PALETTE && bit_depth <= 8)
  326. png_set_expand(png_ptr);
  327. if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
  328. png_set_expand(png_ptr);
  329. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
  330. png_set_expand(png_ptr);
  331. PNG can have files with 16 bits per channel. If you only can handle
  332. 8 bits per channel, this will strip the pixels down to 8 bit.
  333. if (bit_depth == 16)
  334. png_set_strip_16(png_ptr);
  335. The png_set_background() function tells libpng to composite images
  336. with alpha or simple transparency against the supplied background
  337. color. If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
  338. you may use this color, or supply another color more suitable for
  339. the current display (e.g., the background color from a web page). You
  340. need to tell libpng whether the color is in the gamma space of the
  341. display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
  342. (PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
  343. that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
  344. know why anyone would use this, but it's here).
  345. If, for some reason, you don't need the alpha channel on an image,
  346. and you want to remove it rather than combining it with the background
  347. (but the image author certainly had in mind that you *would* combine
  348. it with the background, so that's what you should probably do):
  349. if (color_type & PNG_COLOR_MASK_ALPHA)
  350. png_set_strip_alpha(png_ptr);
  351. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  352. they can, resulting in, for example, 8 pixels per byte for 1 bit
  353. files. This code expands to 1 pixel per byte without changing the
  354. values of the pixels:
  355. if (bit_depth < 8)
  356. png_set_packing(png_ptr);
  357. PNG files have possible bit depths of 1, 2, 4, 8, and 16. All pixels
  358. stored in a PNG image have been "scaled" or "shifted" up to the next
  359. higher possible bit depth (eg from 5 bits/sample in the range [0,31] to
  360. 8 bits/sample in the range [0, 255]). However, it is also possible to
  361. convert the PNG pixel data back to the original bit depth of the image.
  362. This call reduces the pixels back down to the original bit depth:
  363. png_color_16p sig_bit;
  364. if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
  365. png_set_shift(png_ptr, sig_bit);
  366. PNG files store 3-color pixels in red, green, blue order. This code
  367. changes the storage of the pixels to blue, green, red:
  368. if (color_type == PNG_COLOR_TYPE_RGB ||
  369. color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  370. png_set_bgr(png_ptr);
  371. PNG files store RGB pixels packed into 3 bytes. This code expands them
  372. into 4 bytes for windowing systems that need them in this format:
  373. if (bit_depth == 8 && color_type == PNG_COLOR_TYPE_RGB)
  374. png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
  375. where "filler" is the number to fill with, and the location is
  376. either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
  377. you want the filler before the RGB or after. This transformation
  378. does not affect images that already have full alpha channels.
  379. If you are reading an image with an alpha channel, and you need the
  380. data as ARGB instead of the normal PNG format RGBA:
  381. if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  382. png_set_swap_alpha(png_ptr);
  383. For some uses, you may want a grayscale image to be represented as
  384. RGB. This code will do that conversion:
  385. if (color_type == PNG_COLOR_TYPE_GRAY ||
  386. color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  387. png_set_gray_to_rgb(png_ptr);
  388. If you have a grayscale and you are using png_set_expand() to change to
  389. a higher bit-depth you must indicate if the supplied background gray
  390. is supplied in the original file bit depth (need_expand = 1) or in the
  391. expanded bit depth (need_expand = 0). Similarly, if you are reading
  392. a paletted image, you must indicate if you have supplied the background
  393. as a palette index that needs to be expanded (need_expand = 1). You can
  394. also specify an RGB triplet that isn't in the palette when setting your
  395. background for a paletted image.
  396. png_color_16 my_background;
  397. png_color_16p image_background;
  398. if (png_get_bKGD(png_ptr, info_ptr, &image_background))
  399. png_set_background(png_ptr, image_background),
  400. PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
  401. else
  402. png_set_background(png_ptr, &my_background,
  403. PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
  404. To properly display PNG images on any kind of system, the application needs
  405. to know what the display gamma is. Ideally, the user will know this, and
  406. the application will allow them to set it. One method of allowing the user
  407. to set the display gamma separately for each system is to check for the
  408. DISPLAY_GAMMA and VIEWING_GAMMA environment variables or for a SCREEN_GAMMA
  409. environment variable, which will hopefully be correctly set.
  410. Note that display_gamma is the gamma of your display, while screen_gamma is
  411. the overall gamma correction required to produce pleasing results,
  412. which depends on the lighting conditions in the surrounding environment.
  413. Screen_gamma is display_gamma/viewing_gamma, where viewing_gamma is
  414. the amount of additional gamma correction needed to compensate for
  415. a dim (viewing_gamma=1.125) or dark (viewing_gamma=1.25) environment.
  416. In a brightly lit room, no compensation other than the display_gamma
  417. is needed (viewing_gamma=1.0).
  418. if (/* We have a user-defined screen gamma value */)
  419. {
  420. screen_gamma = user_defined_screen_gamma;
  421. }
  422. /* One way that applications can share the same screen gamma value */
  423. else if ((gamma_str = getenv("SCREEN_GAMMA")) != NULL)
  424. {
  425. screen_gamma = atof(gamma_str);
  426. }
  427. /* If we don't have another value */
  428. else
  429. {
  430. screen_gamma = 2.5; /* A good guess for a PC monitor in a bright office */
  431. screen_gamma = 2.2; /* A good guess for a PC monitor in a dim room */
  432. screen_gamma = 2.0; /* A good guess for a PC monitor in a dark room */
  433. screen_gamma = 1.7 or 1.0; /* A good guess for Mac systems */
  434. }
  435. The png_set_gamma() function handles gamma transformations of the data.
  436. Pass both the file gamma and the current screen_gamma. If the file does
  437. not have a gamma value, you can pass one anyway if you have an idea what
  438. it is (usually 0.50 is a good guess for GIF images on PCs). Note
  439. that file gammas are inverted from screen gammas. See the discussions
  440. on gamma in the PNG specification for an excellent description of what
  441. gamma is, and why all applications should support it. It is strongly
  442. recommended that PNG viewers support gamma correction.
  443. if (png_get_gAMA(png_ptr, info_ptr, &gamma))
  444. png_set_gamma(png_ptr, screen_gamma, gamma);
  445. else
  446. png_set_gamma(png_ptr, screen_gamma, 0.50);
  447. If you need to reduce an RGB file to a paletted file, or if a paletted
  448. file has more entries then will fit on your screen, png_set_dither()
  449. will do that. Note that this is a simple match dither that merely
  450. finds the closest color available. This should work fairly well with
  451. optimized palettes, and fairly badly with linear color cubes. If you
  452. pass a palette that is larger then maximum_colors, the file will
  453. reduce the number of colors in the palette so it will fit into
  454. maximum_colors. If there is a histogram, it will use it to make
  455. more intelligent choices when reducing the palette. If there is no
  456. histogram, it may not do as good a job.
  457. if (color_type & PNG_COLOR_MASK_COLOR)
  458. {
  459. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE))
  460. {
  461. png_color_16p histogram;
  462. png_get_hIST(png_ptr, info_ptr, &histogram);
  463. png_set_dither(png_ptr, palette, num_palette, max_screen_colors,
  464. histogram, 1);
  465. }
  466. else
  467. {
  468. png_color std_color_cube[MAX_SCREEN_COLORS] =
  469. { ... colors ... };
  470. png_set_dither(png_ptr, std_color_cube, MAX_SCREEN_COLORS,
  471. MAX_SCREEN_COLORS, NULL,0);
  472. }
  473. }
  474. PNG files describe monochrome as black being zero and white being one.
  475. The following code will reverse this (make black be one and white be
  476. zero):
  477. if (bit_depth == 1 && color_type == PNG_COLOR_GRAY)
  478. png_set_invert_mono(png_ptr);
  479. PNG files store 16 bit pixels in network byte order (big-endian,
  480. ie. most significant bits first). This code chages the storage to the
  481. other way (little-endian, ie. least significant bits first, eg. the
  482. way PCs store them):
  483. if (bit_depth == 16)
  484. png_set_swap(png_ptr);
  485. If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
  486. need to change the order the pixels are packed into bytes, you can use:
  487. if (bit_depth < 8)
  488. png_set_packswap(png_ptr);
  489. The last thing to handle is interlacing; this is covered in detail below,
  490. but you must call the function here if you want libpng to handle expansion
  491. of the interlaced image.
  492. number_of_passes = png_set_interlace_handling(png_ptr);
  493. After setting the transformations, libpng can update your png_info
  494. structure to reflect any transformations you've requested with this
  495. call. This is most useful to update the info structure's rowbytes
  496. field so you can use it to allocate your image memory. This function
  497. will also update your palette with the correct screen_gamma and
  498. background if these have been given with the calls above.
  499. png_read_update_info(png_ptr, info_ptr);
  500. After you call png_read_update_info(), you can allocate any
  501. memory you need to hold the image. The row data is simply
  502. raw byte data for all forms of images. As the actual allocation
  503. varies among applications, no example will be given. If you
  504. are allocating one large chunk, you will need to build an
  505. array of pointers to each row, as it will be needed for some
  506. of the functions below.
  507. After you've allocated memory, you can read the image data.
  508. The simplest way to do this is in one function call. If you are
  509. allocating enough memory to hold the whole image, you can just
  510. call png_read_image() and libpng will read in all the image data
  511. and put it in the memory area supplied. You will need to pass in
  512. an array of pointers to each row.
  513. This function automatically handles interlacing, so you don't need
  514. to call png_set_interlace_handling() or call this function multiple
  515. times, or any of that other stuff necessary with png_read_rows().
  516. png_read_image(png_ptr, row_pointers);
  517. where row_pointers is:
  518. png_bytep row_pointers[height];
  519. You can point to void or char or whatever you use for pixels.
  520. If you don't want to read in the whole image at once, you can
  521. use png_read_rows() instead. If there is no interlacing (check
  522. interlace_type == PNG_INTERLACE_TYPE_NONE), this is simple:
  523. png_read_rows(png_ptr, row_pointers, NULL, number_of_rows);
  524. where row_pointers is the same as in the png_read_image() call.
  525. If you are doing this just one row at a time, you can do this with
  526. row_pointers:
  527. png_bytep row_pointers = row;
  528. png_read_row(png_ptr, &row_pointers, NULL);
  529. If the file is interlaced (info_ptr->interlace_type != 0), things get
  530. somewhat harder. The only current (PNG Specification version 1.0)
  531. interlacing type for PNG is (interlace_type == PNG_INTERLACE_TYPE_ADAM7)
  532. is a somewhat complicated 2D interlace scheme, known as Adam7, that
  533. breaks down an image into seven smaller images of varying size, based
  534. on an 8x8 grid.
  535. libpng can fill out those images or it can give them to you "as is".
  536. If you want them filled out, there are two ways to do that. The one
  537. mentioned in the PNG specification is to expand each pixel to cover
  538. those pixels that have not been read yet (the "rectangle" method).
  539. This results in a blocky image for the first pass, which gradually
  540. smooths out as more pixels are read. The other method is the "sparkle"
  541. method, where pixels are drawn only in their final locations, with the
  542. rest of the image remaining whatever colors they were initialized to
  543. before the start of the read. The first method usually looks better,
  544. but tends to be slower, as there are more pixels to put in the rows.
  545. If you don't want libpng to handle the interlacing details, just call
  546. png_read_rows() seven times to read in all seven images. Each of the
  547. images is a valid image by itself, or they can all be combined on an
  548. 8x8 grid to form a single image (although if you intend to combine them
  549. you would be far better off using the libpng interlace handling).
  550. The first pass will return an image 1/8 as wide as the entire image
  551. (every 8th column starting in column 0) and 1/8 as high as the original
  552. (every 8th row starting in row 0), the second will be 1/8 as wide
  553. (starting in column 4) and 1/8 as high (also starting in row 0). The
  554. third pass will be 1/4 as wide (every 4th pixel starting in column 0) and
  555. 1/8 as high (every 8th row starting in row 4), and the fourth pass will
  556. be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
  557. and every 4th row starting in row 0). The fifth pass will return an
  558. image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
  559. while the sixth pass will be 1/2 as wide and 1/2 as high as the original
  560. (starting in column 1 and row 0). The seventh and final pass will be as
  561. wide as the original, and 1/2 as high, containing all of the odd
  562. numbered scanlines. Phew!
  563. If you want libpng to expand the images, call this before calling
  564. png_start_read_image() or png_read_update_info():
  565. if (interlace_type == PNG_INTERLACE_TYPE_ADAM7)
  566. number_of_passes = png_set_interlace_handling(png_ptr);
  567. This will return the number of passes needed. Currently, this
  568. is seven, but may change if another interlace type is added.
  569. This function can be called even if the file is not interlaced,
  570. where it will return one pass.
  571. If you are not going to display the image after each pass, but are
  572. going to wait until the entire image is read in, use the sparkle
  573. effect. This effect is faster and the end result of either method
  574. is exactly the same. If you are planning on displaying the image
  575. after each pass, the "rectangle" effect is generally considered the
  576. better looking one.
  577. If you only want the "sparkle" effect, just call png_read_rows() as
  578. normal, with the third parameter NULL. Make sure you make pass over
  579. the image number_of_passes times, and you don't change the data in the
  580. rows between calls. You can change the locations of the data, just
  581. not the data. Each pass only writes the pixels appropriate for that
  582. pass, and assumes the data from previous passes is still valid.
  583. png_read_rows(png_ptr, row_pointers, NULL, number_of_rows);
  584. If you only want the first effect (the rectangles), do the same as
  585. before except pass the row buffer in the third parameter, and leave
  586. the second parameter NULL.
  587. png_read_rows(png_ptr, NULL, row_pointers, number_of_rows);
  588. After you are finished reading the image, you can finish reading
  589. the file. If you are interested in comments or time, which may be
  590. stored either before or after the image data, you should pass the
  591. info_ptr pointer from the png_read_info() call, or you can pass a
  592. separate png_info struct if you want to keep the comments from
  593. before and after the image separate. If you are not interested, you
  594. can pass NULL.
  595. png_read_end(png_ptr, end_info);
  596. When you are done, you can free all memory allocated by libpng like this:
  597. png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  598. For a more compact example of reading a PNG image, see the file example.c.
  599. Reading PNG files progressively:
  600. The progressive reader is slightly different then the non-progressive
  601. reader. Instead of calling png_read_info(), png_read_rows(), and
  602. png_read_end(), you make one call to png_process_data(), which calls
  603. callbacks when it has the info, a row, or the end of the image. You
  604. set up these callbacks with png_set_progressive_read_fn(). You don't
  605. have to worry about the input/output functions of libpng, as you are
  606. giving the library the data directly in png_process_data(). I will
  607. assume that you have read the section on reading PNG files above,
  608. so I will only highlight the differences (although I will show
  609. all of the code).
  610. png_structp png_ptr;
  611. png_infop info_ptr;
  612. /* An example code fragment of how you would initialize the progressive
  613. reader in your application. */
  614. int
  615. initialize_png_reader()
  616. {
  617. png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  618. (void *)user_error_ptr, user_error_fn, user_warning_fn);
  619. if (!png_ptr)
  620. return -1;
  621. info_ptr = png_create_info_struct(png_ptr);
  622. if (!info_ptr)
  623. {
  624. png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
  625. return -1;
  626. }
  627. if (setjmp(png_ptr->jmpbuf))
  628. {
  629. png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  630. return -1;
  631. }
  632. /* This one's new. You can provide functions to be called
  633. when the header info is valid, when each row is completed,
  634. and when the image is finished. If you aren't using all
  635. functions, you can specify a NULL parameter. You can use
  636. any struct as the user_ptr (cast to a void pointer for the
  637. function call), and retrieve the pointer from inside the
  638. callbacks using the function png_get_progressive_ptr(png_ptr);
  639. which will return a void pointer, which you have to cast
  640. appropriately.
  641. */
  642. png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
  643. info_callback, row_callback, end_callback);
  644. return 0;
  645. }
  646. /* A code fragment that you call as you recieve blocks of data */
  647. int
  648. process_data(png_bytep buffer, png_uint_32 length)
  649. {
  650. if (setjmp(png_ptr->jmpbuf))
  651. {
  652. png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  653. return -1;
  654. }
  655. /* This one's new also. Simply give it a chunk of data
  656. from the file stream (in order, of course). On machines
  657. with segmented memory models machines, don't give it any
  658. more than 64K. The library seems to run fine with sizes
  659. of 4K. Although you can give it much less if necessary
  660. (I assume you can give it chunks of 1 byte, I haven't
  661. tried less then 256 bytes yet). When this function returns,
  662. you may want to display any rows that were generated in the
  663. row callback if you don't already do so there.
  664. */
  665. png_process_data(png_ptr, info_ptr, buffer, length);
  666. return 0;
  667. }
  668. /* This function is called (as set by png_set_progressive_fn() above)
  669. when enough data has been supplied so all of the header has been read.
  670. */
  671. void
  672. info_callback(png_structp png_ptr, png_infop info)
  673. {
  674. /* Do any setup here, including setting any of the transformations
  675. mentioned in the Reading PNG files section. For now, you _must_
  676. call either png_start_read_image() or png_read_update_info()
  677. after all the transformations are set (even if you don't set
  678. any). You may start getting rows before png_process_data()
  679. returns, so this is your last chance to prepare for that.
  680. */
  681. }
  682. /* This function is called when each row of image data is complete */
  683. void
  684. row_callback(png_structp png_ptr, png_bytep new_row,
  685. png_uint_32 row_num, int pass)
  686. {
  687. /* If the image is interlaced, and you turned on the interlace
  688. handler, this function will be called for every row in every pass.
  689. Some of these rows will not be changed from the previous pass.
  690. When the row is not changed, the new_row variable will be NULL.
  691. The rows and passes are called in order, so you don't really
  692. need the row_num and pass, but I'm supplying them because it
  693. may make your life easier.
  694. For the non-NULL rows of interlaced images, you must call
  695. png_progressive_combine_row() passing in the row and the
  696. old row. You can call this function for NULL rows (it will
  697. just return) and for non-interlaced images (it just does the
  698. memcpy for you) if it will make the code easier. Thus, you
  699. can just do this for all cases:
  700. */
  701. png_progressive_combine_row(png_ptr, old_row, new_row);
  702. /* where old_row is what was displayed for previous rows. Note
  703. that the first pass (pass == 0, really) will completely cover
  704. the old row, so the rows do not have to be initialized. After
  705. the first pass (and only for interlaced images), you will have
  706. to pass the current row, and the function will combine the
  707. old row and the new row.
  708. */
  709. }
  710. void
  711. end_callback(png_structp png_ptr, png_infop info)
  712. {
  713. /* This function is called after the whole image has been read,
  714. including any chunks after the image (up to and including
  715. the IEND). You will usually have the same info chunk as you
  716. had in the header, although some data may have been added
  717. to the comments and time fields.
  718. Most people won't do much here, perhaps setting a flag that
  719. marks the image as finished.
  720. */
  721. }
  722. IV. Writing
  723. Much of this is very similar to reading. However, everything of
  724. importance is repeated here, so you won't have to constantly look
  725. back up in the reading section to understand writing.
  726. You will want to do the I/O initialization before you get into libpng,
  727. so if it doesn't work, you don't have anything to undo. If you are not
  728. using the standard I/O functions, you will need to replace them with
  729. custom writing functions. See the discussion under Customizing libpng.
  730. FILE *fp = fopen(file_name, "wb");
  731. if (!fp)
  732. {
  733. return;
  734. }
  735. Next, png_struct and png_info need to be allocated and initialized.
  736. As these can be both relatively large, you may not want to store these
  737. on the stack, unless you have stack space to spare. Of course, you
  738. will want to check if they return NULL.
  739. png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  740. (void *)user_error_ptr, user_error_fn, user_warning_fn);
  741. if (!png_ptr)
  742. return;
  743. png_infop info_ptr = png_create_info_struct(png_ptr);
  744. if (!info_ptr)
  745. {
  746. png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
  747. return;
  748. }
  749. After you have these structures, you will need to set up the
  750. error handling. When libpng encounters an error, it expects to
  751. longjmp() back to your routine. Therefore, you will need to call
  752. setjmp and pass the jmpbuf field of your png_struct. If you
  753. write the file from different routines, you will need to update
  754. the jmpbuf field every time you enter a new routine that will
  755. call a png_ function. See your documentation of setjmp/longjmp
  756. for your compiler for more information on setjmp/longjmp. See
  757. the discussion on libpng error handling in the Customizing Libpng
  758. section below for more information on the libpng error handling.
  759. if (setjmp(png_ptr->jmpbuf))
  760. {
  761. png_destroy_write_struct(&png_ptr, &info_ptr);
  762. fclose(fp);
  763. return;
  764. }
  765. Now you need to set up the output code. The default for libpng is to
  766. use the C function fwrite(). If you use this, you will need to pass a
  767. valid FILE * in the function png_init_io(). Be sure that the file is
  768. opened in binary mode. Again, if you wish to handle writing data in
  769. another way, see the discussion on libpng I/O handling in the Customizing
  770. Libpng section below.
  771. png_init_io(png_ptr, fp);
  772. You now have the option of modifying how the compression library will
  773. run. The following functions are mainly for testing, but may be useful
  774. in some cases, like if you need to write PNG files extremely fast and
  775. are willing to give up some compression, or if you want to get the
  776. maximum possible compression at the expense of slower writing. If you
  777. have no special needs in this area, let the library do what it wants by
  778. not calling this function at all, as it has been tuned to deliver a good
  779. speed/compression ratio. The second parameter to png_set_filter() is
  780. the filter method, for which the only valid value is '0' (as of the
  781. 06/96 PNG specification. The third parameter is a flag that indicates
  782. which filter type(s) are to be tested for each scanline. See the
  783. Compression Library for details on the specific filter types.
  784. /* turn on or off filtering, and/or choose specific filters */
  785. png_set_filter(png_ptr, 0,
  786. PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_PAETH);
  787. The png_set_compression_???() functions interface to the zlib compression
  788. library, and should mostly be ignored unless you really know what you are
  789. doing. The only generally useful call is png_set_compression_level()
  790. which changes how much time zlib spends on trying to compress the image
  791. data. See the Compression Library for details on the compression levels.
  792. /* set the zlib compression level */
  793. png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
  794. /* set other zlib parameters */
  795. png_set_compression_mem_level(png_ptr, 8);
  796. png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
  797. png_set_compression_window_bits(png_ptr, 15);
  798. png_set_compression_method(png_ptr, 8);
  799. You now need to fill in the png_info structure with all the data you
  800. wish to write before the actual image. Note that the only thing you
  801. are allowed to write after the image is the text chunks and the time
  802. chunk (as of PNG Specification 1.0, anyway). See png_write_end() and
  803. the latest PNG specification for more information on that. If you
  804. wish to write them before the image, fill them in now, and flag that
  805. data as being valid. If you want to wait until after the data, don't
  806. fill them until png_write_end(). For all the fields in png_info and
  807. their data types, see png.h. For explanations of what the fields
  808. contain, see the PNG specification.
  809. Some of the more important parts of the png_info are:
  810. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type,
  811. interlace_type, compression_type, filter_type)
  812. width - holds the width of the image in pixels (up to 2^31).
  813. height - holds the height of the image in pixels (up to 2^31).
  814. bit_depth - holds the bit depth of one of the image channels.
  815. (valid values are 1, 2, 4, 8, 16 and depend also on the
  816. color_type. See also significant bits (sBIT) below).
  817. color_type - describes which color/alpha channels are present.
  818. PNG_COLOR_TYPE_GRAY (bit depths 1, 2, 4, 8, 16)
  819. PNG_COLOR_TYPE_GRAY_ALPHA (bit depths 8, 16)
  820. PNG_COLOR_TYPE_PALETTE (bit depths 1, 2, 4, 8)
  821. PNG_COLOR_TYPE_RGB (bit_depths 8, 16)
  822. PNG_COLOR_TYPE_RGB_ALPHA (bit_depths 8, 16)
  823. PNG_COLOR_MASK_PALETTE
  824. PNG_COLOR_MASK_COLOR
  825. PNG_COLOR_MASK_ALPHA
  826. interlace_type - PNG_INTERLACE_TYPE_NONE or PNG_INTERLACE_TYPE_ADAM7
  827. compression_type - (must be PNG_COMPRESSION_TYPE_DEFAULT for PNG 1.0)
  828. filter_type - (must be PNG_FILTER_TYPE_DEFAULT for PNG 1.0)
  829. png_set_PLTE(png_ptr, info_ptr, palette, num_palette);
  830. palette - the palette for the file (array of png_color)
  831. num_palette - number of entries in the palette
  832. png_set_gAMA(png_ptr, info_ptr, gamma);
  833. gamma - the gamma the image was created at (PNG_INFO_gAMA)
  834. png_set_sRGB(png_ptr, info_ptr, srgb_intent);
  835. srgb_intent - the rendering intent (PNG_INFO_sRGB)
  836. The presence of the sRGB chunk means that the pixel
  837. data is in the sRGB color space. This chunk also
  838. implies specific values of gAMA and cHRM.
  839. Rendering intent is the CSS-1 property that has been
  840. defined by the International Color Consortium
  841. (http://www.color.org). It can be one of
  842. PNG_SRGB_INTENT_SATURATION, PNG_SRGB_INTENT_PERCEPTUAL,
  843. PNG_SRGB_INTENT_ABSOLUTE, or PNG_SRGB_INTENT_RELATIVE.
  844. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, srgb_intent);
  845. srgb_intent - the rendering intent (PNG_INFO_sRGB)
  846. The presence of the sRGB chunk means that the pixel
  847. data is in the sRGB color space. This chunk also
  848. causes gAMA and cHRM chunks with the specific values
  849. that are consistent with sRGB to be written.
  850. png_set_sBIT(png_ptr, info_ptr, sig_bit);
  851. sig_bit - the number of significant bits for (PNG_INFO_sBIT)
  852. the gray, red, green, and blue channels, whichever
  853. are appropriate for the given color type (png_color_16)
  854. png_set_tRNS(png_ptr, info_ptr, trans, num_trans, trans_values);
  855. trans - array of transparent entries for palette (PNG_INFO_tRNS)
  856. trans_values - transparent pixel for non-paletted images (PNG_INFO_tRNS)
  857. num_trans - number of transparent entries (PNG_INFO_tRNS)
  858. png_set_hIST(png_ptr, info_ptr, hist); (PNG_INFO_hIST)
  859. hist - histogram of palette (array of png_color_16)
  860. png_set_tIME(png_ptr, info_ptr, mod_time);
  861. mod_time - time image was last modified (PNG_VALID_tIME)
  862. png_set_bKGD(png_ptr, info_ptr, background);
  863. background - background color (PNG_VALID_bKGD)
  864. png_set_text(png_ptr, info_ptr, text_ptr, num_text);
  865. text_ptr - array of png_text holding image comments
  866. text_ptr[i]->key - keyword for comment.
  867. text_ptr[i]->text - text comments for current keyword.
  868. text_ptr[i]->compression - type of compression used on "text"
  869. PNG_TEXT_COMPRESSION_NONE or
  870. PNG_TEXT_COMPRESSION_zTXt
  871. num_text - number of comments in text_ptr
  872. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  873. offset_x - positive offset from the left edge of the screen
  874. offset_y - positive offset from the top edge of the screen
  875. unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
  876. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  877. res_x - pixels/unit physical resolution in x direction
  878. res_y - pixels/unit physical resolution in x direction
  879. unit_type - PNG_RESOLUTION_UNKOWN, PNG_RESOLUTION_METER
  880. In PNG files, the alpha channel in an image is the level of opacity.
  881. If your data is supplied as a level of transparency, you can invert the
  882. alpha channel before you write it, so that 0 is fully transparent and 255
  883. (in 8-bit or paletted images) or 65535 (in 16-bit images) is fully opaque,
  884. with
  885. png_set_invert_alpha(png_ptr);
  886. This must appear here instead of later with the other transformations
  887. because in the case of paletted images the tRNS chunk data has to
  888. be inverted before the tRNS chunk is written. If your image is not a
  889. paletted image, the tRNS data (which in such cases represents a single
  890. color to be rendered as transparent) won't be changed.
  891. A quick word about text and num_text. text is an array of png_text
  892. structures. num_text is the number of valid structures in the array.
  893. If you want, you can use max_text to hold the size of the array, but
  894. libpng ignores it for writing (it does use it for reading). Each
  895. png_text structure holds a keyword-text value, and a compression type.
  896. The compression types have the same valid numbers as the compression
  897. types of the image data. Currently, the only valid number is zero.
  898. However, you can store text either compressed or uncompressed, unlike
  899. images which always have to be compressed. So if you don't want the
  900. text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
  901. Until text gets around 1000 bytes, it is not worth compressing it.
  902. After the text has been written out to the file, the compression type
  903. is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
  904. so that it isn't written out again at the end (in case you are calling
  905. png_write_end() with the same struct.
  906. The keywords that are given in the PNG Specification are:
  907. Title Short (one line) title or caption for image
  908. Author Name of image's creator
  909. Description Description of image (possibly long)
  910. Copyright Copyright notice
  911. Creation Time Time of original image creation (usually
  912. RFC 1123 format, see below)
  913. Software Software used to create the image
  914. Disclaimer Legal disclaimer
  915. Warning Warning of nature of content
  916. Source Device used to create the image
  917. Comment Miscellaneous comment; conversion from other
  918. image format
  919. The keyword-text pairs work like this. Keywords should be short
  920. simple descriptions of what the comment is about. Some typical
  921. keywords are found in the PNG specification, as is some recomendations
  922. on keywords. You can repeat keywords in a file. You can even write
  923. some text before the image and some after. For example, you may want
  924. to put a description of the image before the image, but leave the
  925. disclaimer until after, so viewers working over modem connections
  926. don't have to wait for the disclaimer to go over the modem before
  927. they start seeing the image. Finally, keywords should be full
  928. words, not abbreviations. Keywords and text are in the ISO 8859-1
  929. (Latin-1) character set (a superset of regular ASCII) and can not
  930. contain NUL characters, and should not contain control or other
  931. unprintable characters. To make the comments widely readable, stick
  932. with basic ASCII, and avoid machine specific character set extensions
  933. like the IBM-PC character set. The keyword must be present, but
  934. you can leave off the text string on non-compressed pairs.
  935. Compressed pairs must have a text string, as only the text string
  936. is compressed anyway, so the compression would be meaningless.
  937. PNG supports modification time via the png_time structure. Two
  938. conversion routines are proved, png_convert_from_time_t() for
  939. time_t and png_convert_from_struct_tm() for struct tm. The
  940. time_t routine uses gmtime(). You don't have to use either of
  941. these, but if you wish to fill in the png_time structure directly,
  942. you should provide the time in universal time (GMT) if possible
  943. instead of your local time. Note that the year number is the full
  944. year (ie 1996, rather than 96 - PNG is year 2000 compliant!), and
  945. that months start with 1.
  946. If you want to store the time of the original image creation, you should
  947. use a plain tEXt chunk with the "Creation Time" keyword. This is
  948. necessary because the "creation time" of a PNG image is somewhat vague,
  949. depending on whether you mean the PNG file, the time the image was
  950. created in a non-PNG format, a still photo from which the image was
  951. scanned, or possibly the subject matter itself. In order to facilitate
  952. machine-readable dates, it is recommended that the "Creation Time"
  953. tEXt chunk use RFC 1123 format dates (eg 22 May 1997 18:07:10 GMT"),
  954. although this isn't a requirement. Unlike the tIME chunk, the
  955. "Creation Time" tEXt chunk is not expected to be automatically changed
  956. by the software. To facilitate the use of RFC 1123 dates, a function
  957. png_convert_to_rfc1123(png_timep) is provided to convert from PNG
  958. time to an RFC 1123 format string.
  959. You are now ready to write all the file information up to the actual
  960. image data. You do this with a call to png_write_info().
  961. png_write_info(png_ptr, info_ptr);
  962. After you've written the file information, you can set up the library
  963. to handle any special transformations of the image data. The various
  964. ways to transform the data will be described in the order that they
  965. should occur. This is important, as some of these change the color
  966. type and/or bit depth of the data, and some others only work on
  967. certain color types and bit depths. Even though each transformation
  968. checks to see if it has data that it can do somthing with, you should
  969. make sure to only enable a transformation if it will be valid for the
  970. data. For example, don't swap red and blue on grayscale data.
  971. PNG files store RGB pixels packed into 3 bytes. This code tells
  972. the library to expect input data with 4 bytes per pixel
  973. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  974. where the 0 is the value that will be put in the 4th byte, and the
  975. location is either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending
  976. upon whether the filler byte is stored XRGB or RGBX.
  977. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  978. they can, resulting in, for example, 8 pixels per byte for 1 bit files.
  979. If the data is supplied at 1 pixel per byte, use this code, which will
  980. correctly pack the pixels into a single byte:
  981. png_set_packing(png_ptr);
  982. PNG files reduce possible bit depths to 1, 2, 4, 8, and 16. If your
  983. data is of another bit depth, you can write an sBIT chunk into the
  984. file so that decoders can get the original data if desired.
  985. /* Set the true bit depth of the image data */
  986. if (color_type & PNG_COLOR_MASK_COLOR)
  987. {
  988. sig_bit.red = true_bit_depth;
  989. sig_bit.green = true_bit_depth;
  990. sig_bit.blue = true_bit_depth;
  991. }
  992. else
  993. {
  994. sig_bit.gray = true_bit_depth;
  995. }
  996. if (color_type & PNG_COLOR_MASK_ALPHA)
  997. {
  998. sig_bit.alpha = true_bit_depth;
  999. }
  1000. png_set_sBIT(png_ptr, info_ptr, &sig_bit);
  1001. If the data is stored in the row buffer in a bit depth other than
  1002. one supported by PNG (ie 3 bit data in the range 0-7 for a 4-bit PNG),
  1003. this will scale the values to appear to be the correct bit depth as
  1004. is required by PNG.
  1005. png_set_shift(png_ptr, &sig_bit);
  1006. PNG files store 16 bit pixels in network byte order (big-endian,
  1007. ie. most significant bits first). This code would be used if they are
  1008. supplied the other way (little-endian, ie. least significant bits
  1009. first, eg. the way PCs store them):
  1010. if (bit_depth > 8)
  1011. png_set_swap(png_ptr);
  1012. If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
  1013. need to change the order the pixels are packed into bytes, you can use:
  1014. if (bit_depth < 8)
  1015. png_set_packswap(png_ptr);
  1016. PNG files store 3 color pixels in red, green, blue order. This code
  1017. would be used if they are supplied as blue, green, red:
  1018. png_set_bgr(png_ptr);
  1019. PNG files describe monochrome as black being zero and white being
  1020. one. This code would be used if the pixels are supplied with this reversed
  1021. (black being one and white being zero):
  1022. png_set_invert_mono(png_ptr);
  1023. It is possible to have libpng flush any pending output, either manually,
  1024. or automatically after a certain number of lines have been written. To
  1025. flush the output stream a single time call:
  1026. png_write_flush(png_ptr);
  1027. and to have libpng flush the output stream periodically after a certain
  1028. number of scanlines have been written, call:
  1029. png_set_flush(png_ptr, nrows);
  1030. Note that the distance between rows is from the last time png_write_flush()
  1031. was called, or the first row of the image if it has never been called.
  1032. So if you write 50 lines, and then png_set_flush 25, it will flush the
  1033. output on the next scanline, and every 25 lines thereafter, unless
  1034. png_write_flush()ls is called before 25 more lines have been written.
  1035. If nrows is too small (less than about 10 lines for a 640 pixel wide
  1036. RGB image) the image compression may decrease noticably (although this
  1037. may be acceptable for real-time applications). Infrequent flushing will
  1038. only degrade the compression performance by a few percent over images
  1039. that do not use flushing.
  1040. That's it for the transformations. Now you can write the image data.
  1041. The simplest way to do this is in one function call. If have the
  1042. whole image in memory, you can just call png_write_image() and libpng
  1043. will write the image. You will need to pass in an array of pointers to
  1044. each row. This function automatically handles interlacing, so you don't
  1045. need to call png_set_interlace_handling() or call this function multiple
  1046. times, or any of that other stuff necessary with png_write_rows().
  1047. png_write_image(png_ptr, row_pointers);
  1048. where row_pointers is:
  1049. png_bytef *row_pointers[height];
  1050. You can point to void or char or whatever you use for pixels.
  1051. If you can't want to write the whole image at once, you can
  1052. use png_write_rows() instead. If the file is not interlaced,
  1053. this is simple:
  1054. png_write_rows(png_ptr, row_pointers, number_of_rows);
  1055. row_pointers is the same as in the png_write_image() call.
  1056. If you are just writing one row at a time, you can do this with
  1057. row_pointers:
  1058. png_bytep row_pointer = row;
  1059. png_write_row(png_ptr, &row_pointer);
  1060. When the file is interlaced, things can get a good deal more
  1061. complicated. The only currently (as of 6/96 -- PNG Specification
  1062. version 1.0) defined interlacing scheme for PNG files is a
  1063. compilcated interlace scheme, known as Adam7, that breaks down an
  1064. image into seven smaller images of varying size. libpng will build
  1065. these images for you, or you can do them yourself. If you want to
  1066. build them yourself, see the PNG specification for details of which
  1067. pixels to write when.
  1068. If you don't want libpng to handle the interlacing details, just
  1069. use png_set_interlace_handling() and call png_write_rows() the
  1070. correct number of times to write all seven sub-images.
  1071. If you want libpng to build the sub-images, call this before you start
  1072. writing any rows:
  1073. number_of_passes = png_set_interlace_handling(png_ptr);
  1074. This will return the number of passes needed. Currently, this
  1075. is seven, but may change if another interlace type is added.
  1076. Then write the complete image number_of_passes times.
  1077. png_write_rows(png_ptr, row_pointers, number_of_rows);
  1078. As some of these rows are not used, and thus return immediately,
  1079. you may want to read about interlacing in the PNG specification,
  1080. and only update the rows that are actually used.
  1081. After you are finished writing the image, you should finish writing
  1082. the file. If you are interested in writing comments or time, you should
  1083. pass an appropriately filled png_info pointer. If you are not interested,
  1084. you can pass NULL.
  1085. png_write_end(png_ptr, info_ptr);
  1086. When you are done, you can free all memory used by libpng like this:
  1087. png_destroy_write_struct(&png_ptr, &info_ptr);
  1088. You must free any data you allocated for info_ptr, such as comments,
  1089. palette, or histogram, before the call to png_destroy_write_struct();
  1090. For a more compact example of writing a PNG image, see the file example.c.
  1091. V. Modifying/Customizing libpng:
  1092. There are two issues here. The first is changing how libpng does
  1093. standard things like memory allocation, input/output, and error handling.
  1094. The second deals with more complicated things like adding new chunks,
  1095. adding new transformations, and generally changing how libpng works.
  1096. All of the memory allocation, input/output, and error handling in libpng
  1097. goes through callbacks which are user setable. The default routines are
  1098. in pngmem.c, pngrio.c, pngwio.c, and pngerror.c respectively. To change
  1099. these functions, call the approprate png_set_???_fn() function.
  1100. Memory allocation is done through the functions png_large_malloc(),
  1101. png_malloc(), png_realloc(), png_large_free(), and png_free(). These
  1102. currently just call the standard C functions. The large functions must
  1103. handle exactly 64K, but they don't have to handle more than that. If
  1104. your pointers can't access more then 64K at a time, you will want to set
  1105. MAXSEG_64K in zlib.h. Since it is unlikely that the method of handling
  1106. memory allocation on a platform will change between applications, these
  1107. functions must be modified in the library at compile time.
  1108. Input/Output in libpng is done through png_read() and png_write(),
  1109. which currently just call fread() and fwrite(). The FILE * is stored in
  1110. png_struct and is initialized via png_init_io(). If you wish to change
  1111. the method of I/O, the library supplies callbacks that you can set
  1112. through the function png_set_read_fn() and png_set_write_fn() at run
  1113. time, instead of calling the png_init_io() function. These functions
  1114. also provide a void pointer that can be retrieved via the function
  1115. png_get_io_ptr(). For example:
  1116. png_set_read_fn(png_structp png_ptr, voidp io_ptr,
  1117. png_rw_ptr read_data_fn)
  1118. png_set_write_fn(png_structp png_ptr, voidp io_ptr,
  1119. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn);
  1120. voidp io_ptr = png_get_io_ptr(png_ptr);
  1121. The replacement I/O functions should have prototypes as follows:
  1122. void user_read_data(png_structp png_ptr, png_bytep data,
  1123. png_uint_32 length);
  1124. void user_write_data(png_structp png_ptr, png_bytep data,
  1125. png_uint_32 length);
  1126. void user_flush_data(png_structp png_ptr);
  1127. Supplying NULL for the read, write, or flush functions sets them back
  1128. to using the default C stream functions. It is an error to read from
  1129. a write stream, and vice versa.
  1130. Error handling in libpng is done through png_error() and png_warning().
  1131. Errors handled through png_error() are fatal, meaning that png_error()
  1132. should never return to its caller. Currently, this is handled via
  1133. setjmp() and longjmp(), but you could change this to do things like
  1134. exit() if you should wish. On non-fatal errors, png_warning() is called
  1135. to print a warning message, and then control returns to the calling code.
  1136. By default png_error() and png_warning() print a message on stderr via
  1137. fprintf() unless the library is compiled with PNG_NO_STDIO defined. If
  1138. you wish to change the behavior of the error functions, you will need to
  1139. set up your own message callbacks. These functions are normally supplied
  1140. at the time that the png_struct is created. It is also possible to change
  1141. these functions after png_create_???_struct() has been called by calling:
  1142. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  1143. png_error_ptr error_fn, png_error_ptr warning_fn);
  1144. png_voidp error_ptr = png_get_error_ptr(png_ptr);
  1145. If NULL is supplied for either error_fn or warning_fn, then the libpng
  1146. default function will be used, calling fprintf() and/or longjmp() if a
  1147. problem is encountered. The replacement error functions should have
  1148. parameters as follows:
  1149. void user_error_fn(png_structp png_ptr, png_const_charp error_msg);
  1150. void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg);
  1151. The motivation behind using setjmp() and longjmp() is the C++ throw and
  1152. catch exception handling methods. This makes the code much easier to write,
  1153. as there is no need to check every return code of every function call.
  1154. However, there are some uncertainties about the status of local variables
  1155. after a longjmp, so the user may want to be careful about doing anything after
  1156. setjmp returns non-zero besides returning itself. Consult your compiler
  1157. documentation for more details.
  1158. If you need to read or write custom chunks, you will need to get deeper
  1159. into the libpng code, as a mechanism has not yet been supplied for user
  1160. callbacks with custom chunks. First, read the PNG specification, and have
  1161. a first level of understanding of how it works. Pay particular attention
  1162. to the sections that describe chunk names, and look at how other chunks
  1163. were designed, so you can do things similarly. Second, check out the
  1164. sections of libpng that read and write chunks. Try to find a chunk that
  1165. is similar to yours and copy off of it. More details can be found in the
  1166. comments inside the code. A way of handling unknown chunks in a generic
  1167. method, potentially via callback functions, would be best.
  1168. If you wish to write your own transformation for the data, look through
  1169. the part of the code that does the transformations, and check out some of
  1170. the simpler ones to get an idea of how they work. Try to find a similar
  1171. transformation to the one you want to add and copy off of it. More details
  1172. can be found in the comments inside the code itself.
  1173. Configuring for 16 bit platforms:
  1174. You may need to change the png_large_malloc() and png_large_free()
  1175. routines in pngmem.c, as these are requred to allocate 64K, although
  1176. there is already support for many of the common DOS compilers. Also,
  1177. you will want to look into zconf.h to tell zlib (and thus libpng) that
  1178. it cannot allocate more then 64K at a time. Even if you can, the memory
  1179. won't be accessable. So limit zlib and libpng to 64K by defining MAXSEG_64K.
  1180. Configuring for DOS:
  1181. For DOS users which only have access to the lower 640K, you will
  1182. have to limit zlib's memory usage via a png_set_compression_mem_level()
  1183. call. See zlib.h or zconf.h in the zlib library for more information.
  1184. Configuring for Medium Model:
  1185. Libpng's support for medium model has been tested on most of the popular
  1186. compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
  1187. defined, and FAR gets defined to far in pngconf.h, and you should be
  1188. all set. Everything in the library (except for zlib's structure) is
  1189. expecting far data. You must use the typedefs with the p or pp on
  1190. the end for pointers (or at least look at them and be careful). Make
  1191. note that the row's of data are defined as png_bytepp which is a
  1192. unsigned char far * far *.
  1193. Configuring for gui/windowing platforms:
  1194. You will need to write new error and warning functions that use the GUI
  1195. interface, as described previously, and set them to be the error and
  1196. warning functions at the time that png_create_???_struct() is called,
  1197. in order to have them available during the structure initialization.
  1198. They can be changed later via png_set_error_fn(). On some compliers,
  1199. you may also have to change the memory allocators (png_malloc, etc.).
  1200. Configuring for compiler xxx:
  1201. All includes for libpng are in pngconf.h. If you need to add/change/delete
  1202. an include, this is the place to do it. The includes that are not
  1203. needed outside libpng are protected by the PNG_INTERNAL definition,
  1204. which is only defined for those routines inside libpng itself. The
  1205. files in libpng proper only include png.h, which includes pngconf.h.
  1206. Configuring zlib:
  1207. There are special functions to configure the compression. Perhaps the
  1208. most useful one changes the compression level, which currently uses
  1209. input compression values in the range 0 - 9. The library normally
  1210. uses the default compression level (Z_DEFAULT_COMPRESSION = 6). Tests
  1211. have shown that for a large majority of images, compression values in
  1212. the range 3-6 compress nearly as well as higher levels, and do so much
  1213. faster. For online applications it may be desirable to have maximum speed
  1214. (Z_BEST_SPEED = 1). With versions of zlib after v0.99, you can also
  1215. specify no compression (Z_NO_COMPRESSION = 0), but this would create
  1216. files larger than just storing the raw bitmap. You can specify the
  1217. compression level by calling:
  1218. png_set_compression_level(png_ptr, level);
  1219. Another useful one is to reduce the memory level used by the library.
  1220. The memory level defaults to 8, but it can be lowered if you are
  1221. short on memory (running DOS, for example, where you only have 640K).
  1222. png_set_compression_mem_level(png_ptr, level);
  1223. The other functions are for configuring zlib. They are not recommended
  1224. for normal use and may result in writing an invalid PNG file. See
  1225. zlib.h for more information on what these mean.
  1226. png_set_compression_strategy(png_ptr, strategy);
  1227. png_set_compression_window_bits(png_ptr, window_bits);
  1228. png_set_compression_method(png_ptr, method);
  1229. Controlling row filtering:
  1230. If you want to control whether libpng uses filtering or not, which
  1231. filters are used, and how it goes about picking row filters, you
  1232. can call one of these functions. The selection and configuration
  1233. of row filters can have a significant impact on the size and
  1234. encoding speed and a somewhat lesser impact on the decoding speed
  1235. of an image. Filtering is enabled by default for RGB and grayscale
  1236. images (with and without alpha), and for 8-bit paletted images, but
  1237. not for paletted images with bit depths less than 8 bits/pixel.
  1238. The 'method' parameter sets the main filtering method, which is
  1239. currently only '0' in the PNG 1.0 specification. The 'filters'
  1240. parameter sets which filter(s), if any, should be used for each
  1241. scanline. Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
  1242. to turn filtering on and off, respectively.
  1243. Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
  1244. PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
  1245. ORed together '|' to specify one or more filters to use. These
  1246. filters are described in more detail in the PNG specification. If
  1247. you intend to change the filter type during the course of writing
  1248. the image, you should start with flags set for all of the filters
  1249. you intend to use so that libpng can initialize its internal
  1250. structures appropriately for all of the filter types.
  1251. filters = PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP;
  1252. png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters);
  1253. It is also possible to influence how libpng chooses from among the
  1254. available filters. This is done in two ways - by telling it how
  1255. important it is to keep the same filter for successive rows, and
  1256. by telling it the relative computational costs of the filters.
  1257. double weights[3] = {1.5, 1.3, 1.1},
  1258. costs[PNG_FILTER_VALUE_LAST] = {1.0, 1.3, 1.3, 1.5, 1.7};
  1259. png_set_filter_selection(png_ptr, PNG_FILTER_SELECTION_WEIGHTED,
  1260. 3, weights, costs);
  1261. The weights are multiplying factors which indicate to libpng that row
  1262. should be the same for successive rows unless another row filter is that
  1263. many times better than the previous filter. In the above example, if
  1264. the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
  1265. "sum of absolute differences" 1.5 x 1.3 times higher than other filters
  1266. and still be chosen, while the NONE filter could have a sum 1.1 times
  1267. higher than other filters and still be chosen. Unspecified weights are
  1268. taken to be 1.0, and the specified weights should probably be declining
  1269. like those above in order to emphasize recent filters over older filters.
  1270. The filter costs specify for each filter type a relative decoding cost
  1271. to be considered when selecting row filters. This means that filters
  1272. with higher costs are less likely to be chosen over filters with lower
  1273. costs, unless their "sum of absolute differences" is that much smaller.
  1274. The costs do not necessarily reflect the exact computational speeds of
  1275. the various filters, since this would unduely influence the final image
  1276. size.
  1277. Note that the numbers above were invented purely for this example and
  1278. are given only to help explain the function usage. Little testing has
  1279. been done to find optimum values for either the costs or the weights.
  1280. Removing unwanted object code:
  1281. There are a bunch of #define's in pngconf.h that control what parts of
  1282. libpng are compiled. All the defines end in _SUPPORTED. If you are
  1283. never going to use an ability, you can change the #define to #undef
  1284. before recompiling libpng and save yourself code and data space.
  1285. You can also turn them off en masse with a compiler directive that
  1286. defines PNG_READ[or WRITE]_NOT_FULLY_SUPPORTED, or
  1287. PNG_READ[or WRITE]_ANCILLARY_CHUNKS_NOT_SUPPORTED, or all four,
  1288. along with directives to turn on any of the capabilities that you do
  1289. want. The NOT_FULLY_SUPPORTED directives disable the extra
  1290. transformations but still leave the library fully capable of reading
  1291. and writing PNG files with all known public chunks [except for sPLT].
  1292. Use of the PNG_READ[or WRITE]_ANCILLARY_CHUNKS_NOT_SUPPORTED directive
  1293. produces a library that is incapable of reading or writing ancillary chunks.
  1294. All the reading and writing specific code are in separate files, so the
  1295. linker should only grab the files it needs. However, if you want to
  1296. make sure, or if you are building a stand alone library, all the
  1297. reading files start with pngr and all the writing files start with
  1298. pngw. The files that don't match either (like png.c, pngtrans.c, etc.)
  1299. are used for both reading and writing, and always need to be included.
  1300. The progressive reader is in pngpread.c
  1301. If you are creating or distributing a dynamically linked library (a .so
  1302. or DLL file), you should not remove or disable any parts of the library,
  1303. as this will cause applications linked with different versions of the
  1304. library to fail if they call functions not available in your library.
  1305. The size of the library itself should not be an issue, because only
  1306. those sections which are actually used will be loaded into memory.
  1307. Changes to Libpng from version 0.88
  1308. It should be noted that versions of libpng later than 0.96 are not
  1309. distributed by the original libpng author, Guy Schalnat, nor by
  1310. Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
  1311. distributed versions 0.89 through 0.96, but rather by another member
  1312. of the original PNG Group, Glenn Randers-Pehrson. Guy and Andreas are
  1313. still alive and well, but they have moved on to other things.
  1314. The old libpng functions png_read_init(), png_write_init(),
  1315. png_info_init(), png_read_destroy(), and png_write_destory() have been
  1316. moved to PNG_INTERNAL in version 0.95 to discourage their use. The
  1317. preferred method of creating and initializing the libpng structures is
  1318. via the png_create_read_struct(), png_create_write_struct(), and
  1319. png_create_info_struct() because they isolate the size of the structures
  1320. from the application, allow version error checking, and also allow the
  1321. use of custom error handling routines during the initialization, which
  1322. the old functions do not. The functions png_read_destroy() and
  1323. png_write_destroy() do not actually free the memory that libpng
  1324. allocated for these structs, but just reset the data structures, so they
  1325. can be used instead of png_destroy_read_struct() and
  1326. png_destroy_write_struct() if you feel there is too much system overhead
  1327. allocating and freeing the png_struct for each image read.
  1328. Setting the error callbacks via png_set_message_fn() before
  1329. png_read_init() as was suggested in libpng-0.88 is no longer supported
  1330. because this caused applications which do not use custom error functions
  1331. to fail if the png_ptr was not initialized to zero. It is still possible
  1332. to set the error callbacks AFTER png_read_init(), or to change them with
  1333. png_set_error_fn(), which is essentially the same function, but with a
  1334. new name to force compilation errors with applications that try to use
  1335. the old method.