libpng.txt 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959
  1. libpng.txt - A description on how to use and modify libpng
  2. libpng version 1.2.8 - December 3, 2004
  3. Updated and distributed by Glenn Randers-Pehrson
  4. <glennrp at users.sourceforge.net>
  5. Copyright (c) 1998-2004 Glenn Randers-Pehrson
  6. For conditions of distribution and use, see copyright
  7. notice in png.h.
  8. based on:
  9. libpng 1.0 beta 6 version 0.96 May 28, 1997
  10. Updated and distributed by Andreas Dilger
  11. Copyright (c) 1996, 1997 Andreas Dilger
  12. libpng 1.0 beta 2 - version 0.88 January 26, 1996
  13. For conditions of distribution and use, see copyright
  14. notice in png.h. Copyright (c) 1995, 1996 Guy Eric
  15. Schalnat, Group 42, Inc.
  16. Updated/rewritten per request in the libpng FAQ
  17. Copyright (c) 1995, 1996 Frank J. T. Wojcik
  18. December 18, 1995 & January 20, 1996
  19. I. Introduction
  20. This file describes how to use and modify the PNG reference library
  21. (known as libpng) for your own use. There are five sections to this
  22. file: introduction, structures, reading, writing, and modification and
  23. configuration notes for various special platforms. In addition to this
  24. file, example.c is a good starting point for using the library, as
  25. it is heavily commented and should include everything most people
  26. will need. We assume that libpng is already installed; see the
  27. INSTALL file for instructions on how to install libpng.
  28. Libpng was written as a companion to the PNG specification, as a way
  29. of reducing the amount of time and effort it takes to support the PNG
  30. file format in application programs.
  31. The PNG specification (second edition), November 2003, is available as
  32. a W3C Recommendation and as an ISO Standard (ISO/IEC 15948:2003 (E)) at
  33. <http://www.w3.org/TR/2003/REC-PNG-20031110/
  34. The W3C and ISO documents have identical technical content.
  35. The PNG-1.2 specification is available at
  36. <http://www.libpng.org/pub/png/documents/>
  37. The PNG-1.0 specification is available
  38. as RFC 2083 <http://www.libpng.org/pub/png/documents/> and as a
  39. W3C Recommendation <http://www.w3.org/TR/REC.png.html>. Some
  40. additional chunks are described in the special-purpose public chunks
  41. documents at <http://www.libpng.org/pub/png/documents/>.
  42. Other information
  43. about PNG, and the latest version of libpng, can be found at the PNG home
  44. page, <http://www.libpng.org/pub/png/>.
  45. Most users will not have to modify the library significantly; advanced
  46. users may want to modify it more. All attempts were made to make it as
  47. complete as possible, while keeping the code easy to understand.
  48. Currently, this library only supports C. Support for other languages
  49. is being considered.
  50. Libpng has been designed to handle multiple sessions at one time,
  51. to be easily modifiable, to be portable to the vast majority of
  52. machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
  53. to use. The ultimate goal of libpng is to promote the acceptance of
  54. the PNG file format in whatever way possible. While there is still
  55. work to be done (see the TODO file), libpng should cover the
  56. majority of the needs of its users.
  57. Libpng uses zlib for its compression and decompression of PNG files.
  58. Further information about zlib, and the latest version of zlib, can
  59. be found at the zlib home page, <http://www.info-zip.org/pub/infozip/zlib/>.
  60. The zlib compression utility is a general purpose utility that is
  61. useful for more than PNG files, and can be used without libpng.
  62. See the documentation delivered with zlib for more details.
  63. You can usually find the source files for the zlib utility wherever you
  64. find the libpng source files.
  65. Libpng is thread safe, provided the threads are using different
  66. instances of the structures. Each thread should have its own
  67. png_struct and png_info instances, and thus its own image.
  68. Libpng does not protect itself against two threads using the
  69. same instance of a structure. Note: thread safety may be defeated
  70. by use of some of the MMX assembler code in pnggccrd.c, which is only
  71. compiled when the user defines PNG_THREAD_UNSAFE_OK.
  72. II. Structures
  73. There are two main structures that are important to libpng, png_struct
  74. and png_info. The first, png_struct, is an internal structure that
  75. will not, for the most part, be used by a user except as the first
  76. variable passed to every libpng function call.
  77. The png_info structure is designed to provide information about the
  78. PNG file. At one time, the fields of png_info were intended to be
  79. directly accessible to the user. However, this tended to cause problems
  80. with applications using dynamically loaded libraries, and as a result
  81. a set of interface functions for png_info (the png_get_*() and png_set_*()
  82. functions) was developed. The fields of png_info are still available for
  83. older applications, but it is suggested that applications use the new
  84. interfaces if at all possible.
  85. Applications that do make direct access to the members of png_struct (except
  86. for png_ptr->jmpbuf) must be recompiled whenever the library is updated,
  87. and applications that make direct access to the members of png_info must
  88. be recompiled if they were compiled or loaded with libpng version 1.0.6,
  89. in which the members were in a different order. In version 1.0.7, the
  90. members of the png_info structure reverted to the old order, as they were
  91. in versions 0.97c through 1.0.5. Starting with version 2.0.0, both
  92. structures are going to be hidden, and the contents of the structures will
  93. only be accessible through the png_get/png_set functions.
  94. The png.h header file is an invaluable reference for programming with libpng.
  95. And while I'm on the topic, make sure you include the libpng header file:
  96. #include <png.h>
  97. III. Reading
  98. We'll now walk you through the possible functions to call when reading
  99. in a PNG file sequentially, briefly explaining the syntax and purpose
  100. of each one. See example.c and png.h for more detail. While
  101. progressive reading is covered in the next section, you will still
  102. need some of the functions discussed in this section to read a PNG
  103. file.
  104. Setup
  105. You will want to do the I/O initialization(*) before you get into libpng,
  106. so if it doesn't work, you don't have much to undo. Of course, you
  107. will also want to insure that you are, in fact, dealing with a PNG
  108. file. Libpng provides a simple check to see if a file is a PNG file.
  109. To use it, pass in the first 1 to 8 bytes of the file to the function
  110. png_sig_cmp(), and it will return 0 if the bytes match the corresponding
  111. bytes of the PNG signature, or nonzero otherwise. Of course, the more bytes
  112. you pass in, the greater the accuracy of the prediction.
  113. If you are intending to keep the file pointer open for use in libpng,
  114. you must ensure you don't read more than 8 bytes from the beginning
  115. of the file, and you also have to make a call to png_set_sig_bytes_read()
  116. with the number of bytes you read from the beginning. Libpng will
  117. then only check the bytes (if any) that your program didn't read.
  118. (*): If you are not using the standard I/O functions, you will need
  119. to replace them with custom functions. See the discussion under
  120. Customizing libpng.
  121. FILE *fp = fopen(file_name, "rb");
  122. if (!fp)
  123. {
  124. return (ERROR);
  125. }
  126. fread(header, 1, number, fp);
  127. is_png = !png_sig_cmp(header, 0, number);
  128. if (!is_png)
  129. {
  130. return (NOT_PNG);
  131. }
  132. Next, png_struct and png_info need to be allocated and initialized. In
  133. order to ensure that the size of these structures is correct even with a
  134. dynamically linked libpng, there are functions to initialize and
  135. allocate the structures. We also pass the library version, optional
  136. pointers to error handling functions, and a pointer to a data struct for
  137. use by the error functions, if necessary (the pointer and functions can
  138. be NULL if the default error handlers are to be used). See the section
  139. on Changes to Libpng below regarding the old initialization functions.
  140. The structure allocation functions quietly return NULL if they fail to
  141. create the structure, so your application should check for that.
  142. png_structp png_ptr = png_create_read_struct
  143. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  144. user_error_fn, user_warning_fn);
  145. if (!png_ptr)
  146. return (ERROR);
  147. png_infop info_ptr = png_create_info_struct(png_ptr);
  148. if (!info_ptr)
  149. {
  150. png_destroy_read_struct(&png_ptr,
  151. (png_infopp)NULL, (png_infopp)NULL);
  152. return (ERROR);
  153. }
  154. png_infop end_info = png_create_info_struct(png_ptr);
  155. if (!end_info)
  156. {
  157. png_destroy_read_struct(&png_ptr, &info_ptr,
  158. (png_infopp)NULL);
  159. return (ERROR);
  160. }
  161. If you want to use your own memory allocation routines,
  162. define PNG_USER_MEM_SUPPORTED and use
  163. png_create_read_struct_2() instead of png_create_read_struct():
  164. png_structp png_ptr = png_create_read_struct_2
  165. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  166. user_error_fn, user_warning_fn, (png_voidp)
  167. user_mem_ptr, user_malloc_fn, user_free_fn);
  168. The error handling routines passed to png_create_read_struct()
  169. and the memory alloc/free routines passed to png_create_struct_2()
  170. are only necessary if you are not using the libpng supplied error
  171. handling and memory alloc/free functions.
  172. When libpng encounters an error, it expects to longjmp back
  173. to your routine. Therefore, you will need to call setjmp and pass
  174. your png_jmpbuf(png_ptr). If you read the file from different
  175. routines, you will need to update the jmpbuf field every time you enter
  176. a new routine that will call a png_*() function.
  177. See your documentation of setjmp/longjmp for your compiler for more
  178. information on setjmp/longjmp. See the discussion on libpng error
  179. handling in the Customizing Libpng section below for more information
  180. on the libpng error handling. If an error occurs, and libpng longjmp's
  181. back to your setjmp, you will want to call png_destroy_read_struct() to
  182. free any memory.
  183. if (setjmp(png_jmpbuf(png_ptr)))
  184. {
  185. png_destroy_read_struct(&png_ptr, &info_ptr,
  186. &end_info);
  187. fclose(fp);
  188. return (ERROR);
  189. }
  190. If you would rather avoid the complexity of setjmp/longjmp issues,
  191. you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case
  192. errors will result in a call to PNG_ABORT() which defaults to abort().
  193. Now you need to set up the input code. The default for libpng is to
  194. use the C function fread(). If you use this, you will need to pass a
  195. valid FILE * in the function png_init_io(). Be sure that the file is
  196. opened in binary mode. If you wish to handle reading data in another
  197. way, you need not call the png_init_io() function, but you must then
  198. implement the libpng I/O methods discussed in the Customizing Libpng
  199. section below.
  200. png_init_io(png_ptr, fp);
  201. If you had previously opened the file and read any of the signature from
  202. the beginning in order to see if this was a PNG file, you need to let
  203. libpng know that there are some bytes missing from the start of the file.
  204. png_set_sig_bytes(png_ptr, number);
  205. Setting up callback code
  206. You can set up a callback function to handle any unknown chunks in the
  207. input stream. You must supply the function
  208. read_chunk_callback(png_ptr ptr,
  209. png_unknown_chunkp chunk);
  210. {
  211. /* The unknown chunk structure contains your
  212. chunk data: */
  213. png_byte name[5];
  214. png_byte *data;
  215. png_size_t size;
  216. /* Note that libpng has already taken care of
  217. the CRC handling */
  218. /* put your code here. Return one of the
  219. following: */
  220. return (-n); /* chunk had an error */
  221. return (0); /* did not recognize */
  222. return (n); /* success */
  223. }
  224. (You can give your function another name that you like instead of
  225. "read_chunk_callback")
  226. To inform libpng about your function, use
  227. png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr,
  228. read_chunk_callback);
  229. This names not only the callback function, but also a user pointer that
  230. you can retrieve with
  231. png_get_user_chunk_ptr(png_ptr);
  232. At this point, you can set up a callback function that will be
  233. called after each row has been read, which you can use to control
  234. a progress meter or the like. It's demonstrated in pngtest.c.
  235. You must supply a function
  236. void read_row_callback(png_ptr ptr, png_uint_32 row,
  237. int pass);
  238. {
  239. /* put your code here */
  240. }
  241. (You can give it another name that you like instead of "read_row_callback")
  242. To inform libpng about your function, use
  243. png_set_read_status_fn(png_ptr, read_row_callback);
  244. Width and height limits
  245. The PNG specification allows the width and height of an image to be as
  246. large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.
  247. Since very few applications really need to process such large images,
  248. we have imposed an arbitrary 1-million limit on rows and columns.
  249. Larger images will be rejected immediately with a png_error() call. If
  250. you wish to override this limit, you can use
  251. png_set_user_limits(png_ptr, width_max, height_max);
  252. to set your own limits, or use width_max = height_max = 0x7fffffffL
  253. to allow all valid dimensions (libpng may reject some very large images
  254. anyway because of potential buffer overflow conditions).
  255. You should put this statement after you create the PNG structure and
  256. before calling png_read_info(), png_read_png(), or png_process_data().
  257. If you need to retrieve the limits that are being applied, use
  258. width_max = png_get_user_width_max(png_ptr);
  259. height_max = png_get_user_height_max(png_ptr);
  260. Unknown-chunk handling
  261. Now you get to set the way the library processes unknown chunks in the
  262. input PNG stream. Both known and unknown chunks will be read. Normal
  263. behavior is that known chunks will be parsed into information in
  264. various info_ptr members; unknown chunks will be discarded. To change
  265. this, you can call:
  266. png_set_keep_unknown_chunks(png_ptr, keep,
  267. chunk_list, num_chunks);
  268. keep - 0: do not handle as unknown
  269. 1: do not keep
  270. 2: keep only if safe-to-copy
  271. 3: keep even if unsafe-to-copy
  272. You can use these definitions:
  273. PNG_HANDLE_CHUNK_AS_DEFAULT 0
  274. PNG_HANDLE_CHUNK_NEVER 1
  275. PNG_HANDLE_CHUNK_IF_SAFE 2
  276. PNG_HANDLE_CHUNK_ALWAYS 3
  277. chunk_list - list of chunks affected (a byte string,
  278. five bytes per chunk, NULL or '\0' if
  279. num_chunks is 0)
  280. num_chunks - number of chunks affected; if 0, all
  281. unknown chunks are affected. If nonzero,
  282. only the chunks in the list are affected
  283. Unknown chunks declared in this way will be saved as raw data onto a
  284. list of png_unknown_chunk structures. If a chunk that is normally
  285. known to libpng is named in the list, it will be handled as unknown,
  286. according to the "keep" directive. If a chunk is named in successive
  287. instances of png_set_keep_unknown_chunks(), the final instance will
  288. take precedence. The IHDR and IEND chunks should not be named in
  289. chunk_list; if they are, libpng will process them normally anyway.
  290. The high-level read interface
  291. At this point there are two ways to proceed; through the high-level
  292. read interface, or through a sequence of low-level read operations.
  293. You can use the high-level interface if (a) you are willing to read
  294. the entire image into memory, and (b) the input transformations
  295. you want to do are limited to the following set:
  296. PNG_TRANSFORM_IDENTITY No transformation
  297. PNG_TRANSFORM_STRIP_16 Strip 16-bit samples to
  298. 8 bits
  299. PNG_TRANSFORM_STRIP_ALPHA Discard the alpha channel
  300. PNG_TRANSFORM_PACKING Expand 1, 2 and 4-bit
  301. samples to bytes
  302. PNG_TRANSFORM_PACKSWAP Change order of packed
  303. pixels to LSB first
  304. PNG_TRANSFORM_EXPAND Perform set_expand()
  305. PNG_TRANSFORM_INVERT_MONO Invert monochrome images
  306. PNG_TRANSFORM_SHIFT Normalize pixels to the
  307. sBIT depth
  308. PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
  309. to BGRA
  310. PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
  311. to AG
  312. PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
  313. to transparency
  314. PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
  315. (This excludes setting a background color, doing gamma transformation,
  316. dithering, and setting filler.) If this is the case, simply do this:
  317. png_read_png(png_ptr, info_ptr, png_transforms, NULL)
  318. where png_transforms is an integer containing the logical OR of
  319. some set of transformation flags. This call is equivalent to png_read_info(),
  320. followed the set of transformations indicated by the transform mask,
  321. then png_read_image(), and finally png_read_end().
  322. (The final parameter of this call is not yet used. Someday it might point
  323. to transformation parameters required by some future input transform.)
  324. You must use png_transforms and not call any png_set_transform() functions
  325. when you use png_read_png().
  326. After you have called png_read_png(), you can retrieve the image data
  327. with
  328. row_pointers = png_get_rows(png_ptr, info_ptr);
  329. where row_pointers is an array of pointers to the pixel data for each row:
  330. png_bytep row_pointers[height];
  331. If you know your image size and pixel size ahead of time, you can allocate
  332. row_pointers prior to calling png_read_png() with
  333. if (height > PNG_UINT_32_MAX/png_sizeof(png_byte))
  334. png_error (png_ptr,
  335. "Image is too tall to process in memory");
  336. if (width > PNG_UINT_32_MAX/pixel_size)
  337. png_error (png_ptr,
  338. "Image is too wide to process in memory");
  339. row_pointers = png_malloc(png_ptr,
  340. height*png_sizeof(png_bytep));
  341. for (int i=0; i<height, i++)
  342. row_pointers[i]=png_malloc(png_ptr,
  343. width*pixel_size);
  344. png_set_rows(png_ptr, info_ptr, &row_pointers);
  345. Alternatively you could allocate your image in one big block and define
  346. row_pointers[i] to point into the proper places in your block.
  347. If you use png_set_rows(), the application is responsible for freeing
  348. row_pointers (and row_pointers[i], if they were separately allocated).
  349. If you don't allocate row_pointers ahead of time, png_read_png() will
  350. do it, and it'll be free'ed when you call png_destroy_*().
  351. The low-level read interface
  352. If you are going the low-level route, you are now ready to read all
  353. the file information up to the actual image data. You do this with a
  354. call to png_read_info().
  355. png_read_info(png_ptr, info_ptr);
  356. This will process all chunks up to but not including the image data.
  357. Querying the info structure
  358. Functions are used to get the information from the info_ptr once it
  359. has been read. Note that these fields may not be completely filled
  360. in until png_read_end() has read the chunk data following the image.
  361. png_get_IHDR(png_ptr, info_ptr, &width, &height,
  362. &bit_depth, &color_type, &interlace_type,
  363. &compression_type, &filter_method);
  364. width - holds the width of the image
  365. in pixels (up to 2^31).
  366. height - holds the height of the image
  367. in pixels (up to 2^31).
  368. bit_depth - holds the bit depth of one of the
  369. image channels. (valid values are
  370. 1, 2, 4, 8, 16 and depend also on
  371. the color_type. See also
  372. significant bits (sBIT) below).
  373. color_type - describes which color/alpha channels
  374. are present.
  375. PNG_COLOR_TYPE_GRAY
  376. (bit depths 1, 2, 4, 8, 16)
  377. PNG_COLOR_TYPE_GRAY_ALPHA
  378. (bit depths 8, 16)
  379. PNG_COLOR_TYPE_PALETTE
  380. (bit depths 1, 2, 4, 8)
  381. PNG_COLOR_TYPE_RGB
  382. (bit_depths 8, 16)
  383. PNG_COLOR_TYPE_RGB_ALPHA
  384. (bit_depths 8, 16)
  385. PNG_COLOR_MASK_PALETTE
  386. PNG_COLOR_MASK_COLOR
  387. PNG_COLOR_MASK_ALPHA
  388. filter_method - (must be PNG_FILTER_TYPE_BASE
  389. for PNG 1.0, and can also be
  390. PNG_INTRAPIXEL_DIFFERENCING if
  391. the PNG datastream is embedded in
  392. a MNG-1.0 datastream)
  393. compression_type - (must be PNG_COMPRESSION_TYPE_BASE
  394. for PNG 1.0)
  395. interlace_type - (PNG_INTERLACE_NONE or
  396. PNG_INTERLACE_ADAM7)
  397. Any or all of interlace_type, compression_type, of
  398. filter_method can be NULL if you are
  399. not interested in their values.
  400. channels = png_get_channels(png_ptr, info_ptr);
  401. channels - number of channels of info for the
  402. color type (valid values are 1 (GRAY,
  403. PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
  404. 4 (RGB_ALPHA or RGB + filler byte))
  405. rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  406. rowbytes - number of bytes needed to hold a row
  407. signature = png_get_signature(png_ptr, info_ptr);
  408. signature - holds the signature read from the
  409. file (if any). The data is kept in
  410. the same offset it would be if the
  411. whole signature were read (i.e. if an
  412. application had already read in 4
  413. bytes of signature before starting
  414. libpng, the remaining 4 bytes would
  415. be in signature[4] through signature[7]
  416. (see png_set_sig_bytes())).
  417. width = png_get_image_width(png_ptr,
  418. info_ptr);
  419. height = png_get_image_height(png_ptr,
  420. info_ptr);
  421. bit_depth = png_get_bit_depth(png_ptr,
  422. info_ptr);
  423. color_type = png_get_color_type(png_ptr,
  424. info_ptr);
  425. filter_method = png_get_filter_type(png_ptr,
  426. info_ptr);
  427. compression_type = png_get_compression_type(png_ptr,
  428. info_ptr);
  429. interlace_type = png_get_interlace_type(png_ptr,
  430. info_ptr);
  431. These are also important, but their validity depends on whether the chunk
  432. has been read. The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
  433. png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
  434. data has been read, or zero if it is missing. The parameters to the
  435. png_get_<chunk> are set directly if they are simple data types, or a pointer
  436. into the info_ptr is returned for any complex types.
  437. png_get_PLTE(png_ptr, info_ptr, &palette,
  438. &num_palette);
  439. palette - the palette for the file
  440. (array of png_color)
  441. num_palette - number of entries in the palette
  442. png_get_gAMA(png_ptr, info_ptr, &gamma);
  443. gamma - the gamma the file is written
  444. at (PNG_INFO_gAMA)
  445. png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
  446. srgb_intent - the rendering intent (PNG_INFO_sRGB)
  447. The presence of the sRGB chunk
  448. means that the pixel data is in the
  449. sRGB color space. This chunk also
  450. implies specific values of gAMA and
  451. cHRM.
  452. png_get_iCCP(png_ptr, info_ptr, &name,
  453. &compression_type, &profile, &proflen);
  454. name - The profile name.
  455. compression - The compression type; always
  456. PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
  457. You may give NULL to this argument to
  458. ignore it.
  459. profile - International Color Consortium color
  460. profile data. May contain NULs.
  461. proflen - length of profile data in bytes.
  462. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  463. sig_bit - the number of significant bits for
  464. (PNG_INFO_sBIT) each of the gray,
  465. red, green, and blue channels,
  466. whichever are appropriate for the
  467. given color type (png_color_16)
  468. png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
  469. &trans_values);
  470. trans - array of transparent entries for
  471. palette (PNG_INFO_tRNS)
  472. trans_values - graylevel or color sample values of
  473. the single transparent color for
  474. non-paletted images (PNG_INFO_tRNS)
  475. num_trans - number of transparent entries
  476. (PNG_INFO_tRNS)
  477. png_get_hIST(png_ptr, info_ptr, &hist);
  478. (PNG_INFO_hIST)
  479. hist - histogram of palette (array of
  480. png_uint_16)
  481. png_get_tIME(png_ptr, info_ptr, &mod_time);
  482. mod_time - time image was last modified
  483. (PNG_VALID_tIME)
  484. png_get_bKGD(png_ptr, info_ptr, &background);
  485. background - background color (PNG_VALID_bKGD)
  486. valid 16-bit red, green and blue
  487. values, regardless of color_type
  488. num_comments = png_get_text(png_ptr, info_ptr,
  489. &text_ptr, &num_text);
  490. num_comments - number of comments
  491. text_ptr - array of png_text holding image
  492. comments
  493. text_ptr[i].compression - type of compression used
  494. on "text" PNG_TEXT_COMPRESSION_NONE
  495. PNG_TEXT_COMPRESSION_zTXt
  496. PNG_ITXT_COMPRESSION_NONE
  497. PNG_ITXT_COMPRESSION_zTXt
  498. text_ptr[i].key - keyword for comment. Must contain
  499. 1-79 characters.
  500. text_ptr[i].text - text comments for current
  501. keyword. Can be empty.
  502. text_ptr[i].text_length - length of text string,
  503. after decompression, 0 for iTXt
  504. text_ptr[i].itxt_length - length of itxt string,
  505. after decompression, 0 for tEXt/zTXt
  506. text_ptr[i].lang - language of comment (empty
  507. string for unknown).
  508. text_ptr[i].lang_key - keyword in UTF-8
  509. (empty string for unknown).
  510. num_text - number of comments (same as
  511. num_comments; you can put NULL here
  512. to avoid the duplication)
  513. Note while png_set_text() will accept text, language,
  514. and translated keywords that can be NULL pointers, the
  515. structure returned by png_get_text will always contain
  516. regular zero-terminated C strings. They might be
  517. empty strings but they will never be NULL pointers.
  518. num_spalettes = png_get_sPLT(png_ptr, info_ptr,
  519. &palette_ptr);
  520. palette_ptr - array of palette structures holding
  521. contents of one or more sPLT chunks
  522. read.
  523. num_spalettes - number of sPLT chunks read.
  524. png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
  525. &unit_type);
  526. offset_x - positive offset from the left edge
  527. of the screen
  528. offset_y - positive offset from the top edge
  529. of the screen
  530. unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
  531. png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
  532. &unit_type);
  533. res_x - pixels/unit physical resolution in
  534. x direction
  535. res_y - pixels/unit physical resolution in
  536. x direction
  537. unit_type - PNG_RESOLUTION_UNKNOWN,
  538. PNG_RESOLUTION_METER
  539. png_get_sCAL(png_ptr, info_ptr, &unit, &width,
  540. &height)
  541. unit - physical scale units (an integer)
  542. width - width of a pixel in physical scale units
  543. height - height of a pixel in physical scale units
  544. (width and height are doubles)
  545. png_get_sCAL_s(png_ptr, info_ptr, &unit, &width,
  546. &height)
  547. unit - physical scale units (an integer)
  548. width - width of a pixel in physical scale units
  549. height - height of a pixel in physical scale units
  550. (width and height are strings like "2.54")
  551. num_unknown_chunks = png_get_unknown_chunks(png_ptr,
  552. info_ptr, &unknowns)
  553. unknowns - array of png_unknown_chunk
  554. structures holding unknown chunks
  555. unknowns[i].name - name of unknown chunk
  556. unknowns[i].data - data of unknown chunk
  557. unknowns[i].size - size of unknown chunk's data
  558. unknowns[i].location - position of chunk in file
  559. The value of "i" corresponds to the order in which the
  560. chunks were read from the PNG file or inserted with the
  561. png_set_unknown_chunks() function.
  562. The data from the pHYs chunk can be retrieved in several convenient
  563. forms:
  564. res_x = png_get_x_pixels_per_meter(png_ptr,
  565. info_ptr)
  566. res_y = png_get_y_pixels_per_meter(png_ptr,
  567. info_ptr)
  568. res_x_and_y = png_get_pixels_per_meter(png_ptr,
  569. info_ptr)
  570. res_x = png_get_x_pixels_per_inch(png_ptr,
  571. info_ptr)
  572. res_y = png_get_y_pixels_per_inch(png_ptr,
  573. info_ptr)
  574. res_x_and_y = png_get_pixels_per_inch(png_ptr,
  575. info_ptr)
  576. aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
  577. info_ptr)
  578. (Each of these returns 0 [signifying "unknown"] if
  579. the data is not present or if res_x is 0;
  580. res_x_and_y is 0 if res_x != res_y)
  581. The data from the oFFs chunk can be retrieved in several convenient
  582. forms:
  583. x_offset = png_get_x_offset_microns(png_ptr, info_ptr);
  584. y_offset = png_get_y_offset_microns(png_ptr, info_ptr);
  585. x_offset = png_get_x_offset_inches(png_ptr, info_ptr);
  586. y_offset = png_get_y_offset_inches(png_ptr, info_ptr);
  587. (Each of these returns 0 [signifying "unknown" if both
  588. x and y are 0] if the data is not present or if the
  589. chunk is present but the unit is the pixel)
  590. For more information, see the png_info definition in png.h and the
  591. PNG specification for chunk contents. Be careful with trusting
  592. rowbytes, as some of the transformations could increase the space
  593. needed to hold a row (expand, filler, gray_to_rgb, etc.).
  594. See png_read_update_info(), below.
  595. A quick word about text_ptr and num_text. PNG stores comments in
  596. keyword/text pairs, one pair per chunk, with no limit on the number
  597. of text chunks, and a 2^31 byte limit on their size. While there are
  598. suggested keywords, there is no requirement to restrict the use to these
  599. strings. It is strongly suggested that keywords and text be sensible
  600. to humans (that's the point), so don't use abbreviations. Non-printing
  601. symbols are not allowed. See the PNG specification for more details.
  602. There is also no requirement to have text after the keyword.
  603. Keywords should be limited to 79 Latin-1 characters without leading or
  604. trailing spaces, but non-consecutive spaces are allowed within the
  605. keyword. It is possible to have the same keyword any number of times.
  606. The text_ptr is an array of png_text structures, each holding a
  607. pointer to a language string, a pointer to a keyword and a pointer to
  608. a text string. The text string, language code, and translated
  609. keyword may be empty or NULL pointers. The keyword/text
  610. pairs are put into the array in the order that they are received.
  611. However, some or all of the text chunks may be after the image, so, to
  612. make sure you have read all the text chunks, don't mess with these
  613. until after you read the stuff after the image. This will be
  614. mentioned again below in the discussion that goes with png_read_end().
  615. Input transformations
  616. After you've read the header information, you can set up the library
  617. to handle any special transformations of the image data. The various
  618. ways to transform the data will be described in the order that they
  619. should occur. This is important, as some of these change the color
  620. type and/or bit depth of the data, and some others only work on
  621. certain color types and bit depths. Even though each transformation
  622. checks to see if it has data that it can do something with, you should
  623. make sure to only enable a transformation if it will be valid for the
  624. data. For example, don't swap red and blue on grayscale data.
  625. The colors used for the background and transparency values should be
  626. supplied in the same format/depth as the current image data. They
  627. are stored in the same format/depth as the image data in a bKGD or tRNS
  628. chunk, so this is what libpng expects for this data. The colors are
  629. transformed to keep in sync with the image data when an application
  630. calls the png_read_update_info() routine (see below).
  631. Data will be decoded into the supplied row buffers packed into bytes
  632. unless the library has been told to transform it into another format.
  633. For example, 4 bit/pixel paletted or grayscale data will be returned
  634. 2 pixels/byte with the leftmost pixel in the high-order bits of the
  635. byte, unless png_set_packing() is called. 8-bit RGB data will be stored
  636. in RGB RGB RGB format unless png_set_filler() or png_set_add_alpha()
  637. is called to insert filler bytes, either before or after each RGB triplet.
  638. 16-bit RGB data will be returned RRGGBB RRGGBB, with the most significant
  639. byte of the color value first, unless png_set_strip_16() is called to
  640. transform it to regular RGB RGB triplets, or png_set_filler() or
  641. png_set_add alpha() is called to insert filler bytes, either before or
  642. after each RRGGBB triplet. Similarly, 8-bit or 16-bit grayscale data can
  643. be modified with
  644. png_set_filler(), png_set_add_alpha(), or png_set_strip_16().
  645. The following code transforms grayscale images of less than 8 to 8 bits,
  646. changes paletted images to RGB, and adds a full alpha channel if there is
  647. transparency information in a tRNS chunk. This is most useful on
  648. grayscale images with bit depths of 2 or 4 or if there is a multiple-image
  649. viewing application that wishes to treat all images in the same way.
  650. if (color_type == PNG_COLOR_TYPE_PALETTE)
  651. png_set_palette_to_rgb(png_ptr);
  652. if (color_type == PNG_COLOR_TYPE_GRAY &&
  653. bit_depth < 8) png_set_gray_1_2_4_to_8(png_ptr);
  654. if (png_get_valid(png_ptr, info_ptr,
  655. PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
  656. These three functions are actually aliases for png_set_expand(), added
  657. in libpng version 1.0.4, with the function names expanded to improve code
  658. readability. In some future version they may actually do different
  659. things.
  660. PNG can have files with 16 bits per channel. If you only can handle
  661. 8 bits per channel, this will strip the pixels down to 8 bit.
  662. if (bit_depth == 16)
  663. png_set_strip_16(png_ptr);
  664. If, for some reason, you don't need the alpha channel on an image,
  665. and you want to remove it rather than combining it with the background
  666. (but the image author certainly had in mind that you *would* combine
  667. it with the background, so that's what you should probably do):
  668. if (color_type & PNG_COLOR_MASK_ALPHA)
  669. png_set_strip_alpha(png_ptr);
  670. In PNG files, the alpha channel in an image
  671. is the level of opacity. If you need the alpha channel in an image to
  672. be the level of transparency instead of opacity, you can invert the
  673. alpha channel (or the tRNS chunk data) after it's read, so that 0 is
  674. fully opaque and 255 (in 8-bit or paletted images) or 65535 (in 16-bit
  675. images) is fully transparent, with
  676. png_set_invert_alpha(png_ptr);
  677. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  678. they can, resulting in, for example, 8 pixels per byte for 1 bit
  679. files. This code expands to 1 pixel per byte without changing the
  680. values of the pixels:
  681. if (bit_depth < 8)
  682. png_set_packing(png_ptr);
  683. PNG files have possible bit depths of 1, 2, 4, 8, and 16. All pixels
  684. stored in a PNG image have been "scaled" or "shifted" up to the next
  685. higher possible bit depth (e.g. from 5 bits/sample in the range [0,31] to
  686. 8 bits/sample in the range [0, 255]). However, it is also possible to
  687. convert the PNG pixel data back to the original bit depth of the image.
  688. This call reduces the pixels back down to the original bit depth:
  689. png_color_8p sig_bit;
  690. if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
  691. png_set_shift(png_ptr, sig_bit);
  692. PNG files store 3-color pixels in red, green, blue order. This code
  693. changes the storage of the pixels to blue, green, red:
  694. if (color_type == PNG_COLOR_TYPE_RGB ||
  695. color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  696. png_set_bgr(png_ptr);
  697. PNG files store RGB pixels packed into 3 or 6 bytes. This code expands them
  698. into 4 or 8 bytes for windowing systems that need them in this format:
  699. if (color_type == PNG_COLOR_TYPE_RGB)
  700. png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
  701. where "filler" is the 8 or 16-bit number to fill with, and the location is
  702. either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
  703. you want the filler before the RGB or after. This transformation
  704. does not affect images that already have full alpha channels. To add an
  705. opaque alpha channel, use filler=0xff or 0xffff and PNG_FILLER_AFTER which
  706. will generate RGBA pixels.
  707. Note that png_set_filler() does not change the color type. If you want
  708. to do that, you can add a true alpha channel with
  709. if (color_type == PNG_COLOR_TYPE_RGB ||
  710. color_type == PNG_COLOR_TYPE_GRAY)
  711. png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER);
  712. where "filler" contains the alpha value to assign to each pixel.
  713. This function was added in libpng-1.2.7.
  714. If you are reading an image with an alpha channel, and you need the
  715. data as ARGB instead of the normal PNG format RGBA:
  716. if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  717. png_set_swap_alpha(png_ptr);
  718. For some uses, you may want a grayscale image to be represented as
  719. RGB. This code will do that conversion:
  720. if (color_type == PNG_COLOR_TYPE_GRAY ||
  721. color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  722. png_set_gray_to_rgb(png_ptr);
  723. Conversely, you can convert an RGB or RGBA image to grayscale or grayscale
  724. with alpha.
  725. if (color_type == PNG_COLOR_TYPE_RGB ||
  726. color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  727. png_set_rgb_to_gray_fixed(png_ptr, error_action,
  728. int red_weight, int green_weight);
  729. error_action = 1: silently do the conversion
  730. error_action = 2: issue a warning if the original
  731. image has any pixel where
  732. red != green or red != blue
  733. error_action = 3: issue an error and abort the
  734. conversion if the original
  735. image has any pixel where
  736. red != green or red != blue
  737. red_weight: weight of red component times 100000
  738. green_weight: weight of green component times 100000
  739. If either weight is negative, default
  740. weights (21268, 71514) are used.
  741. If you have set error_action = 1 or 2, you can
  742. later check whether the image really was gray, after processing
  743. the image rows, with the png_get_rgb_to_gray_status(png_ptr) function.
  744. It will return a png_byte that is zero if the image was gray or
  745. 1 if there were any non-gray pixels. bKGD and sBIT data
  746. will be silently converted to grayscale, using the green channel
  747. data, regardless of the error_action setting.
  748. With red_weight+green_weight<=100000,
  749. the normalized graylevel is computed:
  750. int rw = red_weight * 65536;
  751. int gw = green_weight * 65536;
  752. int bw = 65536 - (rw + gw);
  753. gray = (rw*red + gw*green + bw*blue)/65536;
  754. The default values approximate those recommended in the Charles
  755. Poynton's Color FAQ, <http://www.inforamp.net/~poynton/>
  756. Copyright (c) 1998-01-04 Charles Poynton <poynton at inforamp.net>
  757. Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  758. Libpng approximates this with
  759. Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  760. which can be expressed with integers as
  761. Y = (6969 * R + 23434 * G + 2365 * B)/32768
  762. The calculation is done in a linear colorspace, if the image gamma
  763. is known.
  764. If you have a grayscale and you are using png_set_expand_depth(),
  765. png_set_expand(), or png_set_gray_to_rgb to change to truecolor or to
  766. a higher bit-depth, you must either supply the background color as a gray
  767. value at the original file bit-depth (need_expand = 1) or else supply the
  768. background color as an RGB triplet at the final, expanded bit depth
  769. (need_expand = 0). Similarly, if you are reading a paletted image, you
  770. must either supply the background color as a palette index (need_expand = 1)
  771. or as an RGB triplet that may or may not be in the palette (need_expand = 0).
  772. png_color_16 my_background;
  773. png_color_16p image_background;
  774. if (png_get_bKGD(png_ptr, info_ptr, &image_background))
  775. png_set_background(png_ptr, image_background,
  776. PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
  777. else
  778. png_set_background(png_ptr, &my_background,
  779. PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
  780. The png_set_background() function tells libpng to composite images
  781. with alpha or simple transparency against the supplied background
  782. color. If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
  783. you may use this color, or supply another color more suitable for
  784. the current display (e.g., the background color from a web page). You
  785. need to tell libpng whether the color is in the gamma space of the
  786. display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
  787. (PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
  788. that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
  789. know why anyone would use this, but it's here).
  790. To properly display PNG images on any kind of system, the application needs
  791. to know what the display gamma is. Ideally, the user will know this, and
  792. the application will allow them to set it. One method of allowing the user
  793. to set the display gamma separately for each system is to check for a
  794. SCREEN_GAMMA or DISPLAY_GAMMA environment variable, which will hopefully be
  795. correctly set.
  796. Note that display_gamma is the overall gamma correction required to produce
  797. pleasing results, which depends on the lighting conditions in the surrounding
  798. environment. In a dim or brightly lit room, no compensation other than
  799. the physical gamma exponent of the monitor is needed, while in a dark room
  800. a slightly smaller exponent is better.
  801. double gamma, screen_gamma;
  802. if (/* We have a user-defined screen
  803. gamma value */)
  804. {
  805. screen_gamma = user_defined_screen_gamma;
  806. }
  807. /* One way that applications can share the same
  808. screen gamma value */
  809. else if ((gamma_str = getenv("SCREEN_GAMMA"))
  810. != NULL)
  811. {
  812. screen_gamma = (double)atof(gamma_str);
  813. }
  814. /* If we don't have another value */
  815. else
  816. {
  817. screen_gamma = 2.2; /* A good guess for a
  818. PC monitor in a bright office or a dim room */
  819. screen_gamma = 2.0; /* A good guess for a
  820. PC monitor in a dark room */
  821. screen_gamma = 1.7 or 1.0; /* A good
  822. guess for Mac systems */
  823. }
  824. The png_set_gamma() function handles gamma transformations of the data.
  825. Pass both the file gamma and the current screen_gamma. If the file does
  826. not have a gamma value, you can pass one anyway if you have an idea what
  827. it is (usually 0.45455 is a good guess for GIF images on PCs). Note
  828. that file gammas are inverted from screen gammas. See the discussions
  829. on gamma in the PNG specification for an excellent description of what
  830. gamma is, and why all applications should support it. It is strongly
  831. recommended that PNG viewers support gamma correction.
  832. if (png_get_gAMA(png_ptr, info_ptr, &gamma))
  833. png_set_gamma(png_ptr, screen_gamma, gamma);
  834. else
  835. png_set_gamma(png_ptr, screen_gamma, 0.45455);
  836. If you need to reduce an RGB file to a paletted file, or if a paletted
  837. file has more entries then will fit on your screen, png_set_dither()
  838. will do that. Note that this is a simple match dither that merely
  839. finds the closest color available. This should work fairly well with
  840. optimized palettes, and fairly badly with linear color cubes. If you
  841. pass a palette that is larger then maximum_colors, the file will
  842. reduce the number of colors in the palette so it will fit into
  843. maximum_colors. If there is a histogram, it will use it to make
  844. more intelligent choices when reducing the palette. If there is no
  845. histogram, it may not do as good a job.
  846. if (color_type & PNG_COLOR_MASK_COLOR)
  847. {
  848. if (png_get_valid(png_ptr, info_ptr,
  849. PNG_INFO_PLTE))
  850. {
  851. png_uint_16p histogram = NULL;
  852. png_get_hIST(png_ptr, info_ptr,
  853. &histogram);
  854. png_set_dither(png_ptr, palette, num_palette,
  855. max_screen_colors, histogram, 1);
  856. }
  857. else
  858. {
  859. png_color std_color_cube[MAX_SCREEN_COLORS] =
  860. { ... colors ... };
  861. png_set_dither(png_ptr, std_color_cube,
  862. MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
  863. NULL,0);
  864. }
  865. }
  866. PNG files describe monochrome as black being zero and white being one.
  867. The following code will reverse this (make black be one and white be
  868. zero):
  869. if (bit_depth == 1 && color_type == PNG_COLOR_TYPE_GRAY)
  870. png_set_invert_mono(png_ptr);
  871. This function can also be used to invert grayscale and gray-alpha images:
  872. if (color_type == PNG_COLOR_TYPE_GRAY ||
  873. color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  874. png_set_invert_mono(png_ptr);
  875. PNG files store 16 bit pixels in network byte order (big-endian,
  876. ie. most significant bits first). This code changes the storage to the
  877. other way (little-endian, i.e. least significant bits first, the
  878. way PCs store them):
  879. if (bit_depth == 16)
  880. png_set_swap(png_ptr);
  881. If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
  882. need to change the order the pixels are packed into bytes, you can use:
  883. if (bit_depth < 8)
  884. png_set_packswap(png_ptr);
  885. Finally, you can write your own transformation function if none of
  886. the existing ones meets your needs. This is done by setting a callback
  887. with
  888. png_set_read_user_transform_fn(png_ptr,
  889. read_transform_fn);
  890. You must supply the function
  891. void read_transform_fn(png_ptr ptr, row_info_ptr
  892. row_info, png_bytep data)
  893. See pngtest.c for a working example. Your function will be called
  894. after all of the other transformations have been processed.
  895. You can also set up a pointer to a user structure for use by your
  896. callback function, and you can inform libpng that your transform
  897. function will change the number of channels or bit depth with the
  898. function
  899. png_set_user_transform_info(png_ptr, user_ptr,
  900. user_depth, user_channels);
  901. The user's application, not libpng, is responsible for allocating and
  902. freeing any memory required for the user structure.
  903. You can retrieve the pointer via the function
  904. png_get_user_transform_ptr(). For example:
  905. voidp read_user_transform_ptr =
  906. png_get_user_transform_ptr(png_ptr);
  907. The last thing to handle is interlacing; this is covered in detail below,
  908. but you must call the function here if you want libpng to handle expansion
  909. of the interlaced image.
  910. number_of_passes = png_set_interlace_handling(png_ptr);
  911. After setting the transformations, libpng can update your png_info
  912. structure to reflect any transformations you've requested with this
  913. call. This is most useful to update the info structure's rowbytes
  914. field so you can use it to allocate your image memory. This function
  915. will also update your palette with the correct screen_gamma and
  916. background if these have been given with the calls above.
  917. png_read_update_info(png_ptr, info_ptr);
  918. After you call png_read_update_info(), you can allocate any
  919. memory you need to hold the image. The row data is simply
  920. raw byte data for all forms of images. As the actual allocation
  921. varies among applications, no example will be given. If you
  922. are allocating one large chunk, you will need to build an
  923. array of pointers to each row, as it will be needed for some
  924. of the functions below.
  925. Reading image data
  926. After you've allocated memory, you can read the image data.
  927. The simplest way to do this is in one function call. If you are
  928. allocating enough memory to hold the whole image, you can just
  929. call png_read_image() and libpng will read in all the image data
  930. and put it in the memory area supplied. You will need to pass in
  931. an array of pointers to each row.
  932. This function automatically handles interlacing, so you don't need
  933. to call png_set_interlace_handling() or call this function multiple
  934. times, or any of that other stuff necessary with png_read_rows().
  935. png_read_image(png_ptr, row_pointers);
  936. where row_pointers is:
  937. png_bytep row_pointers[height];
  938. You can point to void or char or whatever you use for pixels.
  939. If you don't want to read in the whole image at once, you can
  940. use png_read_rows() instead. If there is no interlacing (check
  941. interlace_type == PNG_INTERLACE_NONE), this is simple:
  942. png_read_rows(png_ptr, row_pointers, NULL,
  943. number_of_rows);
  944. where row_pointers is the same as in the png_read_image() call.
  945. If you are doing this just one row at a time, you can do this with
  946. a single row_pointer instead of an array of row_pointers:
  947. png_bytep row_pointer = row;
  948. png_read_row(png_ptr, row_pointer, NULL);
  949. If the file is interlaced (interlace_type != 0 in the IHDR chunk), things
  950. get somewhat harder. The only current (PNG Specification version 1.2)
  951. interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7)
  952. is a somewhat complicated 2D interlace scheme, known as Adam7, that
  953. breaks down an image into seven smaller images of varying size, based
  954. on an 8x8 grid.
  955. libpng can fill out those images or it can give them to you "as is".
  956. If you want them filled out, there are two ways to do that. The one
  957. mentioned in the PNG specification is to expand each pixel to cover
  958. those pixels that have not been read yet (the "rectangle" method).
  959. This results in a blocky image for the first pass, which gradually
  960. smooths out as more pixels are read. The other method is the "sparkle"
  961. method, where pixels are drawn only in their final locations, with the
  962. rest of the image remaining whatever colors they were initialized to
  963. before the start of the read. The first method usually looks better,
  964. but tends to be slower, as there are more pixels to put in the rows.
  965. If you don't want libpng to handle the interlacing details, just call
  966. png_read_rows() seven times to read in all seven images. Each of the
  967. images is a valid image by itself, or they can all be combined on an
  968. 8x8 grid to form a single image (although if you intend to combine them
  969. you would be far better off using the libpng interlace handling).
  970. The first pass will return an image 1/8 as wide as the entire image
  971. (every 8th column starting in column 0) and 1/8 as high as the original
  972. (every 8th row starting in row 0), the second will be 1/8 as wide
  973. (starting in column 4) and 1/8 as high (also starting in row 0). The
  974. third pass will be 1/4 as wide (every 4th pixel starting in column 0) and
  975. 1/8 as high (every 8th row starting in row 4), and the fourth pass will
  976. be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
  977. and every 4th row starting in row 0). The fifth pass will return an
  978. image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
  979. while the sixth pass will be 1/2 as wide and 1/2 as high as the original
  980. (starting in column 1 and row 0). The seventh and final pass will be as
  981. wide as the original, and 1/2 as high, containing all of the odd
  982. numbered scanlines. Phew!
  983. If you want libpng to expand the images, call this before calling
  984. png_start_read_image() or png_read_update_info():
  985. if (interlace_type == PNG_INTERLACE_ADAM7)
  986. number_of_passes
  987. = png_set_interlace_handling(png_ptr);
  988. This will return the number of passes needed. Currently, this
  989. is seven, but may change if another interlace type is added.
  990. This function can be called even if the file is not interlaced,
  991. where it will return one pass.
  992. If you are not going to display the image after each pass, but are
  993. going to wait until the entire image is read in, use the sparkle
  994. effect. This effect is faster and the end result of either method
  995. is exactly the same. If you are planning on displaying the image
  996. after each pass, the "rectangle" effect is generally considered the
  997. better looking one.
  998. If you only want the "sparkle" effect, just call png_read_rows() as
  999. normal, with the third parameter NULL. Make sure you make pass over
  1000. the image number_of_passes times, and you don't change the data in the
  1001. rows between calls. You can change the locations of the data, just
  1002. not the data. Each pass only writes the pixels appropriate for that
  1003. pass, and assumes the data from previous passes is still valid.
  1004. png_read_rows(png_ptr, row_pointers, NULL,
  1005. number_of_rows);
  1006. If you only want the first effect (the rectangles), do the same as
  1007. before except pass the row buffer in the third parameter, and leave
  1008. the second parameter NULL.
  1009. png_read_rows(png_ptr, NULL, row_pointers,
  1010. number_of_rows);
  1011. Finishing a sequential read
  1012. After you are finished reading the image through either the high- or
  1013. low-level interfaces, you can finish reading the file. If you are
  1014. interested in comments or time, which may be stored either before or
  1015. after the image data, you should pass the separate png_info struct if
  1016. you want to keep the comments from before and after the image
  1017. separate. If you are not interested, you can pass NULL.
  1018. png_read_end(png_ptr, end_info);
  1019. When you are done, you can free all memory allocated by libpng like this:
  1020. png_destroy_read_struct(&png_ptr, &info_ptr,
  1021. &end_info);
  1022. It is also possible to individually free the info_ptr members that
  1023. point to libpng-allocated storage with the following function:
  1024. png_free_data(png_ptr, info_ptr, mask, seq)
  1025. mask - identifies data to be freed, a mask
  1026. containing the logical OR of one or
  1027. more of
  1028. PNG_FREE_PLTE, PNG_FREE_TRNS,
  1029. PNG_FREE_HIST, PNG_FREE_ICCP,
  1030. PNG_FREE_PCAL, PNG_FREE_ROWS,
  1031. PNG_FREE_SCAL, PNG_FREE_SPLT,
  1032. PNG_FREE_TEXT, PNG_FREE_UNKN,
  1033. or simply PNG_FREE_ALL
  1034. seq - sequence number of item to be freed
  1035. (-1 for all items)
  1036. This function may be safely called when the relevant storage has
  1037. already been freed, or has not yet been allocated, or was allocated
  1038. by the user and not by libpng, and will in those
  1039. cases do nothing. The "seq" parameter is ignored if only one item
  1040. of the selected data type, such as PLTE, is allowed. If "seq" is not
  1041. -1, and multiple items are allowed for the data type identified in
  1042. the mask, such as text or sPLT, only the n'th item in the structure
  1043. is freed, where n is "seq".
  1044. The default behavior is only to free data that was allocated internally
  1045. by libpng. This can be changed, so that libpng will not free the data,
  1046. or so that it will free data that was allocated by the user with png_malloc()
  1047. or png_zalloc() and passed in via a png_set_*() function, with
  1048. png_data_freer(png_ptr, info_ptr, freer, mask)
  1049. mask - which data elements are affected
  1050. same choices as in png_free_data()
  1051. freer - one of
  1052. PNG_DESTROY_WILL_FREE_DATA
  1053. PNG_SET_WILL_FREE_DATA
  1054. PNG_USER_WILL_FREE_DATA
  1055. This function only affects data that has already been allocated.
  1056. You can call this function after reading the PNG data but before calling
  1057. any png_set_*() functions, to control whether the user or the png_set_*()
  1058. function is responsible for freeing any existing data that might be present,
  1059. and again after the png_set_*() functions to control whether the user
  1060. or png_destroy_*() is supposed to free the data. When the user assumes
  1061. responsibility for libpng-allocated data, the application must use
  1062. png_free() to free it, and when the user transfers responsibility to libpng
  1063. for data that the user has allocated, the user must have used png_malloc()
  1064. or png_zalloc() to allocate it.
  1065. If you allocated your row_pointers in a single block, as suggested above in
  1066. the description of the high level read interface, you must not transfer
  1067. responsibility for freeing it to the png_set_rows or png_read_destroy function,
  1068. because they would also try to free the individual row_pointers[i].
  1069. If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
  1070. separately, do not transfer responsibility for freeing text_ptr to libpng,
  1071. because when libpng fills a png_text structure it combines these members with
  1072. the key member, and png_free_data() will free only text_ptr.key. Similarly,
  1073. if you transfer responsibility for free'ing text_ptr from libpng to your
  1074. application, your application must not separately free those members.
  1075. The png_free_data() function will turn off the "valid" flag for anything
  1076. it frees. If you need to turn the flag off for a chunk that was freed by your
  1077. application instead of by libpng, you can use
  1078. png_set_invalid(png_ptr, info_ptr, mask);
  1079. mask - identifies the chunks to be made invalid,
  1080. containing the logical OR of one or
  1081. more of
  1082. PNG_INFO_gAMA, PNG_INFO_sBIT,
  1083. PNG_INFO_cHRM, PNG_INFO_PLTE,
  1084. PNG_INFO_tRNS, PNG_INFO_bKGD,
  1085. PNG_INFO_hIST, PNG_INFO_pHYs,
  1086. PNG_INFO_oFFs, PNG_INFO_tIME,
  1087. PNG_INFO_pCAL, PNG_INFO_sRGB,
  1088. PNG_INFO_iCCP, PNG_INFO_sPLT,
  1089. PNG_INFO_sCAL, PNG_INFO_IDAT
  1090. For a more compact example of reading a PNG image, see the file example.c.
  1091. Reading PNG files progressively
  1092. The progressive reader is slightly different then the non-progressive
  1093. reader. Instead of calling png_read_info(), png_read_rows(), and
  1094. png_read_end(), you make one call to png_process_data(), which calls
  1095. callbacks when it has the info, a row, or the end of the image. You
  1096. set up these callbacks with png_set_progressive_read_fn(). You don't
  1097. have to worry about the input/output functions of libpng, as you are
  1098. giving the library the data directly in png_process_data(). I will
  1099. assume that you have read the section on reading PNG files above,
  1100. so I will only highlight the differences (although I will show
  1101. all of the code).
  1102. png_structp png_ptr;
  1103. png_infop info_ptr;
  1104. /* An example code fragment of how you would
  1105. initialize the progressive reader in your
  1106. application. */
  1107. int
  1108. initialize_png_reader()
  1109. {
  1110. png_ptr = png_create_read_struct
  1111. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  1112. user_error_fn, user_warning_fn);
  1113. if (!png_ptr)
  1114. return (ERROR);
  1115. info_ptr = png_create_info_struct(png_ptr);
  1116. if (!info_ptr)
  1117. {
  1118. png_destroy_read_struct(&png_ptr, (png_infopp)NULL,
  1119. (png_infopp)NULL);
  1120. return (ERROR);
  1121. }
  1122. if (setjmp(png_jmpbuf(png_ptr)))
  1123. {
  1124. png_destroy_read_struct(&png_ptr, &info_ptr,
  1125. (png_infopp)NULL);
  1126. return (ERROR);
  1127. }
  1128. /* This one's new. You can provide functions
  1129. to be called when the header info is valid,
  1130. when each row is completed, and when the image
  1131. is finished. If you aren't using all functions,
  1132. you can specify NULL parameters. Even when all
  1133. three functions are NULL, you need to call
  1134. png_set_progressive_read_fn(). You can use
  1135. any struct as the user_ptr (cast to a void pointer
  1136. for the function call), and retrieve the pointer
  1137. from inside the callbacks using the function
  1138. png_get_progressive_ptr(png_ptr);
  1139. which will return a void pointer, which you have
  1140. to cast appropriately.
  1141. */
  1142. png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
  1143. info_callback, row_callback, end_callback);
  1144. return 0;
  1145. }
  1146. /* A code fragment that you call as you receive blocks
  1147. of data */
  1148. int
  1149. process_data(png_bytep buffer, png_uint_32 length)
  1150. {
  1151. if (setjmp(png_jmpbuf(png_ptr)))
  1152. {
  1153. png_destroy_read_struct(&png_ptr, &info_ptr,
  1154. (png_infopp)NULL);
  1155. return (ERROR);
  1156. }
  1157. /* This one's new also. Simply give it a chunk
  1158. of data from the file stream (in order, of
  1159. course). On machines with segmented memory
  1160. models machines, don't give it any more than
  1161. 64K. The library seems to run fine with sizes
  1162. of 4K. Although you can give it much less if
  1163. necessary (I assume you can give it chunks of
  1164. 1 byte, I haven't tried less then 256 bytes
  1165. yet). When this function returns, you may
  1166. want to display any rows that were generated
  1167. in the row callback if you don't already do
  1168. so there.
  1169. */
  1170. png_process_data(png_ptr, info_ptr, buffer, length);
  1171. return 0;
  1172. }
  1173. /* This function is called (as set by
  1174. png_set_progressive_read_fn() above) when enough data
  1175. has been supplied so all of the header has been
  1176. read.
  1177. */
  1178. void
  1179. info_callback(png_structp png_ptr, png_infop info)
  1180. {
  1181. /* Do any setup here, including setting any of
  1182. the transformations mentioned in the Reading
  1183. PNG files section. For now, you _must_ call
  1184. either png_start_read_image() or
  1185. png_read_update_info() after all the
  1186. transformations are set (even if you don't set
  1187. any). You may start getting rows before
  1188. png_process_data() returns, so this is your
  1189. last chance to prepare for that.
  1190. */
  1191. }
  1192. /* This function is called when each row of image
  1193. data is complete */
  1194. void
  1195. row_callback(png_structp png_ptr, png_bytep new_row,
  1196. png_uint_32 row_num, int pass)
  1197. {
  1198. /* If the image is interlaced, and you turned
  1199. on the interlace handler, this function will
  1200. be called for every row in every pass. Some
  1201. of these rows will not be changed from the
  1202. previous pass. When the row is not changed,
  1203. the new_row variable will be NULL. The rows
  1204. and passes are called in order, so you don't
  1205. really need the row_num and pass, but I'm
  1206. supplying them because it may make your life
  1207. easier.
  1208. For the non-NULL rows of interlaced images,
  1209. you must call png_progressive_combine_row()
  1210. passing in the row and the old row. You can
  1211. call this function for NULL rows (it will just
  1212. return) and for non-interlaced images (it just
  1213. does the memcpy for you) if it will make the
  1214. code easier. Thus, you can just do this for
  1215. all cases:
  1216. */
  1217. png_progressive_combine_row(png_ptr, old_row,
  1218. new_row);
  1219. /* where old_row is what was displayed for
  1220. previously for the row. Note that the first
  1221. pass (pass == 0, really) will completely cover
  1222. the old row, so the rows do not have to be
  1223. initialized. After the first pass (and only
  1224. for interlaced images), you will have to pass
  1225. the current row, and the function will combine
  1226. the old row and the new row.
  1227. */
  1228. }
  1229. void
  1230. end_callback(png_structp png_ptr, png_infop info)
  1231. {
  1232. /* This function is called after the whole image
  1233. has been read, including any chunks after the
  1234. image (up to and including the IEND). You
  1235. will usually have the same info chunk as you
  1236. had in the header, although some data may have
  1237. been added to the comments and time fields.
  1238. Most people won't do much here, perhaps setting
  1239. a flag that marks the image as finished.
  1240. */
  1241. }
  1242. IV. Writing
  1243. Much of this is very similar to reading. However, everything of
  1244. importance is repeated here, so you won't have to constantly look
  1245. back up in the reading section to understand writing.
  1246. Setup
  1247. You will want to do the I/O initialization before you get into libpng,
  1248. so if it doesn't work, you don't have anything to undo. If you are not
  1249. using the standard I/O functions, you will need to replace them with
  1250. custom writing functions. See the discussion under Customizing libpng.
  1251. FILE *fp = fopen(file_name, "wb");
  1252. if (!fp)
  1253. {
  1254. return (ERROR);
  1255. }
  1256. Next, png_struct and png_info need to be allocated and initialized.
  1257. As these can be both relatively large, you may not want to store these
  1258. on the stack, unless you have stack space to spare. Of course, you
  1259. will want to check if they return NULL. If you are also reading,
  1260. you won't want to name your read structure and your write structure
  1261. both "png_ptr"; you can call them anything you like, such as
  1262. "read_ptr" and "write_ptr". Look at pngtest.c, for example.
  1263. png_structp png_ptr = png_create_write_struct
  1264. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  1265. user_error_fn, user_warning_fn);
  1266. if (!png_ptr)
  1267. return (ERROR);
  1268. png_infop info_ptr = png_create_info_struct(png_ptr);
  1269. if (!info_ptr)
  1270. {
  1271. png_destroy_write_struct(&png_ptr,
  1272. (png_infopp)NULL);
  1273. return (ERROR);
  1274. }
  1275. If you want to use your own memory allocation routines,
  1276. define PNG_USER_MEM_SUPPORTED and use
  1277. png_create_write_struct_2() instead of png_create_write_struct():
  1278. png_structp png_ptr = png_create_write_struct_2
  1279. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  1280. user_error_fn, user_warning_fn, (png_voidp)
  1281. user_mem_ptr, user_malloc_fn, user_free_fn);
  1282. After you have these structures, you will need to set up the
  1283. error handling. When libpng encounters an error, it expects to
  1284. longjmp() back to your routine. Therefore, you will need to call
  1285. setjmp() and pass the png_jmpbuf(png_ptr). If you
  1286. write the file from different routines, you will need to update
  1287. the png_jmpbuf(png_ptr) every time you enter a new routine that will
  1288. call a png_*() function. See your documentation of setjmp/longjmp
  1289. for your compiler for more information on setjmp/longjmp. See
  1290. the discussion on libpng error handling in the Customizing Libpng
  1291. section below for more information on the libpng error handling.
  1292. if (setjmp(png_jmpbuf(png_ptr)))
  1293. {
  1294. png_destroy_write_struct(&png_ptr, &info_ptr);
  1295. fclose(fp);
  1296. return (ERROR);
  1297. }
  1298. ...
  1299. return;
  1300. If you would rather avoid the complexity of setjmp/longjmp issues,
  1301. you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case
  1302. errors will result in a call to PNG_ABORT() which defaults to abort().
  1303. Now you need to set up the output code. The default for libpng is to
  1304. use the C function fwrite(). If you use this, you will need to pass a
  1305. valid FILE * in the function png_init_io(). Be sure that the file is
  1306. opened in binary mode. Again, if you wish to handle writing data in
  1307. another way, see the discussion on libpng I/O handling in the Customizing
  1308. Libpng section below.
  1309. png_init_io(png_ptr, fp);
  1310. Write callbacks
  1311. At this point, you can set up a callback function that will be
  1312. called after each row has been written, which you can use to control
  1313. a progress meter or the like. It's demonstrated in pngtest.c.
  1314. You must supply a function
  1315. void write_row_callback(png_ptr, png_uint_32 row,
  1316. int pass);
  1317. {
  1318. /* put your code here */
  1319. }
  1320. (You can give it another name that you like instead of "write_row_callback")
  1321. To inform libpng about your function, use
  1322. png_set_write_status_fn(png_ptr, write_row_callback);
  1323. You now have the option of modifying how the compression library will
  1324. run. The following functions are mainly for testing, but may be useful
  1325. in some cases, like if you need to write PNG files extremely fast and
  1326. are willing to give up some compression, or if you want to get the
  1327. maximum possible compression at the expense of slower writing. If you
  1328. have no special needs in this area, let the library do what it wants by
  1329. not calling this function at all, as it has been tuned to deliver a good
  1330. speed/compression ratio. The second parameter to png_set_filter() is
  1331. the filter method, for which the only valid values are 0 (as of the
  1332. July 1999 PNG specification, version 1.2) or 64 (if you are writing
  1333. a PNG datastream that is to be embedded in a MNG datastream). The third
  1334. parameter is a flag that indicates which filter type(s) are to be tested
  1335. for each scanline. See the PNG specification for details on the specific filter
  1336. types.
  1337. /* turn on or off filtering, and/or choose
  1338. specific filters. You can use either a single
  1339. PNG_FILTER_VALUE_NAME or the logical OR of one
  1340. or more PNG_FILTER_NAME masks. */
  1341. png_set_filter(png_ptr, 0,
  1342. PNG_FILTER_NONE | PNG_FILTER_VALUE_NONE |
  1343. PNG_FILTER_SUB | PNG_FILTER_VALUE_SUB |
  1344. PNG_FILTER_UP | PNG_FILTER_VALUE_UP |
  1345. PNG_FILTER_AVE | PNG_FILTER_VALUE_AVE |
  1346. PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH|
  1347. PNG_ALL_FILTERS);
  1348. If an application
  1349. wants to start and stop using particular filters during compression,
  1350. it should start out with all of the filters (to ensure that the previous
  1351. row of pixels will be stored in case it's needed later), and then add
  1352. and remove them after the start of compression.
  1353. If you are writing a PNG datastream that is to be embedded in a MNG
  1354. datastream, the second parameter can be either 0 or 64.
  1355. The png_set_compression_*() functions interface to the zlib compression
  1356. library, and should mostly be ignored unless you really know what you are
  1357. doing. The only generally useful call is png_set_compression_level()
  1358. which changes how much time zlib spends on trying to compress the image
  1359. data. See the Compression Library (zlib.h and algorithm.txt, distributed
  1360. with zlib) for details on the compression levels.
  1361. /* set the zlib compression level */
  1362. png_set_compression_level(png_ptr,
  1363. Z_BEST_COMPRESSION);
  1364. /* set other zlib parameters */
  1365. png_set_compression_mem_level(png_ptr, 8);
  1366. png_set_compression_strategy(png_ptr,
  1367. Z_DEFAULT_STRATEGY);
  1368. png_set_compression_window_bits(png_ptr, 15);
  1369. png_set_compression_method(png_ptr, 8);
  1370. png_set_compression_buffer_size(png_ptr, 8192)
  1371. extern PNG_EXPORT(void,png_set_zbuf_size)
  1372. Setting the contents of info for output
  1373. You now need to fill in the png_info structure with all the data you
  1374. wish to write before the actual image. Note that the only thing you
  1375. are allowed to write after the image is the text chunks and the time
  1376. chunk (as of PNG Specification 1.2, anyway). See png_write_end() and
  1377. the latest PNG specification for more information on that. If you
  1378. wish to write them before the image, fill them in now, and flag that
  1379. data as being valid. If you want to wait until after the data, don't
  1380. fill them until png_write_end(). For all the fields in png_info and
  1381. their data types, see png.h. For explanations of what the fields
  1382. contain, see the PNG specification.
  1383. Some of the more important parts of the png_info are:
  1384. png_set_IHDR(png_ptr, info_ptr, width, height,
  1385. bit_depth, color_type, interlace_type,
  1386. compression_type, filter_method)
  1387. width - holds the width of the image
  1388. in pixels (up to 2^31).
  1389. height - holds the height of the image
  1390. in pixels (up to 2^31).
  1391. bit_depth - holds the bit depth of one of the
  1392. image channels.
  1393. (valid values are 1, 2, 4, 8, 16
  1394. and depend also on the
  1395. color_type. See also significant
  1396. bits (sBIT) below).
  1397. color_type - describes which color/alpha
  1398. channels are present.
  1399. PNG_COLOR_TYPE_GRAY
  1400. (bit depths 1, 2, 4, 8, 16)
  1401. PNG_COLOR_TYPE_GRAY_ALPHA
  1402. (bit depths 8, 16)
  1403. PNG_COLOR_TYPE_PALETTE
  1404. (bit depths 1, 2, 4, 8)
  1405. PNG_COLOR_TYPE_RGB
  1406. (bit_depths 8, 16)
  1407. PNG_COLOR_TYPE_RGB_ALPHA
  1408. (bit_depths 8, 16)
  1409. PNG_COLOR_MASK_PALETTE
  1410. PNG_COLOR_MASK_COLOR
  1411. PNG_COLOR_MASK_ALPHA
  1412. interlace_type - PNG_INTERLACE_NONE or
  1413. PNG_INTERLACE_ADAM7
  1414. compression_type - (must be
  1415. PNG_COMPRESSION_TYPE_DEFAULT)
  1416. filter_method - (must be PNG_FILTER_TYPE_DEFAULT
  1417. or, if you are writing a PNG to
  1418. be embedded in a MNG datastream,
  1419. can also be
  1420. PNG_INTRAPIXEL_DIFFERENCING)
  1421. png_set_PLTE(png_ptr, info_ptr, palette,
  1422. num_palette);
  1423. palette - the palette for the file
  1424. (array of png_color)
  1425. num_palette - number of entries in the palette
  1426. png_set_gAMA(png_ptr, info_ptr, gamma);
  1427. gamma - the gamma the image was created
  1428. at (PNG_INFO_gAMA)
  1429. png_set_sRGB(png_ptr, info_ptr, srgb_intent);
  1430. srgb_intent - the rendering intent
  1431. (PNG_INFO_sRGB) The presence of
  1432. the sRGB chunk means that the pixel
  1433. data is in the sRGB color space.
  1434. This chunk also implies specific
  1435. values of gAMA and cHRM. Rendering
  1436. intent is the CSS-1 property that
  1437. has been defined by the International
  1438. Color Consortium
  1439. (http://www.color.org).
  1440. It can be one of
  1441. PNG_sRGB_INTENT_SATURATION,
  1442. PNG_sRGB_INTENT_PERCEPTUAL,
  1443. PNG_sRGB_INTENT_ABSOLUTE, or
  1444. PNG_sRGB_INTENT_RELATIVE.
  1445. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
  1446. srgb_intent);
  1447. srgb_intent - the rendering intent
  1448. (PNG_INFO_sRGB) The presence of the
  1449. sRGB chunk means that the pixel
  1450. data is in the sRGB color space.
  1451. This function also causes gAMA and
  1452. cHRM chunks with the specific values
  1453. that are consistent with sRGB to be
  1454. written.
  1455. png_set_iCCP(png_ptr, info_ptr, name, compression_type,
  1456. profile, proflen);
  1457. name - The profile name.
  1458. compression - The compression type; always
  1459. PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
  1460. You may give NULL to this argument to
  1461. ignore it.
  1462. profile - International Color Consortium color
  1463. profile data. May contain NULs.
  1464. proflen - length of profile data in bytes.
  1465. png_set_sBIT(png_ptr, info_ptr, sig_bit);
  1466. sig_bit - the number of significant bits for
  1467. (PNG_INFO_sBIT) each of the gray, red,
  1468. green, and blue channels, whichever are
  1469. appropriate for the given color type
  1470. (png_color_16)
  1471. png_set_tRNS(png_ptr, info_ptr, trans, num_trans,
  1472. trans_values);
  1473. trans - array of transparent entries for
  1474. palette (PNG_INFO_tRNS)
  1475. trans_values - graylevel or color sample values of
  1476. the single transparent color for
  1477. non-paletted images (PNG_INFO_tRNS)
  1478. num_trans - number of transparent entries
  1479. (PNG_INFO_tRNS)
  1480. png_set_hIST(png_ptr, info_ptr, hist);
  1481. (PNG_INFO_hIST)
  1482. hist - histogram of palette (array of
  1483. png_uint_16)
  1484. png_set_tIME(png_ptr, info_ptr, mod_time);
  1485. mod_time - time image was last modified
  1486. (PNG_VALID_tIME)
  1487. png_set_bKGD(png_ptr, info_ptr, background);
  1488. background - background color (PNG_VALID_bKGD)
  1489. png_set_text(png_ptr, info_ptr, text_ptr, num_text);
  1490. text_ptr - array of png_text holding image
  1491. comments
  1492. text_ptr[i].compression - type of compression used
  1493. on "text" PNG_TEXT_COMPRESSION_NONE
  1494. PNG_TEXT_COMPRESSION_zTXt
  1495. PNG_ITXT_COMPRESSION_NONE
  1496. PNG_ITXT_COMPRESSION_zTXt
  1497. text_ptr[i].key - keyword for comment. Must contain
  1498. 1-79 characters.
  1499. text_ptr[i].text - text comments for current
  1500. keyword. Can be NULL or empty.
  1501. text_ptr[i].text_length - length of text string,
  1502. after decompression, 0 for iTXt
  1503. text_ptr[i].itxt_length - length of itxt string,
  1504. after decompression, 0 for tEXt/zTXt
  1505. text_ptr[i].lang - language of comment (NULL or
  1506. empty for unknown).
  1507. text_ptr[i].translated_keyword - keyword in UTF-8 (NULL
  1508. or empty for unknown).
  1509. num_text - number of comments
  1510. png_set_sPLT(png_ptr, info_ptr, &palette_ptr,
  1511. num_spalettes);
  1512. palette_ptr - array of png_sPLT_struct structures
  1513. to be added to the list of palettes
  1514. in the info structure.
  1515. num_spalettes - number of palette structures to be
  1516. added.
  1517. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
  1518. unit_type);
  1519. offset_x - positive offset from the left
  1520. edge of the screen
  1521. offset_y - positive offset from the top
  1522. edge of the screen
  1523. unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
  1524. png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
  1525. unit_type);
  1526. res_x - pixels/unit physical resolution
  1527. in x direction
  1528. res_y - pixels/unit physical resolution
  1529. in y direction
  1530. unit_type - PNG_RESOLUTION_UNKNOWN,
  1531. PNG_RESOLUTION_METER
  1532. png_set_sCAL(png_ptr, info_ptr, unit, width, height)
  1533. unit - physical scale units (an integer)
  1534. width - width of a pixel in physical scale units
  1535. height - height of a pixel in physical scale units
  1536. (width and height are doubles)
  1537. png_set_sCAL_s(png_ptr, info_ptr, unit, width, height)
  1538. unit - physical scale units (an integer)
  1539. width - width of a pixel in physical scale units
  1540. height - height of a pixel in physical scale units
  1541. (width and height are strings like "2.54")
  1542. png_set_unknown_chunks(png_ptr, info_ptr, &unknowns,
  1543. num_unknowns)
  1544. unknowns - array of png_unknown_chunk
  1545. structures holding unknown chunks
  1546. unknowns[i].name - name of unknown chunk
  1547. unknowns[i].data - data of unknown chunk
  1548. unknowns[i].size - size of unknown chunk's data
  1549. unknowns[i].location - position to write chunk in file
  1550. 0: do not write chunk
  1551. PNG_HAVE_IHDR: before PLTE
  1552. PNG_HAVE_PLTE: before IDAT
  1553. PNG_AFTER_IDAT: after IDAT
  1554. The "location" member is set automatically according to
  1555. what part of the output file has already been written.
  1556. You can change its value after calling png_set_unknown_chunks()
  1557. as demonstrated in pngtest.c. Within each of the "locations",
  1558. the chunks are sequenced according to their position in the
  1559. structure (that is, the value of "i", which is the order in which
  1560. the chunk was either read from the input file or defined with
  1561. png_set_unknown_chunks).
  1562. A quick word about text and num_text. text is an array of png_text
  1563. structures. num_text is the number of valid structures in the array.
  1564. Each png_text structure holds a language code, a keyword, a text value,
  1565. and a compression type.
  1566. The compression types have the same valid numbers as the compression
  1567. types of the image data. Currently, the only valid number is zero.
  1568. However, you can store text either compressed or uncompressed, unlike
  1569. images, which always have to be compressed. So if you don't want the
  1570. text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
  1571. Because tEXt and zTXt chunks don't have a language field, if you
  1572. specify PNG_TEXT_COMPRESSION_NONE or PNG_TEXT_COMPRESSION_zTXt
  1573. any language code or translated keyword will not be written out.
  1574. Until text gets around 1000 bytes, it is not worth compressing it.
  1575. After the text has been written out to the file, the compression type
  1576. is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
  1577. so that it isn't written out again at the end (in case you are calling
  1578. png_write_end() with the same struct.
  1579. The keywords that are given in the PNG Specification are:
  1580. Title Short (one line) title or
  1581. caption for image
  1582. Author Name of image's creator
  1583. Description Description of image (possibly long)
  1584. Copyright Copyright notice
  1585. Creation Time Time of original image creation
  1586. (usually RFC 1123 format, see below)
  1587. Software Software used to create the image
  1588. Disclaimer Legal disclaimer
  1589. Warning Warning of nature of content
  1590. Source Device used to create the image
  1591. Comment Miscellaneous comment; conversion
  1592. from other image format
  1593. The keyword-text pairs work like this. Keywords should be short
  1594. simple descriptions of what the comment is about. Some typical
  1595. keywords are found in the PNG specification, as is some recommendations
  1596. on keywords. You can repeat keywords in a file. You can even write
  1597. some text before the image and some after. For example, you may want
  1598. to put a description of the image before the image, but leave the
  1599. disclaimer until after, so viewers working over modem connections
  1600. don't have to wait for the disclaimer to go over the modem before
  1601. they start seeing the image. Finally, keywords should be full
  1602. words, not abbreviations. Keywords and text are in the ISO 8859-1
  1603. (Latin-1) character set (a superset of regular ASCII) and can not
  1604. contain NUL characters, and should not contain control or other
  1605. unprintable characters. To make the comments widely readable, stick
  1606. with basic ASCII, and avoid machine specific character set extensions
  1607. like the IBM-PC character set. The keyword must be present, but
  1608. you can leave off the text string on non-compressed pairs.
  1609. Compressed pairs must have a text string, as only the text string
  1610. is compressed anyway, so the compression would be meaningless.
  1611. PNG supports modification time via the png_time structure. Two
  1612. conversion routines are provided, png_convert_from_time_t() for
  1613. time_t and png_convert_from_struct_tm() for struct tm. The
  1614. time_t routine uses gmtime(). You don't have to use either of
  1615. these, but if you wish to fill in the png_time structure directly,
  1616. you should provide the time in universal time (GMT) if possible
  1617. instead of your local time. Note that the year number is the full
  1618. year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and
  1619. that months start with 1.
  1620. If you want to store the time of the original image creation, you should
  1621. use a plain tEXt chunk with the "Creation Time" keyword. This is
  1622. necessary because the "creation time" of a PNG image is somewhat vague,
  1623. depending on whether you mean the PNG file, the time the image was
  1624. created in a non-PNG format, a still photo from which the image was
  1625. scanned, or possibly the subject matter itself. In order to facilitate
  1626. machine-readable dates, it is recommended that the "Creation Time"
  1627. tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"),
  1628. although this isn't a requirement. Unlike the tIME chunk, the
  1629. "Creation Time" tEXt chunk is not expected to be automatically changed
  1630. by the software. To facilitate the use of RFC 1123 dates, a function
  1631. png_convert_to_rfc1123(png_timep) is provided to convert from PNG
  1632. time to an RFC 1123 format string.
  1633. Writing unknown chunks
  1634. You can use the png_set_unknown_chunks function to queue up chunks
  1635. for writing. You give it a chunk name, raw data, and a size; that's
  1636. all there is to it. The chunks will be written by the next following
  1637. png_write_info_before_PLTE, png_write_info, or png_write_end function.
  1638. Any chunks previously read into the info structure's unknown-chunk
  1639. list will also be written out in a sequence that satisfies the PNG
  1640. specification's ordering rules.
  1641. The high-level write interface
  1642. At this point there are two ways to proceed; through the high-level
  1643. write interface, or through a sequence of low-level write operations.
  1644. You can use the high-level interface if your image data is present
  1645. in the info structure. All defined output
  1646. transformations are permitted, enabled by the following masks.
  1647. PNG_TRANSFORM_IDENTITY No transformation
  1648. PNG_TRANSFORM_PACKING Pack 1, 2 and 4-bit samples
  1649. PNG_TRANSFORM_PACKSWAP Change order of packed
  1650. pixels to LSB first
  1651. PNG_TRANSFORM_INVERT_MONO Invert monochrome images
  1652. PNG_TRANSFORM_SHIFT Normalize pixels to the
  1653. sBIT depth
  1654. PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA
  1655. to BGRA
  1656. PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA
  1657. to AG
  1658. PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity
  1659. to transparency
  1660. PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples
  1661. PNG_TRANSFORM_STRIP_FILLER Strip out filler bytes.
  1662. If you have valid image data in the info structure (you can use
  1663. png_set_rows() to put image data in the info structure), simply do this:
  1664. png_write_png(png_ptr, info_ptr, png_transforms, NULL)
  1665. where png_transforms is an integer containing the logical OR of some set of
  1666. transformation flags. This call is equivalent to png_write_info(),
  1667. followed the set of transformations indicated by the transform mask,
  1668. then png_write_image(), and finally png_write_end().
  1669. (The final parameter of this call is not yet used. Someday it might point
  1670. to transformation parameters required by some future output transform.)
  1671. You must use png_transforms and not call any png_set_transform() functions
  1672. when you use png_write_png().
  1673. The low-level write interface
  1674. If you are going the low-level route instead, you are now ready to
  1675. write all the file information up to the actual image data. You do
  1676. this with a call to png_write_info().
  1677. png_write_info(png_ptr, info_ptr);
  1678. Note that there is one transformation you may need to do before
  1679. png_write_info(). In PNG files, the alpha channel in an image is the
  1680. level of opacity. If your data is supplied as a level of
  1681. transparency, you can invert the alpha channel before you write it, so
  1682. that 0 is fully transparent and 255 (in 8-bit or paletted images) or
  1683. 65535 (in 16-bit images) is fully opaque, with
  1684. png_set_invert_alpha(png_ptr);
  1685. This must appear before png_write_info() instead of later with the
  1686. other transformations because in the case of paletted images the tRNS
  1687. chunk data has to be inverted before the tRNS chunk is written. If
  1688. your image is not a paletted image, the tRNS data (which in such cases
  1689. represents a single color to be rendered as transparent) won't need to
  1690. be changed, and you can safely do this transformation after your
  1691. png_write_info() call.
  1692. If you need to write a private chunk that you want to appear before
  1693. the PLTE chunk when PLTE is present, you can write the PNG info in
  1694. two steps, and insert code to write your own chunk between them:
  1695. png_write_info_before_PLTE(png_ptr, info_ptr);
  1696. png_set_unknown_chunks(png_ptr, info_ptr, ...);
  1697. png_write_info(png_ptr, info_ptr);
  1698. After you've written the file information, you can set up the library
  1699. to handle any special transformations of the image data. The various
  1700. ways to transform the data will be described in the order that they
  1701. should occur. This is important, as some of these change the color
  1702. type and/or bit depth of the data, and some others only work on
  1703. certain color types and bit depths. Even though each transformation
  1704. checks to see if it has data that it can do something with, you should
  1705. make sure to only enable a transformation if it will be valid for the
  1706. data. For example, don't swap red and blue on grayscale data.
  1707. PNG files store RGB pixels packed into 3 or 6 bytes. This code tells
  1708. the library to strip input data that has 4 or 8 bytes per pixel down
  1709. to 3 or 6 bytes (or strip 2 or 4-byte grayscale+filler data to 1 or 2
  1710. bytes per pixel).
  1711. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  1712. where the 0 is unused, and the location is either PNG_FILLER_BEFORE or
  1713. PNG_FILLER_AFTER, depending upon whether the filler byte in the pixel
  1714. is stored XRGB or RGBX.
  1715. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  1716. they can, resulting in, for example, 8 pixels per byte for 1 bit files.
  1717. If the data is supplied at 1 pixel per byte, use this code, which will
  1718. correctly pack the pixels into a single byte:
  1719. png_set_packing(png_ptr);
  1720. PNG files reduce possible bit depths to 1, 2, 4, 8, and 16. If your
  1721. data is of another bit depth, you can write an sBIT chunk into the
  1722. file so that decoders can recover the original data if desired.
  1723. /* Set the true bit depth of the image data */
  1724. if (color_type & PNG_COLOR_MASK_COLOR)
  1725. {
  1726. sig_bit.red = true_bit_depth;
  1727. sig_bit.green = true_bit_depth;
  1728. sig_bit.blue = true_bit_depth;
  1729. }
  1730. else
  1731. {
  1732. sig_bit.gray = true_bit_depth;
  1733. }
  1734. if (color_type & PNG_COLOR_MASK_ALPHA)
  1735. {
  1736. sig_bit.alpha = true_bit_depth;
  1737. }
  1738. png_set_sBIT(png_ptr, info_ptr, &sig_bit);
  1739. If the data is stored in the row buffer in a bit depth other than
  1740. one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG),
  1741. this will scale the values to appear to be the correct bit depth as
  1742. is required by PNG.
  1743. png_set_shift(png_ptr, &sig_bit);
  1744. PNG files store 16 bit pixels in network byte order (big-endian,
  1745. ie. most significant bits first). This code would be used if they are
  1746. supplied the other way (little-endian, i.e. least significant bits
  1747. first, the way PCs store them):
  1748. if (bit_depth > 8)
  1749. png_set_swap(png_ptr);
  1750. If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
  1751. need to change the order the pixels are packed into bytes, you can use:
  1752. if (bit_depth < 8)
  1753. png_set_packswap(png_ptr);
  1754. PNG files store 3 color pixels in red, green, blue order. This code
  1755. would be used if they are supplied as blue, green, red:
  1756. png_set_bgr(png_ptr);
  1757. PNG files describe monochrome as black being zero and white being
  1758. one. This code would be used if the pixels are supplied with this reversed
  1759. (black being one and white being zero):
  1760. png_set_invert_mono(png_ptr);
  1761. Finally, you can write your own transformation function if none of
  1762. the existing ones meets your needs. This is done by setting a callback
  1763. with
  1764. png_set_write_user_transform_fn(png_ptr,
  1765. write_transform_fn);
  1766. You must supply the function
  1767. void write_transform_fn(png_ptr ptr, row_info_ptr
  1768. row_info, png_bytep data)
  1769. See pngtest.c for a working example. Your function will be called
  1770. before any of the other transformations are processed.
  1771. You can also set up a pointer to a user structure for use by your
  1772. callback function.
  1773. png_set_user_transform_info(png_ptr, user_ptr, 0, 0);
  1774. The user_channels and user_depth parameters of this function are ignored
  1775. when writing; you can set them to zero as shown.
  1776. You can retrieve the pointer via the function png_get_user_transform_ptr().
  1777. For example:
  1778. voidp write_user_transform_ptr =
  1779. png_get_user_transform_ptr(png_ptr);
  1780. It is possible to have libpng flush any pending output, either manually,
  1781. or automatically after a certain number of lines have been written. To
  1782. flush the output stream a single time call:
  1783. png_write_flush(png_ptr);
  1784. and to have libpng flush the output stream periodically after a certain
  1785. number of scanlines have been written, call:
  1786. png_set_flush(png_ptr, nrows);
  1787. Note that the distance between rows is from the last time png_write_flush()
  1788. was called, or the first row of the image if it has never been called.
  1789. So if you write 50 lines, and then png_set_flush 25, it will flush the
  1790. output on the next scanline, and every 25 lines thereafter, unless
  1791. png_write_flush() is called before 25 more lines have been written.
  1792. If nrows is too small (less than about 10 lines for a 640 pixel wide
  1793. RGB image) the image compression may decrease noticeably (although this
  1794. may be acceptable for real-time applications). Infrequent flushing will
  1795. only degrade the compression performance by a few percent over images
  1796. that do not use flushing.
  1797. Writing the image data
  1798. That's it for the transformations. Now you can write the image data.
  1799. The simplest way to do this is in one function call. If you have the
  1800. whole image in memory, you can just call png_write_image() and libpng
  1801. will write the image. You will need to pass in an array of pointers to
  1802. each row. This function automatically handles interlacing, so you don't
  1803. need to call png_set_interlace_handling() or call this function multiple
  1804. times, or any of that other stuff necessary with png_write_rows().
  1805. png_write_image(png_ptr, row_pointers);
  1806. where row_pointers is:
  1807. png_byte *row_pointers[height];
  1808. You can point to void or char or whatever you use for pixels.
  1809. If you don't want to write the whole image at once, you can
  1810. use png_write_rows() instead. If the file is not interlaced,
  1811. this is simple:
  1812. png_write_rows(png_ptr, row_pointers,
  1813. number_of_rows);
  1814. row_pointers is the same as in the png_write_image() call.
  1815. If you are just writing one row at a time, you can do this with
  1816. a single row_pointer instead of an array of row_pointers:
  1817. png_bytep row_pointer = row;
  1818. png_write_row(png_ptr, row_pointer);
  1819. When the file is interlaced, things can get a good deal more
  1820. complicated. The only currently (as of the PNG Specification
  1821. version 1.2, dated July 1999) defined interlacing scheme for PNG files
  1822. is the "Adam7" interlace scheme, that breaks down an
  1823. image into seven smaller images of varying size. libpng will build
  1824. these images for you, or you can do them yourself. If you want to
  1825. build them yourself, see the PNG specification for details of which
  1826. pixels to write when.
  1827. If you don't want libpng to handle the interlacing details, just
  1828. use png_set_interlace_handling() and call png_write_rows() the
  1829. correct number of times to write all seven sub-images.
  1830. If you want libpng to build the sub-images, call this before you start
  1831. writing any rows:
  1832. number_of_passes =
  1833. png_set_interlace_handling(png_ptr);
  1834. This will return the number of passes needed. Currently, this
  1835. is seven, but may change if another interlace type is added.
  1836. Then write the complete image number_of_passes times.
  1837. png_write_rows(png_ptr, row_pointers,
  1838. number_of_rows);
  1839. As some of these rows are not used, and thus return immediately,
  1840. you may want to read about interlacing in the PNG specification,
  1841. and only update the rows that are actually used.
  1842. Finishing a sequential write
  1843. After you are finished writing the image, you should finish writing
  1844. the file. If you are interested in writing comments or time, you should
  1845. pass an appropriately filled png_info pointer. If you are not interested,
  1846. you can pass NULL.
  1847. png_write_end(png_ptr, info_ptr);
  1848. When you are done, you can free all memory used by libpng like this:
  1849. png_destroy_write_struct(&png_ptr, &info_ptr);
  1850. It is also possible to individually free the info_ptr members that
  1851. point to libpng-allocated storage with the following function:
  1852. png_free_data(png_ptr, info_ptr, mask, seq)
  1853. mask - identifies data to be freed, a mask
  1854. containing the logical OR of one or
  1855. more of
  1856. PNG_FREE_PLTE, PNG_FREE_TRNS,
  1857. PNG_FREE_HIST, PNG_FREE_ICCP,
  1858. PNG_FREE_PCAL, PNG_FREE_ROWS,
  1859. PNG_FREE_SCAL, PNG_FREE_SPLT,
  1860. PNG_FREE_TEXT, PNG_FREE_UNKN,
  1861. or simply PNG_FREE_ALL
  1862. seq - sequence number of item to be freed
  1863. (-1 for all items)
  1864. This function may be safely called when the relevant storage has
  1865. already been freed, or has not yet been allocated, or was allocated
  1866. by the user and not by libpng, and will in those
  1867. cases do nothing. The "seq" parameter is ignored if only one item
  1868. of the selected data type, such as PLTE, is allowed. If "seq" is not
  1869. -1, and multiple items are allowed for the data type identified in
  1870. the mask, such as text or sPLT, only the n'th item in the structure
  1871. is freed, where n is "seq".
  1872. If you allocated data such as a palette that you passed
  1873. in to libpng with png_set_*, you must not free it until just before the call to
  1874. png_destroy_write_struct().
  1875. The default behavior is only to free data that was allocated internally
  1876. by libpng. This can be changed, so that libpng will not free the data,
  1877. or so that it will free data that was allocated by the user with png_malloc()
  1878. or png_zalloc() and passed in via a png_set_*() function, with
  1879. png_data_freer(png_ptr, info_ptr, freer, mask)
  1880. mask - which data elements are affected
  1881. same choices as in png_free_data()
  1882. freer - one of
  1883. PNG_DESTROY_WILL_FREE_DATA
  1884. PNG_SET_WILL_FREE_DATA
  1885. PNG_USER_WILL_FREE_DATA
  1886. For example, to transfer responsibility for some data from a read structure
  1887. to a write structure, you could use
  1888. png_data_freer(read_ptr, read_info_ptr,
  1889. PNG_USER_WILL_FREE_DATA,
  1890. PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
  1891. png_data_freer(write_ptr, write_info_ptr,
  1892. PNG_DESTROY_WILL_FREE_DATA,
  1893. PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
  1894. thereby briefly reassigning responsibility for freeing to the user but
  1895. immediately afterwards reassigning it once more to the write_destroy
  1896. function. Having done this, it would then be safe to destroy the read
  1897. structure and continue to use the PLTE, tRNS, and hIST data in the write
  1898. structure.
  1899. This function only affects data that has already been allocated.
  1900. You can call this function before calling after the png_set_*() functions
  1901. to control whether the user or png_destroy_*() is supposed to free the data.
  1902. When the user assumes responsibility for libpng-allocated data, the
  1903. application must use
  1904. png_free() to free it, and when the user transfers responsibility to libpng
  1905. for data that the user has allocated, the user must have used png_malloc()
  1906. or png_zalloc() to allocate it.
  1907. If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
  1908. separately, do not transfer responsibility for freeing text_ptr to libpng,
  1909. because when libpng fills a png_text structure it combines these members with
  1910. the key member, and png_free_data() will free only text_ptr.key. Similarly,
  1911. if you transfer responsibility for free'ing text_ptr from libpng to your
  1912. application, your application must not separately free those members.
  1913. For a more compact example of writing a PNG image, see the file example.c.
  1914. V. Modifying/Customizing libpng:
  1915. There are three issues here. The first is changing how libpng does
  1916. standard things like memory allocation, input/output, and error handling.
  1917. The second deals with more complicated things like adding new chunks,
  1918. adding new transformations, and generally changing how libpng works.
  1919. Both of those are compile-time issues; that is, they are generally
  1920. determined at the time the code is written, and there is rarely a need
  1921. to provide the user with a means of changing them. The third is a
  1922. run-time issue: choosing between and/or tuning one or more alternate
  1923. versions of computationally intensive routines; specifically, optimized
  1924. assembly-language (and therefore compiler- and platform-dependent)
  1925. versions.
  1926. Memory allocation, input/output, and error handling
  1927. All of the memory allocation, input/output, and error handling in libpng
  1928. goes through callbacks that are user-settable. The default routines are
  1929. in pngmem.c, pngrio.c, pngwio.c, and pngerror.c, respectively. To change
  1930. these functions, call the appropriate png_set_*_fn() function.
  1931. Memory allocation is done through the functions png_malloc()
  1932. and png_free(). These currently just call the standard C functions. If
  1933. your pointers can't access more then 64K at a time, you will want to set
  1934. MAXSEG_64K in zlib.h. Since it is unlikely that the method of handling
  1935. memory allocation on a platform will change between applications, these
  1936. functions must be modified in the library at compile time. If you prefer
  1937. to use a different method of allocating and freeing data, you can use
  1938. png_create_read_struct_2() or png_create_write_struct_2() to register
  1939. your own functions as described above.
  1940. These functions also provide a void pointer that can be retrieved via
  1941. mem_ptr=png_get_mem_ptr(png_ptr);
  1942. Your replacement memory functions must have prototypes as follows:
  1943. png_voidp malloc_fn(png_structp png_ptr,
  1944. png_size_t size);
  1945. void free_fn(png_structp png_ptr, png_voidp ptr);
  1946. Your malloc_fn() must return NULL in case of failure. The png_malloc()
  1947. function will normally call png_error() if it receives a NULL from the
  1948. system memory allocator or from your replacement malloc_fn().
  1949. Input/Output in libpng is done through png_read() and png_write(),
  1950. which currently just call fread() and fwrite(). The FILE * is stored in
  1951. png_struct and is initialized via png_init_io(). If you wish to change
  1952. the method of I/O, the library supplies callbacks that you can set
  1953. through the function png_set_read_fn() and png_set_write_fn() at run
  1954. time, instead of calling the png_init_io() function. These functions
  1955. also provide a void pointer that can be retrieved via the function
  1956. png_get_io_ptr(). For example:
  1957. png_set_read_fn(png_structp read_ptr,
  1958. voidp read_io_ptr, png_rw_ptr read_data_fn)
  1959. png_set_write_fn(png_structp write_ptr,
  1960. voidp write_io_ptr, png_rw_ptr write_data_fn,
  1961. png_flush_ptr output_flush_fn);
  1962. voidp read_io_ptr = png_get_io_ptr(read_ptr);
  1963. voidp write_io_ptr = png_get_io_ptr(write_ptr);
  1964. The replacement I/O functions must have prototypes as follows:
  1965. void user_read_data(png_structp png_ptr,
  1966. png_bytep data, png_size_t length);
  1967. void user_write_data(png_structp png_ptr,
  1968. png_bytep data, png_size_t length);
  1969. void user_flush_data(png_structp png_ptr);
  1970. Supplying NULL for the read, write, or flush functions sets them back
  1971. to using the default C stream functions. It is an error to read from
  1972. a write stream, and vice versa.
  1973. Error handling in libpng is done through png_error() and png_warning().
  1974. Errors handled through png_error() are fatal, meaning that png_error()
  1975. should never return to its caller. Currently, this is handled via
  1976. setjmp() and longjmp() (unless you have compiled libpng with
  1977. PNG_SETJMP_NOT_SUPPORTED, in which case it is handled via PNG_ABORT()),
  1978. but you could change this to do things like exit() if you should wish.
  1979. On non-fatal errors, png_warning() is called
  1980. to print a warning message, and then control returns to the calling code.
  1981. By default png_error() and png_warning() print a message on stderr via
  1982. fprintf() unless the library is compiled with PNG_NO_CONSOLE_IO defined
  1983. (because you don't want the messages) or PNG_NO_STDIO defined (because
  1984. fprintf() isn't available). If you wish to change the behavior of the error
  1985. functions, you will need to set up your own message callbacks. These
  1986. functions are normally supplied at the time that the png_struct is created.
  1987. It is also possible to redirect errors and warnings to your own replacement
  1988. functions after png_create_*_struct() has been called by calling:
  1989. png_set_error_fn(png_structp png_ptr,
  1990. png_voidp error_ptr, png_error_ptr error_fn,
  1991. png_error_ptr warning_fn);
  1992. png_voidp error_ptr = png_get_error_ptr(png_ptr);
  1993. If NULL is supplied for either error_fn or warning_fn, then the libpng
  1994. default function will be used, calling fprintf() and/or longjmp() if a
  1995. problem is encountered. The replacement error functions should have
  1996. parameters as follows:
  1997. void user_error_fn(png_structp png_ptr,
  1998. png_const_charp error_msg);
  1999. void user_warning_fn(png_structp png_ptr,
  2000. png_const_charp warning_msg);
  2001. The motivation behind using setjmp() and longjmp() is the C++ throw and
  2002. catch exception handling methods. This makes the code much easier to write,
  2003. as there is no need to check every return code of every function call.
  2004. However, there are some uncertainties about the status of local variables
  2005. after a longjmp, so the user may want to be careful about doing anything after
  2006. setjmp returns non-zero besides returning itself. Consult your compiler
  2007. documentation for more details. For an alternative approach, you may wish
  2008. to use the "cexcept" facility (see http://cexcept.sourceforge.net).
  2009. Custom chunks
  2010. If you need to read or write custom chunks, you may need to get deeper
  2011. into the libpng code. The library now has mechanisms for storing
  2012. and writing chunks of unknown type; you can even declare callbacks
  2013. for custom chunks. Hoewver, this may not be good enough if the
  2014. library code itself needs to know about interactions between your
  2015. chunk and existing `intrinsic' chunks.
  2016. If you need to write a new intrinsic chunk, first read the PNG
  2017. specification. Acquire a first level of
  2018. understanding of how it works. Pay particular attention to the
  2019. sections that describe chunk names, and look at how other chunks were
  2020. designed, so you can do things similarly. Second, check out the
  2021. sections of libpng that read and write chunks. Try to find a chunk
  2022. that is similar to yours and use it as a template. More details can
  2023. be found in the comments inside the code. It is best to handle unknown
  2024. chunks in a generic method, via callback functions, instead of by
  2025. modifying libpng functions.
  2026. If you wish to write your own transformation for the data, look through
  2027. the part of the code that does the transformations, and check out some of
  2028. the simpler ones to get an idea of how they work. Try to find a similar
  2029. transformation to the one you want to add and copy off of it. More details
  2030. can be found in the comments inside the code itself.
  2031. Configuring for 16 bit platforms
  2032. You will want to look into zconf.h to tell zlib (and thus libpng) that
  2033. it cannot allocate more then 64K at a time. Even if you can, the memory
  2034. won't be accessible. So limit zlib and libpng to 64K by defining MAXSEG_64K.
  2035. Configuring for DOS
  2036. For DOS users who only have access to the lower 640K, you will
  2037. have to limit zlib's memory usage via a png_set_compression_mem_level()
  2038. call. See zlib.h or zconf.h in the zlib library for more information.
  2039. Configuring for Medium Model
  2040. Libpng's support for medium model has been tested on most of the popular
  2041. compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
  2042. defined, and FAR gets defined to far in pngconf.h, and you should be
  2043. all set. Everything in the library (except for zlib's structure) is
  2044. expecting far data. You must use the typedefs with the p or pp on
  2045. the end for pointers (or at least look at them and be careful). Make
  2046. note that the rows of data are defined as png_bytepp, which is an
  2047. unsigned char far * far *.
  2048. Configuring for gui/windowing platforms:
  2049. You will need to write new error and warning functions that use the GUI
  2050. interface, as described previously, and set them to be the error and
  2051. warning functions at the time that png_create_*_struct() is called,
  2052. in order to have them available during the structure initialization.
  2053. They can be changed later via png_set_error_fn(). On some compilers,
  2054. you may also have to change the memory allocators (png_malloc, etc.).
  2055. Configuring for compiler xxx:
  2056. All includes for libpng are in pngconf.h. If you need to add/change/delete
  2057. an include, this is the place to do it. The includes that are not
  2058. needed outside libpng are protected by the PNG_INTERNAL definition,
  2059. which is only defined for those routines inside libpng itself. The
  2060. files in libpng proper only include png.h, which includes pngconf.h.
  2061. Configuring zlib:
  2062. There are special functions to configure the compression. Perhaps the
  2063. most useful one changes the compression level, which currently uses
  2064. input compression values in the range 0 - 9. The library normally
  2065. uses the default compression level (Z_DEFAULT_COMPRESSION = 6). Tests
  2066. have shown that for a large majority of images, compression values in
  2067. the range 3-6 compress nearly as well as higher levels, and do so much
  2068. faster. For online applications it may be desirable to have maximum speed
  2069. (Z_BEST_SPEED = 1). With versions of zlib after v0.99, you can also
  2070. specify no compression (Z_NO_COMPRESSION = 0), but this would create
  2071. files larger than just storing the raw bitmap. You can specify the
  2072. compression level by calling:
  2073. png_set_compression_level(png_ptr, level);
  2074. Another useful one is to reduce the memory level used by the library.
  2075. The memory level defaults to 8, but it can be lowered if you are
  2076. short on memory (running DOS, for example, where you only have 640K).
  2077. Note that the memory level does have an effect on compression; among
  2078. other things, lower levels will result in sections of incompressible
  2079. data being emitted in smaller stored blocks, with a correspondingly
  2080. larger relative overhead of up to 15% in the worst case.
  2081. png_set_compression_mem_level(png_ptr, level);
  2082. The other functions are for configuring zlib. They are not recommended
  2083. for normal use and may result in writing an invalid PNG file. See
  2084. zlib.h for more information on what these mean.
  2085. png_set_compression_strategy(png_ptr,
  2086. strategy);
  2087. png_set_compression_window_bits(png_ptr,
  2088. window_bits);
  2089. png_set_compression_method(png_ptr, method);
  2090. png_set_compression_buffer_size(png_ptr, size);
  2091. Controlling row filtering
  2092. If you want to control whether libpng uses filtering or not, which
  2093. filters are used, and how it goes about picking row filters, you
  2094. can call one of these functions. The selection and configuration
  2095. of row filters can have a significant impact on the size and
  2096. encoding speed and a somewhat lesser impact on the decoding speed
  2097. of an image. Filtering is enabled by default for RGB and grayscale
  2098. images (with and without alpha), but not for paletted images nor
  2099. for any images with bit depths less than 8 bits/pixel.
  2100. The 'method' parameter sets the main filtering method, which is
  2101. currently only '0' in the PNG 1.2 specification. The 'filters'
  2102. parameter sets which filter(s), if any, should be used for each
  2103. scanline. Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
  2104. to turn filtering on and off, respectively.
  2105. Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
  2106. PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
  2107. ORed together with '|' to specify one or more filters to use.
  2108. These filters are described in more detail in the PNG specification.
  2109. If you intend to change the filter type during the course of writing
  2110. the image, you should start with flags set for all of the filters
  2111. you intend to use so that libpng can initialize its internal
  2112. structures appropriately for all of the filter types. (Note that this
  2113. means the first row must always be adaptively filtered, because libpng
  2114. currently does not allocate the filter buffers until png_write_row()
  2115. is called for the first time.)
  2116. filters = PNG_FILTER_NONE | PNG_FILTER_SUB
  2117. PNG_FILTER_UP | PNG_FILTER_AVE |
  2118. PNG_FILTER_PAETH | PNG_ALL_FILTERS;
  2119. png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
  2120. filters);
  2121. The second parameter can also be
  2122. PNG_INTRAPIXEL_DIFFERENCING if you are
  2123. writing a PNG to be embedded in a MNG
  2124. datastream. This parameter must be the
  2125. same as the value of filter_method used
  2126. in png_set_IHDR().
  2127. It is also possible to influence how libpng chooses from among the
  2128. available filters. This is done in one or both of two ways - by
  2129. telling it how important it is to keep the same filter for successive
  2130. rows, and by telling it the relative computational costs of the filters.
  2131. double weights[3] = {1.5, 1.3, 1.1},
  2132. costs[PNG_FILTER_VALUE_LAST] =
  2133. {1.0, 1.3, 1.3, 1.5, 1.7};
  2134. png_set_filter_heuristics(png_ptr,
  2135. PNG_FILTER_HEURISTIC_WEIGHTED, 3,
  2136. weights, costs);
  2137. The weights are multiplying factors that indicate to libpng that the
  2138. row filter should be the same for successive rows unless another row filter
  2139. is that many times better than the previous filter. In the above example,
  2140. if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
  2141. "sum of absolute differences" 1.5 x 1.3 times higher than other filters
  2142. and still be chosen, while the NONE filter could have a sum 1.1 times
  2143. higher than other filters and still be chosen. Unspecified weights are
  2144. taken to be 1.0, and the specified weights should probably be declining
  2145. like those above in order to emphasize recent filters over older filters.
  2146. The filter costs specify for each filter type a relative decoding cost
  2147. to be considered when selecting row filters. This means that filters
  2148. with higher costs are less likely to be chosen over filters with lower
  2149. costs, unless their "sum of absolute differences" is that much smaller.
  2150. The costs do not necessarily reflect the exact computational speeds of
  2151. the various filters, since this would unduly influence the final image
  2152. size.
  2153. Note that the numbers above were invented purely for this example and
  2154. are given only to help explain the function usage. Little testing has
  2155. been done to find optimum values for either the costs or the weights.
  2156. Removing unwanted object code
  2157. There are a bunch of #define's in pngconf.h that control what parts of
  2158. libpng are compiled. All the defines end in _SUPPORTED. If you are
  2159. never going to use a capability, you can change the #define to #undef
  2160. before recompiling libpng and save yourself code and data space, or
  2161. you can turn off individual capabilities with defines that begin with
  2162. PNG_NO_.
  2163. You can also turn all of the transforms and ancillary chunk capabilities
  2164. off en masse with compiler directives that define
  2165. PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS,
  2166. or all four,
  2167. along with directives to turn on any of the capabilities that you do
  2168. want. The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable
  2169. the extra transformations but still leave the library fully capable of reading
  2170. and writing PNG files with all known public chunks
  2171. Use of the PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive
  2172. produces a library that is incapable of reading or writing ancillary chunks.
  2173. If you are not using the progressive reading capability, you can
  2174. turn that off with PNG_NO_PROGRESSIVE_READ (don't confuse
  2175. this with the INTERLACING capability, which you'll still have).
  2176. All the reading and writing specific code are in separate files, so the
  2177. linker should only grab the files it needs. However, if you want to
  2178. make sure, or if you are building a stand alone library, all the
  2179. reading files start with pngr and all the writing files start with
  2180. pngw. The files that don't match either (like png.c, pngtrans.c, etc.)
  2181. are used for both reading and writing, and always need to be included.
  2182. The progressive reader is in pngpread.c
  2183. If you are creating or distributing a dynamically linked library (a .so
  2184. or DLL file), you should not remove or disable any parts of the library,
  2185. as this will cause applications linked with different versions of the
  2186. library to fail if they call functions not available in your library.
  2187. The size of the library itself should not be an issue, because only
  2188. those sections that are actually used will be loaded into memory.
  2189. Requesting debug printout
  2190. The macro definition PNG_DEBUG can be used to request debugging
  2191. printout. Set it to an integer value in the range 0 to 3. Higher
  2192. numbers result in increasing amounts of debugging information. The
  2193. information is printed to the "stderr" file, unless another file
  2194. name is specified in the PNG_DEBUG_FILE macro definition.
  2195. When PNG_DEBUG > 0, the following functions (macros) become available:
  2196. png_debug(level, message)
  2197. png_debug1(level, message, p1)
  2198. png_debug2(level, message, p1, p2)
  2199. in which "level" is compared to PNG_DEBUG to decide whether to print
  2200. the message, "message" is the formatted string to be printed,
  2201. and p1 and p2 are parameters that are to be embedded in the string
  2202. according to printf-style formatting directives. For example,
  2203. png_debug1(2, "foo=%d\n", foo);
  2204. is expanded to
  2205. if(PNG_DEBUG > 2)
  2206. fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
  2207. When PNG_DEBUG is defined but is zero, the macros aren't defined, but you
  2208. can still use PNG_DEBUG to control your own debugging:
  2209. #ifdef PNG_DEBUG
  2210. fprintf(stderr, ...
  2211. #endif
  2212. When PNG_DEBUG = 1, the macros are defined, but only png_debug statements
  2213. having level = 0 will be printed. There aren't any such statements in
  2214. this version of libpng, but if you insert some they will be printed.
  2215. VI. Runtime optimization
  2216. A new feature in libpng 1.2.0 is the ability to dynamically switch between
  2217. standard and optimized versions of some routines. Currently these are
  2218. limited to three computationally intensive tasks when reading PNG files:
  2219. decoding row filters, expanding interlacing, and combining interlaced or
  2220. transparent row data with previous row data. Currently the optimized
  2221. versions are available only for x86 (Intel, AMD, etc.) platforms with
  2222. MMX support, though this may change in future versions. (For example,
  2223. the non-MMX assembler optimizations for zlib might become similarly
  2224. runtime-selectable in future releases, in which case libpng could be
  2225. extended to support them. Alternatively, the compile-time choice of
  2226. floating-point versus integer routines for gamma correction might become
  2227. runtime-selectable.)
  2228. Because such optimizations tend to be very platform- and compiler-dependent,
  2229. both in how they are written and in how they perform, the new runtime code
  2230. in libpng has been written to allow programs to query, enable, and disable
  2231. either specific optimizations or all such optimizations. For example, to
  2232. enable all possible optimizations (bearing in mind that some "optimizations"
  2233. may actually run more slowly in rare cases):
  2234. #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200)
  2235. png_uint_32 mask, flags;
  2236. flags = png_get_asm_flags(png_ptr);
  2237. mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE);
  2238. png_set_asm_flags(png_ptr, flags | mask);
  2239. #endif
  2240. To enable only optimizations relevant to reading PNGs, use PNG_SELECT_READ
  2241. by itself when calling png_get_asm_flagmask(); similarly for optimizing
  2242. only writing. To disable all optimizations:
  2243. #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200)
  2244. flags = png_get_asm_flags(png_ptr);
  2245. mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE);
  2246. png_set_asm_flags(png_ptr, flags & ~mask);
  2247. #endif
  2248. To enable or disable only MMX-related features, use png_get_mmx_flagmask()
  2249. in place of png_get_asm_flagmask(). The mmx version takes one additional
  2250. parameter:
  2251. #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200)
  2252. int selection = PNG_SELECT_READ | PNG_SELECT_WRITE;
  2253. int compilerID;
  2254. mask = png_get_mmx_flagmask(selection, &compilerID);
  2255. #endif
  2256. On return, compilerID will indicate which version of the MMX assembler
  2257. optimizations was compiled. Currently two flavors exist: Microsoft
  2258. Visual C++ (compilerID == 1) and GNU C (a.k.a. gcc/gas, compilerID == 2).
  2259. On non-x86 platforms or on systems compiled without MMX optimizations, a
  2260. value of -1 is used.
  2261. Note that both png_get_asm_flagmask() and png_get_mmx_flagmask() return
  2262. all valid, settable optimization bits for the version of the library that's
  2263. currently in use. In the case of shared (dynamically linked) libraries,
  2264. this may include optimizations that did not exist at the time the code was
  2265. written and compiled. It is also possible, of course, to enable only known,
  2266. specific optimizations; for example:
  2267. #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200)
  2268. flags = PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  2269. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  2270. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  2271. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  2272. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  2273. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ;
  2274. png_set_asm_flags(png_ptr, flags);
  2275. #endif
  2276. This method would enable only the MMX read-optimizations available at the
  2277. time of libpng 1.2.0's release, regardless of whether a later version of
  2278. the DLL were actually being used. (Also note that these functions did not
  2279. exist in versions older than 1.2.0, so any attempt to run a dynamically
  2280. linked app on such an older version would fail.)
  2281. To determine whether the processor supports MMX instructions at all, use
  2282. the png_mmx_support() function:
  2283. #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200)
  2284. mmxsupport = png_mmx_support();
  2285. #endif
  2286. It returns -1 if MMX support is not compiled into libpng, 0 if MMX code
  2287. is compiled but MMX is not supported by the processor, or 1 if MMX support
  2288. is fully available. Note that png_mmx_support(), png_get_mmx_flagmask(),
  2289. and png_get_asm_flagmask() all may be called without allocating and ini-
  2290. tializing any PNG structures (for example, as part of a usage screen or
  2291. "about" box).
  2292. The following code can be used to prevent an application from using the
  2293. thread_unsafe features, even if libpng was built with PNG_THREAD_UNSAFE_OK
  2294. defined:
  2295. #if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) \
  2296. && defined(PNG_THREAD_UNSAFE_OK)
  2297. /* Disable thread-unsafe features of pnggccrd */
  2298. if (png_access_version() >= 10200)
  2299. {
  2300. png_uint_32 mmx_disable_mask = 0;
  2301. png_uint_32 asm_flags;
  2302. mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  2303. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  2304. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  2305. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH );
  2306. asm_flags = png_get_asm_flags(png_ptr);
  2307. png_set_asm_flags(png_ptr, asm_flags & ~mmx_disable_mask);
  2308. }
  2309. #endif
  2310. For more extensive examples of runtime querying, enabling and disabling
  2311. of optimized features, see contrib/gregbook/readpng2.c in the libpng
  2312. source-code distribution.
  2313. VII. MNG support
  2314. The MNG specification (available at http://www.libpng.org/pub/mng) allows
  2315. certain extensions to PNG for PNG images that are embedded in MNG datastreams.
  2316. Libpng can support some of these extensions. To enable them, use the
  2317. png_permit_mng_features() function:
  2318. feature_set = png_permit_mng_features(png_ptr, mask)
  2319. mask is a png_uint_32 containing the logical OR of the
  2320. features you want to enable. These include
  2321. PNG_FLAG_MNG_EMPTY_PLTE
  2322. PNG_FLAG_MNG_FILTER_64
  2323. PNG_ALL_MNG_FEATURES
  2324. feature_set is a png_uint_32 that is the logical AND of
  2325. your mask with the set of MNG features that is
  2326. supported by the version of libpng that you are using.
  2327. It is an error to use this function when reading or writing a standalone
  2328. PNG file with the PNG 8-byte signature. The PNG datastream must be wrapped
  2329. in a MNG datastream. As a minimum, it must have the MNG 8-byte signature
  2330. and the MHDR and MEND chunks. Libpng does not provide support for these
  2331. or any other MNG chunks; your application must provide its own support for
  2332. them. You may wish to consider using libmng (available at
  2333. http://www.libmng.com) instead.
  2334. VIII. Changes to Libpng from version 0.88
  2335. It should be noted that versions of libpng later than 0.96 are not
  2336. distributed by the original libpng author, Guy Schalnat, nor by
  2337. Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
  2338. distributed versions 0.89 through 0.96, but rather by another member
  2339. of the original PNG Group, Glenn Randers-Pehrson. Guy and Andreas are
  2340. still alive and well, but they have moved on to other things.
  2341. The old libpng functions png_read_init(), png_write_init(),
  2342. png_info_init(), png_read_destroy(), and png_write_destroy() have been
  2343. moved to PNG_INTERNAL in version 0.95 to discourage their use. These
  2344. functions will be removed from libpng version 2.0.0.
  2345. The preferred method of creating and initializing the libpng structures is
  2346. via the png_create_read_struct(), png_create_write_struct(), and
  2347. png_create_info_struct() because they isolate the size of the structures
  2348. from the application, allow version error checking, and also allow the
  2349. use of custom error handling routines during the initialization, which
  2350. the old functions do not. The functions png_read_destroy() and
  2351. png_write_destroy() do not actually free the memory that libpng
  2352. allocated for these structs, but just reset the data structures, so they
  2353. can be used instead of png_destroy_read_struct() and
  2354. png_destroy_write_struct() if you feel there is too much system overhead
  2355. allocating and freeing the png_struct for each image read.
  2356. Setting the error callbacks via png_set_message_fn() before
  2357. png_read_init() as was suggested in libpng-0.88 is no longer supported
  2358. because this caused applications that do not use custom error functions
  2359. to fail if the png_ptr was not initialized to zero. It is still possible
  2360. to set the error callbacks AFTER png_read_init(), or to change them with
  2361. png_set_error_fn(), which is essentially the same function, but with a new
  2362. name to force compilation errors with applications that try to use the old
  2363. method.
  2364. Starting with version 1.0.7, you can find out which version of the library
  2365. you are using at run-time:
  2366. png_uint_32 libpng_vn = png_access_version_number();
  2367. The number libpng_vn is constructed from the major version, minor
  2368. version with leading zero, and release number with leading zero,
  2369. (e.g., libpng_vn for version 1.0.7 is 10007).
  2370. You can also check which version of png.h you used when compiling your
  2371. application:
  2372. png_uint_32 application_vn = PNG_LIBPNG_VER;
  2373. IX. Y2K Compliance in libpng
  2374. December 3, 2004
  2375. Since the PNG Development group is an ad-hoc body, we can't make
  2376. an official declaration.
  2377. This is your unofficial assurance that libpng from version 0.71 and
  2378. upward through 1.2.8 are Y2K compliant. It is my belief that earlier
  2379. versions were also Y2K compliant.
  2380. Libpng only has three year fields. One is a 2-byte unsigned integer that
  2381. will hold years up to 65535. The other two hold the date in text
  2382. format, and will hold years up to 9999.
  2383. The integer is
  2384. "png_uint_16 year" in png_time_struct.
  2385. The strings are
  2386. "png_charp time_buffer" in png_struct and
  2387. "near_time_buffer", which is a local character string in png.c.
  2388. There are seven time-related functions:
  2389. png_convert_to_rfc_1123() in png.c
  2390. (formerly png_convert_to_rfc_1152() in error)
  2391. png_convert_from_struct_tm() in pngwrite.c, called
  2392. in pngwrite.c
  2393. png_convert_from_time_t() in pngwrite.c
  2394. png_get_tIME() in pngget.c
  2395. png_handle_tIME() in pngrutil.c, called in pngread.c
  2396. png_set_tIME() in pngset.c
  2397. png_write_tIME() in pngwutil.c, called in pngwrite.c
  2398. All appear to handle dates properly in a Y2K environment. The
  2399. png_convert_from_time_t() function calls gmtime() to convert from system
  2400. clock time, which returns (year - 1900), which we properly convert to
  2401. the full 4-digit year. There is a possibility that applications using
  2402. libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  2403. function, or that they are incorrectly passing only a 2-digit year
  2404. instead of "year - 1900" into the png_convert_from_struct_tm() function,
  2405. but this is not under our control. The libpng documentation has always
  2406. stated that it works with 4-digit years, and the APIs have been
  2407. documented as such.
  2408. The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  2409. integer to hold the year, and can hold years as large as 65535.
  2410. zlib, upon which libpng depends, is also Y2K compliant. It contains
  2411. no date-related code.
  2412. Glenn Randers-Pehrson
  2413. libpng maintainer
  2414. PNG Development Group