pngwrite.c 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449
  1. /* pngwrite.c - general routines to write a PNG file
  2. *
  3. * Copyright (c) 2018-2025 Cosmin Truta
  4. * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  5. * Copyright (c) 1996-1997 Andreas Dilger
  6. * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
  7. *
  8. * This code is released under the libpng license.
  9. * For conditions of distribution and use, see the disclaimer
  10. * and license in png.h
  11. */
  12. #include "pngpriv.h"
  13. #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
  14. # include <errno.h>
  15. #endif /* SIMPLIFIED_WRITE_STDIO */
  16. #ifdef PNG_WRITE_SUPPORTED
  17. #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  18. /* Write out all the unknown chunks for the current given location */
  19. static void
  20. write_unknown_chunks(png_structrp png_ptr, png_const_inforp info_ptr,
  21. unsigned int where)
  22. {
  23. if (info_ptr->unknown_chunks_num != 0)
  24. {
  25. png_const_unknown_chunkp up;
  26. png_debug(5, "writing extra chunks");
  27. for (up = info_ptr->unknown_chunks;
  28. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  29. ++up)
  30. if ((up->location & where) != 0)
  31. {
  32. /* If per-chunk unknown chunk handling is enabled use it, otherwise
  33. * just write the chunks the application has set.
  34. */
  35. #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
  36. int keep = png_handle_as_unknown(png_ptr, up->name);
  37. /* NOTE: this code is radically different from the read side in the
  38. * matter of handling an ancillary unknown chunk. In the read side
  39. * the default behavior is to discard it, in the code below the default
  40. * behavior is to write it. Critical chunks are, however, only
  41. * written if explicitly listed or if the default is set to write all
  42. * unknown chunks.
  43. *
  44. * The default handling is also slightly weird - it is not possible to
  45. * stop the writing of all unsafe-to-copy chunks!
  46. *
  47. * TODO: REVIEW: this would seem to be a bug.
  48. */
  49. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  50. ((up->name[3] & 0x20) /* safe-to-copy overrides everything */ ||
  51. keep == PNG_HANDLE_CHUNK_ALWAYS ||
  52. (keep == PNG_HANDLE_CHUNK_AS_DEFAULT &&
  53. png_ptr->unknown_default == PNG_HANDLE_CHUNK_ALWAYS)))
  54. #endif
  55. {
  56. /* TODO: review, what is wrong with a zero length unknown chunk? */
  57. if (up->size == 0)
  58. png_warning(png_ptr, "Writing zero-length unknown chunk");
  59. png_write_chunk(png_ptr, up->name, up->data, up->size);
  60. }
  61. }
  62. }
  63. }
  64. #endif /* WRITE_UNKNOWN_CHUNKS */
  65. /* Writes all the PNG information. This is the suggested way to use the
  66. * library. If you have a new chunk to add, make a function to write it,
  67. * and put it in the correct location here. If you want the chunk written
  68. * after the image data, put it in png_write_end(). I strongly encourage
  69. * you to supply a PNG_INFO_<chunk> flag, and check info_ptr->valid before
  70. * writing the chunk, as that will keep the code from breaking if you want
  71. * to just write a plain PNG file. If you have long comments, I suggest
  72. * writing them in png_write_end(), and compressing them.
  73. */
  74. void PNGAPI
  75. png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr)
  76. {
  77. png_debug(1, "in png_write_info_before_PLTE");
  78. if (png_ptr == NULL || info_ptr == NULL)
  79. return;
  80. if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
  81. {
  82. /* Write PNG signature */
  83. png_write_sig(png_ptr);
  84. #ifdef PNG_MNG_FEATURES_SUPPORTED
  85. if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \
  86. png_ptr->mng_features_permitted != 0)
  87. {
  88. png_warning(png_ptr,
  89. "MNG features are not allowed in a PNG datastream");
  90. png_ptr->mng_features_permitted = 0;
  91. }
  92. #endif
  93. /* Write IHDR information. */
  94. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  95. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  96. info_ptr->filter_type,
  97. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  98. info_ptr->interlace_type
  99. #else
  100. 0
  101. #endif
  102. );
  103. /* The rest of these check to see if the valid field has the appropriate
  104. * flag set, and if it does, writes the chunk.
  105. *
  106. * 1.6.0: COLORSPACE support controls the writing of these chunks too, and
  107. * the chunks will be written if the WRITE routine is there and
  108. * information * is available in the COLORSPACE. (See
  109. * png_colorspace_sync_info in png.c for where the valid flags get set.)
  110. *
  111. * Under certain circumstances the colorspace can be invalidated without
  112. * syncing the info_struct 'valid' flags; this happens if libpng detects
  113. * an error and calls png_error while the color space is being set, yet
  114. * the application continues writing the PNG. So check the 'invalid'
  115. * flag here too.
  116. */
  117. #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  118. /* Write unknown chunks first; PNG v3 establishes a precedence order
  119. * for colourspace chunks. It is certain therefore that new
  120. * colourspace chunks will have a precedence and very likely it will be
  121. * higher than all known so far. Writing the unknown chunks here is
  122. * most likely to present the chunks in the most convenient order.
  123. *
  124. * FUTURE: maybe write chunks in the order the app calls png_set_chnk
  125. * to give the app control.
  126. */
  127. write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
  128. #endif
  129. #ifdef PNG_WRITE_sBIT_SUPPORTED
  130. /* PNG v3: a streaming app will need to see this before cICP because
  131. * the information is helpful in handling HLG encoding (which is
  132. * natively 10 bits but gets expanded to 16 in PNG.)
  133. *
  134. * The app shouldn't care about the order ideally, but it might have
  135. * no choice. In PNG v3, apps are allowed to reject PNGs where the
  136. * APNG chunks are out of order so it behooves libpng to be nice here.
  137. */
  138. if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
  139. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  140. #endif
  141. /* PNG v3: the July 2004 version of the TR introduced the concept of colour
  142. * space priority. As above it therefore behooves libpng to write the colour
  143. * space chunks in the priority order so that a streaming app need not buffer
  144. * them.
  145. *
  146. * PNG v3: Chunks mDCV and cLLI provide ancillary information for the
  147. * interpretation of the colourspace chunkgs but do not require support for
  148. * those chunks so are outside the "COLORSPACE" check but before the write of
  149. * the colourspace chunks themselves.
  150. */
  151. #ifdef PNG_WRITE_cLLI_SUPPORTED
  152. if ((info_ptr->valid & PNG_INFO_cLLI) != 0)
  153. {
  154. png_write_cLLI_fixed(png_ptr, info_ptr->maxCLL, info_ptr->maxFALL);
  155. }
  156. #endif
  157. #ifdef PNG_WRITE_mDCV_SUPPORTED
  158. if ((info_ptr->valid & PNG_INFO_mDCV) != 0)
  159. {
  160. png_write_mDCV_fixed(png_ptr,
  161. info_ptr->mastering_red_x, info_ptr->mastering_red_y,
  162. info_ptr->mastering_green_x, info_ptr->mastering_green_y,
  163. info_ptr->mastering_blue_x, info_ptr->mastering_blue_y,
  164. info_ptr->mastering_white_x, info_ptr->mastering_white_y,
  165. info_ptr->mastering_maxDL, info_ptr->mastering_minDL);
  166. }
  167. #endif
  168. # ifdef PNG_WRITE_cICP_SUPPORTED /* Priority 4 */
  169. if ((info_ptr->valid & PNG_INFO_cICP) != 0)
  170. {
  171. png_write_cICP(png_ptr,
  172. info_ptr->cicp_colour_primaries,
  173. info_ptr->cicp_transfer_function,
  174. info_ptr->cicp_matrix_coefficients,
  175. info_ptr->cicp_video_full_range_flag);
  176. }
  177. # endif
  178. # ifdef PNG_WRITE_iCCP_SUPPORTED /* Priority 3 */
  179. if ((info_ptr->valid & PNG_INFO_iCCP) != 0)
  180. {
  181. png_write_iCCP(png_ptr, info_ptr->iccp_name,
  182. info_ptr->iccp_profile, info_ptr->iccp_proflen);
  183. }
  184. # endif
  185. # ifdef PNG_WRITE_sRGB_SUPPORTED /* Priority 2 */
  186. if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
  187. png_write_sRGB(png_ptr, info_ptr->rendering_intent);
  188. # endif /* WRITE_sRGB */
  189. # ifdef PNG_WRITE_gAMA_SUPPORTED /* Priority 1 */
  190. if ((info_ptr->valid & PNG_INFO_gAMA) != 0)
  191. png_write_gAMA_fixed(png_ptr, info_ptr->gamma);
  192. # endif
  193. # ifdef PNG_WRITE_cHRM_SUPPORTED /* Also priority 1 */
  194. if ((info_ptr->valid & PNG_INFO_cHRM) != 0)
  195. png_write_cHRM_fixed(png_ptr, &info_ptr->cHRM);
  196. # endif
  197. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198. }
  199. }
  200. void PNGAPI
  201. png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
  202. {
  203. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  204. int i;
  205. #endif
  206. png_debug(1, "in png_write_info");
  207. if (png_ptr == NULL || info_ptr == NULL)
  208. return;
  209. png_write_info_before_PLTE(png_ptr, info_ptr);
  210. if ((info_ptr->valid & PNG_INFO_PLTE) != 0)
  211. png_write_PLTE(png_ptr, info_ptr->palette,
  212. (png_uint_32)info_ptr->num_palette);
  213. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  214. png_error(png_ptr, "Valid palette required for paletted images");
  215. #ifdef PNG_WRITE_tRNS_SUPPORTED
  216. if ((info_ptr->valid & PNG_INFO_tRNS) !=0)
  217. {
  218. #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
  219. /* Invert the alpha channel (in tRNS) */
  220. if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 &&
  221. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  222. {
  223. int j, jend;
  224. jend = info_ptr->num_trans;
  225. if (jend > PNG_MAX_PALETTE_LENGTH)
  226. jend = PNG_MAX_PALETTE_LENGTH;
  227. for (j = 0; j<jend; ++j)
  228. info_ptr->trans_alpha[j] =
  229. (png_byte)(255 - info_ptr->trans_alpha[j]);
  230. }
  231. #endif
  232. png_write_tRNS(png_ptr, info_ptr->trans_alpha, &(info_ptr->trans_color),
  233. info_ptr->num_trans, info_ptr->color_type);
  234. }
  235. #endif
  236. #ifdef PNG_WRITE_bKGD_SUPPORTED
  237. if ((info_ptr->valid & PNG_INFO_bKGD) != 0)
  238. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  239. #endif
  240. #ifdef PNG_WRITE_eXIf_SUPPORTED
  241. if ((info_ptr->valid & PNG_INFO_eXIf) != 0)
  242. {
  243. png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
  244. png_ptr->mode |= PNG_WROTE_eXIf;
  245. }
  246. #endif
  247. #ifdef PNG_WRITE_hIST_SUPPORTED
  248. if ((info_ptr->valid & PNG_INFO_hIST) != 0)
  249. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  250. #endif
  251. #ifdef PNG_WRITE_oFFs_SUPPORTED
  252. if ((info_ptr->valid & PNG_INFO_oFFs) != 0)
  253. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  254. info_ptr->offset_unit_type);
  255. #endif
  256. #ifdef PNG_WRITE_pCAL_SUPPORTED
  257. if ((info_ptr->valid & PNG_INFO_pCAL) != 0)
  258. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  259. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  260. info_ptr->pcal_units, info_ptr->pcal_params);
  261. #endif
  262. #ifdef PNG_WRITE_sCAL_SUPPORTED
  263. if ((info_ptr->valid & PNG_INFO_sCAL) != 0)
  264. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  265. info_ptr->scal_s_width, info_ptr->scal_s_height);
  266. #endif /* sCAL */
  267. #ifdef PNG_WRITE_pHYs_SUPPORTED
  268. if ((info_ptr->valid & PNG_INFO_pHYs) != 0)
  269. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  270. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  271. #endif /* pHYs */
  272. #ifdef PNG_WRITE_tIME_SUPPORTED
  273. if ((info_ptr->valid & PNG_INFO_tIME) != 0)
  274. {
  275. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  276. png_ptr->mode |= PNG_WROTE_tIME;
  277. }
  278. #endif /* tIME */
  279. #ifdef PNG_WRITE_sPLT_SUPPORTED
  280. if ((info_ptr->valid & PNG_INFO_sPLT) != 0)
  281. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  282. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  283. #endif /* sPLT */
  284. #ifdef PNG_WRITE_TEXT_SUPPORTED
  285. /* Check to see if we need to write text chunks */
  286. for (i = 0; i < info_ptr->num_text; i++)
  287. {
  288. png_debug2(2, "Writing header text chunk %d, type %d", i,
  289. info_ptr->text[i].compression);
  290. /* An internationalized chunk? */
  291. if (info_ptr->text[i].compression > 0)
  292. {
  293. #ifdef PNG_WRITE_iTXt_SUPPORTED
  294. /* Write international chunk */
  295. png_write_iTXt(png_ptr,
  296. info_ptr->text[i].compression,
  297. info_ptr->text[i].key,
  298. info_ptr->text[i].lang,
  299. info_ptr->text[i].lang_key,
  300. info_ptr->text[i].text);
  301. /* Mark this chunk as written */
  302. if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  303. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  304. else
  305. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  306. #else
  307. png_warning(png_ptr, "Unable to write international text");
  308. #endif
  309. }
  310. /* If we want a compressed text chunk */
  311. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  312. {
  313. #ifdef PNG_WRITE_zTXt_SUPPORTED
  314. /* Write compressed chunk */
  315. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  316. info_ptr->text[i].text, info_ptr->text[i].compression);
  317. /* Mark this chunk as written */
  318. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  319. #else
  320. png_warning(png_ptr, "Unable to write compressed text");
  321. #endif
  322. }
  323. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  324. {
  325. #ifdef PNG_WRITE_tEXt_SUPPORTED
  326. /* Write uncompressed chunk */
  327. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  328. info_ptr->text[i].text,
  329. 0);
  330. /* Mark this chunk as written */
  331. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  332. #else
  333. /* Can't get here */
  334. png_warning(png_ptr, "Unable to write uncompressed text");
  335. #endif
  336. }
  337. }
  338. #endif /* tEXt */
  339. #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  340. write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE);
  341. #endif
  342. }
  343. /* Writes the end of the PNG file. If you don't want to write comments or
  344. * time information, you can pass NULL for info. If you already wrote these
  345. * in png_write_info(), do not write them again here. If you have long
  346. * comments, I suggest writing them here, and compressing them.
  347. */
  348. void PNGAPI
  349. png_write_end(png_structrp png_ptr, png_inforp info_ptr)
  350. {
  351. png_debug(1, "in png_write_end");
  352. if (png_ptr == NULL)
  353. return;
  354. if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
  355. png_error(png_ptr, "No IDATs written into file");
  356. #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
  357. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  358. png_ptr->num_palette_max >= png_ptr->num_palette)
  359. png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
  360. #endif
  361. /* See if user wants us to write information chunks */
  362. if (info_ptr != NULL)
  363. {
  364. #ifdef PNG_WRITE_TEXT_SUPPORTED
  365. int i; /* local index variable */
  366. #endif
  367. #ifdef PNG_WRITE_tIME_SUPPORTED
  368. /* Check to see if user has supplied a time chunk */
  369. if ((info_ptr->valid & PNG_INFO_tIME) != 0 &&
  370. (png_ptr->mode & PNG_WROTE_tIME) == 0)
  371. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  372. #endif
  373. #ifdef PNG_WRITE_TEXT_SUPPORTED
  374. /* Loop through comment chunks */
  375. for (i = 0; i < info_ptr->num_text; i++)
  376. {
  377. png_debug2(2, "Writing trailer text chunk %d, type %d", i,
  378. info_ptr->text[i].compression);
  379. /* An internationalized chunk? */
  380. if (info_ptr->text[i].compression > 0)
  381. {
  382. #ifdef PNG_WRITE_iTXt_SUPPORTED
  383. /* Write international chunk */
  384. png_write_iTXt(png_ptr,
  385. info_ptr->text[i].compression,
  386. info_ptr->text[i].key,
  387. info_ptr->text[i].lang,
  388. info_ptr->text[i].lang_key,
  389. info_ptr->text[i].text);
  390. /* Mark this chunk as written */
  391. if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  392. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  393. else
  394. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  395. #else
  396. png_warning(png_ptr, "Unable to write international text");
  397. #endif
  398. }
  399. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  400. {
  401. #ifdef PNG_WRITE_zTXt_SUPPORTED
  402. /* Write compressed chunk */
  403. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  404. info_ptr->text[i].text, info_ptr->text[i].compression);
  405. /* Mark this chunk as written */
  406. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  407. #else
  408. png_warning(png_ptr, "Unable to write compressed text");
  409. #endif
  410. }
  411. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  412. {
  413. #ifdef PNG_WRITE_tEXt_SUPPORTED
  414. /* Write uncompressed chunk */
  415. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  416. info_ptr->text[i].text, 0);
  417. /* Mark this chunk as written */
  418. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  419. #else
  420. png_warning(png_ptr, "Unable to write uncompressed text");
  421. #endif
  422. }
  423. }
  424. #endif
  425. #ifdef PNG_WRITE_eXIf_SUPPORTED
  426. if ((info_ptr->valid & PNG_INFO_eXIf) != 0 &&
  427. (png_ptr->mode & PNG_WROTE_eXIf) == 0)
  428. png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
  429. #endif
  430. #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  431. write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT);
  432. #endif
  433. }
  434. png_ptr->mode |= PNG_AFTER_IDAT;
  435. /* Write end of PNG file */
  436. png_write_IEND(png_ptr);
  437. /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03,
  438. * and restored again in libpng-1.2.30, may cause some applications that
  439. * do not set png_ptr->output_flush_fn to crash. If your application
  440. * experiences a problem, please try building libpng with
  441. * PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED defined, and report the event to
  442. * png-mng-implement at lists.sf.net .
  443. */
  444. #ifdef PNG_WRITE_FLUSH_SUPPORTED
  445. # ifdef PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED
  446. png_flush(png_ptr);
  447. # endif
  448. #endif
  449. }
  450. #ifdef PNG_CONVERT_tIME_SUPPORTED
  451. void PNGAPI
  452. png_convert_from_struct_tm(png_timep ptime, const struct tm * ttime)
  453. {
  454. png_debug(1, "in png_convert_from_struct_tm");
  455. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  456. ptime->month = (png_byte)(ttime->tm_mon + 1);
  457. ptime->day = (png_byte)ttime->tm_mday;
  458. ptime->hour = (png_byte)ttime->tm_hour;
  459. ptime->minute = (png_byte)ttime->tm_min;
  460. ptime->second = (png_byte)ttime->tm_sec;
  461. }
  462. void PNGAPI
  463. png_convert_from_time_t(png_timep ptime, time_t ttime)
  464. {
  465. struct tm *tbuf;
  466. png_debug(1, "in png_convert_from_time_t");
  467. tbuf = gmtime(&ttime);
  468. if (tbuf == NULL)
  469. {
  470. /* TODO: add a safe function which takes a png_ptr argument and raises
  471. * a png_error if the ttime argument is invalid and the call to gmtime
  472. * fails as a consequence.
  473. */
  474. memset(ptime, 0, sizeof(*ptime));
  475. return;
  476. }
  477. png_convert_from_struct_tm(ptime, tbuf);
  478. }
  479. #endif
  480. /* Initialize png_ptr structure, and allocate any memory needed */
  481. PNG_FUNCTION(png_structp,PNGAPI
  482. png_create_write_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
  483. png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
  484. {
  485. #ifndef PNG_USER_MEM_SUPPORTED
  486. png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
  487. error_fn, warn_fn, NULL, NULL, NULL);
  488. #else
  489. return png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  490. warn_fn, NULL, NULL, NULL);
  491. }
  492. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  493. PNG_FUNCTION(png_structp,PNGAPI
  494. png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
  495. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  496. png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
  497. {
  498. png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
  499. error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
  500. #endif /* USER_MEM */
  501. if (png_ptr != NULL)
  502. {
  503. /* Set the zlib control values to defaults; they can be overridden by the
  504. * application after the struct has been created.
  505. */
  506. png_ptr->zbuffer_size = PNG_ZBUF_SIZE;
  507. /* The 'zlib_strategy' setting is irrelevant because png_default_claim in
  508. * pngwutil.c defaults it according to whether or not filters will be
  509. * used, and ignores this setting.
  510. */
  511. png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY;
  512. png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION;
  513. png_ptr->zlib_mem_level = 8;
  514. png_ptr->zlib_window_bits = 15;
  515. png_ptr->zlib_method = 8;
  516. #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
  517. png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY;
  518. png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION;
  519. png_ptr->zlib_text_mem_level = 8;
  520. png_ptr->zlib_text_window_bits = 15;
  521. png_ptr->zlib_text_method = 8;
  522. #endif /* WRITE_COMPRESSED_TEXT */
  523. /* This is a highly dubious configuration option; by default it is off,
  524. * but it may be appropriate for private builds that are testing
  525. * extensions not conformant to the current specification, or of
  526. * applications that must not fail to write at all costs!
  527. */
  528. #ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED
  529. /* In stable builds only warn if an application error can be completely
  530. * handled.
  531. */
  532. png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
  533. #endif
  534. /* App warnings are warnings in release (or release candidate) builds but
  535. * are errors during development.
  536. */
  537. #if PNG_RELEASE_BUILD
  538. png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
  539. #endif
  540. /* TODO: delay this, it can be done in png_init_io() (if the app doesn't
  541. * do it itself) avoiding setting the default function if it is not
  542. * required.
  543. */
  544. png_set_write_fn(png_ptr, NULL, NULL, NULL);
  545. }
  546. return png_ptr;
  547. }
  548. /* Write a few rows of image data. If the image is interlaced,
  549. * either you will have to write the 7 sub images, or, if you
  550. * have called png_set_interlace_handling(), you will have to
  551. * "write" the image seven times.
  552. */
  553. void PNGAPI
  554. png_write_rows(png_structrp png_ptr, png_bytepp row,
  555. png_uint_32 num_rows)
  556. {
  557. png_uint_32 i; /* row counter */
  558. png_bytepp rp; /* row pointer */
  559. png_debug(1, "in png_write_rows");
  560. if (png_ptr == NULL)
  561. return;
  562. /* Loop through the rows */
  563. for (i = 0, rp = row; i < num_rows; i++, rp++)
  564. {
  565. png_write_row(png_ptr, *rp);
  566. }
  567. }
  568. /* Write the image. You only need to call this function once, even
  569. * if you are writing an interlaced image.
  570. */
  571. void PNGAPI
  572. png_write_image(png_structrp png_ptr, png_bytepp image)
  573. {
  574. png_uint_32 i; /* row index */
  575. int pass, num_pass; /* pass variables */
  576. png_bytepp rp; /* points to current row */
  577. if (png_ptr == NULL)
  578. return;
  579. png_debug(1, "in png_write_image");
  580. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  581. /* Initialize interlace handling. If image is not interlaced,
  582. * this will set pass to 1
  583. */
  584. num_pass = png_set_interlace_handling(png_ptr);
  585. #else
  586. num_pass = 1;
  587. #endif
  588. /* Loop through passes */
  589. for (pass = 0; pass < num_pass; pass++)
  590. {
  591. /* Loop through image */
  592. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  593. {
  594. png_write_row(png_ptr, *rp);
  595. }
  596. }
  597. }
  598. #ifdef PNG_MNG_FEATURES_SUPPORTED
  599. /* Performs intrapixel differencing */
  600. static void
  601. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  602. {
  603. png_debug(1, "in png_do_write_intrapixel");
  604. if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
  605. {
  606. int bytes_per_pixel;
  607. png_uint_32 row_width = row_info->width;
  608. if (row_info->bit_depth == 8)
  609. {
  610. png_bytep rp;
  611. png_uint_32 i;
  612. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  613. bytes_per_pixel = 3;
  614. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  615. bytes_per_pixel = 4;
  616. else
  617. return;
  618. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  619. {
  620. *(rp) = (png_byte)(*rp - *(rp + 1));
  621. *(rp + 2) = (png_byte)(*(rp + 2) - *(rp + 1));
  622. }
  623. }
  624. #ifdef PNG_WRITE_16BIT_SUPPORTED
  625. else if (row_info->bit_depth == 16)
  626. {
  627. png_bytep rp;
  628. png_uint_32 i;
  629. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  630. bytes_per_pixel = 6;
  631. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  632. bytes_per_pixel = 8;
  633. else
  634. return;
  635. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  636. {
  637. png_uint_32 s0 = (png_uint_32)(*(rp ) << 8) | *(rp + 1);
  638. png_uint_32 s1 = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
  639. png_uint_32 s2 = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
  640. png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL);
  641. png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
  642. *(rp ) = (png_byte)(red >> 8);
  643. *(rp + 1) = (png_byte)red;
  644. *(rp + 4) = (png_byte)(blue >> 8);
  645. *(rp + 5) = (png_byte)blue;
  646. }
  647. }
  648. #endif /* WRITE_16BIT */
  649. }
  650. }
  651. #endif /* MNG_FEATURES */
  652. /* Called by user to write a row of image data */
  653. void PNGAPI
  654. png_write_row(png_structrp png_ptr, png_const_bytep row)
  655. {
  656. /* 1.5.6: moved from png_struct to be a local structure: */
  657. png_row_info row_info;
  658. png_debug2(1, "in png_write_row (row %u, pass %d)",
  659. png_ptr->row_number, png_ptr->pass);
  660. if (png_ptr == NULL)
  661. return;
  662. /* Initialize transformations and other stuff if first time */
  663. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  664. {
  665. /* Make sure we wrote the header info */
  666. if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
  667. png_error(png_ptr,
  668. "png_write_info was never called before png_write_row");
  669. /* Check for transforms that have been set but were defined out */
  670. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  671. if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
  672. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined");
  673. #endif
  674. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  675. if ((png_ptr->transformations & PNG_FILLER) != 0)
  676. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined");
  677. #endif
  678. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
  679. defined(PNG_READ_PACKSWAP_SUPPORTED)
  680. if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
  681. png_warning(png_ptr,
  682. "PNG_WRITE_PACKSWAP_SUPPORTED is not defined");
  683. #endif
  684. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  685. if ((png_ptr->transformations & PNG_PACK) != 0)
  686. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined");
  687. #endif
  688. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  689. if ((png_ptr->transformations & PNG_SHIFT) != 0)
  690. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined");
  691. #endif
  692. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  693. if ((png_ptr->transformations & PNG_BGR) != 0)
  694. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined");
  695. #endif
  696. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  697. if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
  698. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined");
  699. #endif
  700. png_write_start_row(png_ptr);
  701. }
  702. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  703. /* If interlaced and not interested in row, return */
  704. if (png_ptr->interlaced != 0 &&
  705. (png_ptr->transformations & PNG_INTERLACE) != 0)
  706. {
  707. switch (png_ptr->pass)
  708. {
  709. case 0:
  710. if ((png_ptr->row_number & 0x07) != 0)
  711. {
  712. png_write_finish_row(png_ptr);
  713. return;
  714. }
  715. break;
  716. case 1:
  717. if ((png_ptr->row_number & 0x07) != 0 || png_ptr->width < 5)
  718. {
  719. png_write_finish_row(png_ptr);
  720. return;
  721. }
  722. break;
  723. case 2:
  724. if ((png_ptr->row_number & 0x07) != 4)
  725. {
  726. png_write_finish_row(png_ptr);
  727. return;
  728. }
  729. break;
  730. case 3:
  731. if ((png_ptr->row_number & 0x03) != 0 || png_ptr->width < 3)
  732. {
  733. png_write_finish_row(png_ptr);
  734. return;
  735. }
  736. break;
  737. case 4:
  738. if ((png_ptr->row_number & 0x03) != 2)
  739. {
  740. png_write_finish_row(png_ptr);
  741. return;
  742. }
  743. break;
  744. case 5:
  745. if ((png_ptr->row_number & 0x01) != 0 || png_ptr->width < 2)
  746. {
  747. png_write_finish_row(png_ptr);
  748. return;
  749. }
  750. break;
  751. case 6:
  752. if ((png_ptr->row_number & 0x01) == 0)
  753. {
  754. png_write_finish_row(png_ptr);
  755. return;
  756. }
  757. break;
  758. default: /* error: ignore it */
  759. break;
  760. }
  761. }
  762. #endif
  763. /* Set up row info for transformations */
  764. row_info.color_type = png_ptr->color_type;
  765. row_info.width = png_ptr->usr_width;
  766. row_info.channels = png_ptr->usr_channels;
  767. row_info.bit_depth = png_ptr->usr_bit_depth;
  768. row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels);
  769. row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
  770. png_debug1(3, "row_info->color_type = %d", row_info.color_type);
  771. png_debug1(3, "row_info->width = %u", row_info.width);
  772. png_debug1(3, "row_info->channels = %d", row_info.channels);
  773. png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth);
  774. png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth);
  775. png_debug1(3, "row_info->rowbytes = %lu", (unsigned long)row_info.rowbytes);
  776. /* Copy user's row into buffer, leaving room for filter byte. */
  777. memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes);
  778. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  779. /* Handle interlacing */
  780. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  781. (png_ptr->transformations & PNG_INTERLACE) != 0)
  782. {
  783. png_do_write_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass);
  784. /* This should always get caught above, but still ... */
  785. if (row_info.width == 0)
  786. {
  787. png_write_finish_row(png_ptr);
  788. return;
  789. }
  790. }
  791. #endif
  792. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  793. /* Handle other transformations */
  794. if (png_ptr->transformations != 0)
  795. png_do_write_transformations(png_ptr, &row_info);
  796. #endif
  797. /* At this point the row_info pixel depth must match the 'transformed' depth,
  798. * which is also the output depth.
  799. */
  800. if (row_info.pixel_depth != png_ptr->pixel_depth ||
  801. row_info.pixel_depth != png_ptr->transformed_pixel_depth)
  802. png_error(png_ptr, "internal write transform logic error");
  803. #ifdef PNG_MNG_FEATURES_SUPPORTED
  804. /* Write filter_method 64 (intrapixel differencing) only if
  805. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  806. * 2. Libpng did not write a PNG signature (this filter_method is only
  807. * used in PNG datastreams that are embedded in MNG datastreams) and
  808. * 3. The application called png_permit_mng_features with a mask that
  809. * included PNG_FLAG_MNG_FILTER_64 and
  810. * 4. The filter_method is 64 and
  811. * 5. The color_type is RGB or RGBA
  812. */
  813. if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
  814. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  815. {
  816. /* Intrapixel differencing */
  817. png_do_write_intrapixel(&row_info, png_ptr->row_buf + 1);
  818. }
  819. #endif
  820. /* Added at libpng-1.5.10 */
  821. #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
  822. /* Check for out-of-range palette index */
  823. if (row_info.color_type == PNG_COLOR_TYPE_PALETTE &&
  824. png_ptr->num_palette_max >= 0)
  825. png_do_check_palette_indexes(png_ptr, &row_info);
  826. #endif
  827. /* Find a filter if necessary, filter the row and write it out. */
  828. png_write_find_filter(png_ptr, &row_info);
  829. if (png_ptr->write_row_fn != NULL)
  830. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  831. }
  832. #ifdef PNG_WRITE_FLUSH_SUPPORTED
  833. /* Set the automatic flush interval or 0 to turn flushing off */
  834. void PNGAPI
  835. png_set_flush(png_structrp png_ptr, int nrows)
  836. {
  837. png_debug(1, "in png_set_flush");
  838. if (png_ptr == NULL)
  839. return;
  840. png_ptr->flush_dist = (nrows < 0 ? 0 : (png_uint_32)nrows);
  841. }
  842. /* Flush the current output buffers now */
  843. void PNGAPI
  844. png_write_flush(png_structrp png_ptr)
  845. {
  846. png_debug(1, "in png_write_flush");
  847. if (png_ptr == NULL)
  848. return;
  849. /* We have already written out all of the data */
  850. if (png_ptr->row_number >= png_ptr->num_rows)
  851. return;
  852. png_compress_IDAT(png_ptr, NULL, 0, Z_SYNC_FLUSH);
  853. png_ptr->flush_rows = 0;
  854. png_flush(png_ptr);
  855. }
  856. #endif /* WRITE_FLUSH */
  857. /* Free any memory used in png_ptr struct without freeing the struct itself. */
  858. static void
  859. png_write_destroy(png_structrp png_ptr)
  860. {
  861. png_debug(1, "in png_write_destroy");
  862. /* Free any memory zlib uses */
  863. if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
  864. deflateEnd(&png_ptr->zstream);
  865. /* Free our memory. png_free checks NULL for us. */
  866. png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
  867. png_free(png_ptr, png_ptr->row_buf);
  868. png_ptr->row_buf = NULL;
  869. #ifdef PNG_WRITE_FILTER_SUPPORTED
  870. png_free(png_ptr, png_ptr->prev_row);
  871. png_free(png_ptr, png_ptr->try_row);
  872. png_free(png_ptr, png_ptr->tst_row);
  873. png_ptr->prev_row = NULL;
  874. png_ptr->try_row = NULL;
  875. png_ptr->tst_row = NULL;
  876. #endif
  877. #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
  878. png_free(png_ptr, png_ptr->chunk_list);
  879. png_ptr->chunk_list = NULL;
  880. #endif
  881. /* The error handling and memory handling information is left intact at this
  882. * point: the jmp_buf may still have to be freed. See png_destroy_png_struct
  883. * for how this happens.
  884. */
  885. }
  886. /* Free all memory used by the write.
  887. * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for
  888. * *png_ptr_ptr. Prior to 1.6.0 it would accept such a value and it would free
  889. * the passed in info_structs but it would quietly fail to free any of the data
  890. * inside them. In 1.6.0 it quietly does nothing (it has to be quiet because it
  891. * has no png_ptr.)
  892. */
  893. void PNGAPI
  894. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  895. {
  896. png_debug(1, "in png_destroy_write_struct");
  897. if (png_ptr_ptr != NULL)
  898. {
  899. png_structrp png_ptr = *png_ptr_ptr;
  900. if (png_ptr != NULL) /* added in libpng 1.6.0 */
  901. {
  902. png_destroy_info_struct(png_ptr, info_ptr_ptr);
  903. *png_ptr_ptr = NULL;
  904. png_write_destroy(png_ptr);
  905. png_destroy_png_struct(png_ptr);
  906. }
  907. }
  908. }
  909. /* Allow the application to select one or more row filters to use. */
  910. void PNGAPI
  911. png_set_filter(png_structrp png_ptr, int method, int filters)
  912. {
  913. png_debug(1, "in png_set_filter");
  914. if (png_ptr == NULL)
  915. return;
  916. #ifdef PNG_MNG_FEATURES_SUPPORTED
  917. if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
  918. (method == PNG_INTRAPIXEL_DIFFERENCING))
  919. method = PNG_FILTER_TYPE_BASE;
  920. #endif
  921. if (method == PNG_FILTER_TYPE_BASE)
  922. {
  923. switch (filters & (PNG_ALL_FILTERS | 0x07))
  924. {
  925. #ifdef PNG_WRITE_FILTER_SUPPORTED
  926. case 5:
  927. case 6:
  928. case 7: png_app_error(png_ptr, "Unknown row filter for method 0");
  929. #endif /* WRITE_FILTER */
  930. /* FALLTHROUGH */
  931. case PNG_FILTER_VALUE_NONE:
  932. png_ptr->do_filter = PNG_FILTER_NONE; break;
  933. #ifdef PNG_WRITE_FILTER_SUPPORTED
  934. case PNG_FILTER_VALUE_SUB:
  935. png_ptr->do_filter = PNG_FILTER_SUB; break;
  936. case PNG_FILTER_VALUE_UP:
  937. png_ptr->do_filter = PNG_FILTER_UP; break;
  938. case PNG_FILTER_VALUE_AVG:
  939. png_ptr->do_filter = PNG_FILTER_AVG; break;
  940. case PNG_FILTER_VALUE_PAETH:
  941. png_ptr->do_filter = PNG_FILTER_PAETH; break;
  942. default:
  943. png_ptr->do_filter = (png_byte)filters; break;
  944. #else
  945. default:
  946. png_app_error(png_ptr, "Unknown row filter for method 0");
  947. #endif /* WRITE_FILTER */
  948. }
  949. #ifdef PNG_WRITE_FILTER_SUPPORTED
  950. /* If we have allocated the row_buf, this means we have already started
  951. * with the image and we should have allocated all of the filter buffers
  952. * that have been selected. If prev_row isn't already allocated, then
  953. * it is too late to start using the filters that need it, since we
  954. * will be missing the data in the previous row. If an application
  955. * wants to start and stop using particular filters during compression,
  956. * it should start out with all of the filters, and then remove them
  957. * or add them back after the start of compression.
  958. *
  959. * NOTE: this is a nasty constraint on the code, because it means that the
  960. * prev_row buffer must be maintained even if there are currently no
  961. * 'prev_row' requiring filters active.
  962. */
  963. if (png_ptr->row_buf != NULL)
  964. {
  965. int num_filters;
  966. png_alloc_size_t buf_size;
  967. /* Repeat the checks in png_write_start_row; 1 pixel high or wide
  968. * images cannot benefit from certain filters. If this isn't done here
  969. * the check below will fire on 1 pixel high images.
  970. */
  971. if (png_ptr->height == 1)
  972. filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
  973. if (png_ptr->width == 1)
  974. filters &= ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
  975. if ((filters & (PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)) != 0
  976. && png_ptr->prev_row == NULL)
  977. {
  978. /* This is the error case, however it is benign - the previous row
  979. * is not available so the filter can't be used. Just warn here.
  980. */
  981. png_app_warning(png_ptr,
  982. "png_set_filter: UP/AVG/PAETH cannot be added after start");
  983. filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
  984. }
  985. num_filters = 0;
  986. if (filters & PNG_FILTER_SUB)
  987. num_filters++;
  988. if (filters & PNG_FILTER_UP)
  989. num_filters++;
  990. if (filters & PNG_FILTER_AVG)
  991. num_filters++;
  992. if (filters & PNG_FILTER_PAETH)
  993. num_filters++;
  994. /* Allocate needed row buffers if they have not already been
  995. * allocated.
  996. */
  997. buf_size = PNG_ROWBYTES(png_ptr->usr_channels * png_ptr->usr_bit_depth,
  998. png_ptr->width) + 1;
  999. if (png_ptr->try_row == NULL)
  1000. png_ptr->try_row = png_voidcast(png_bytep,
  1001. png_malloc(png_ptr, buf_size));
  1002. if (num_filters > 1)
  1003. {
  1004. if (png_ptr->tst_row == NULL)
  1005. png_ptr->tst_row = png_voidcast(png_bytep,
  1006. png_malloc(png_ptr, buf_size));
  1007. }
  1008. }
  1009. png_ptr->do_filter = (png_byte)filters;
  1010. #endif
  1011. }
  1012. else
  1013. png_error(png_ptr, "Unknown custom filter method");
  1014. }
  1015. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */
  1016. /* Provide floating and fixed point APIs */
  1017. #ifdef PNG_FLOATING_POINT_SUPPORTED
  1018. void PNGAPI
  1019. png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method,
  1020. int num_weights, png_const_doublep filter_weights,
  1021. png_const_doublep filter_costs)
  1022. {
  1023. PNG_UNUSED(png_ptr)
  1024. PNG_UNUSED(heuristic_method)
  1025. PNG_UNUSED(num_weights)
  1026. PNG_UNUSED(filter_weights)
  1027. PNG_UNUSED(filter_costs)
  1028. }
  1029. #endif /* FLOATING_POINT */
  1030. #ifdef PNG_FIXED_POINT_SUPPORTED
  1031. void PNGAPI
  1032. png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method,
  1033. int num_weights, png_const_fixed_point_p filter_weights,
  1034. png_const_fixed_point_p filter_costs)
  1035. {
  1036. PNG_UNUSED(png_ptr)
  1037. PNG_UNUSED(heuristic_method)
  1038. PNG_UNUSED(num_weights)
  1039. PNG_UNUSED(filter_weights)
  1040. PNG_UNUSED(filter_costs)
  1041. }
  1042. #endif /* FIXED_POINT */
  1043. #endif /* WRITE_WEIGHTED_FILTER */
  1044. #ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
  1045. void PNGAPI
  1046. png_set_compression_level(png_structrp png_ptr, int level)
  1047. {
  1048. png_debug(1, "in png_set_compression_level");
  1049. if (png_ptr == NULL)
  1050. return;
  1051. png_ptr->zlib_level = level;
  1052. }
  1053. void PNGAPI
  1054. png_set_compression_mem_level(png_structrp png_ptr, int mem_level)
  1055. {
  1056. png_debug(1, "in png_set_compression_mem_level");
  1057. if (png_ptr == NULL)
  1058. return;
  1059. png_ptr->zlib_mem_level = mem_level;
  1060. }
  1061. void PNGAPI
  1062. png_set_compression_strategy(png_structrp png_ptr, int strategy)
  1063. {
  1064. png_debug(1, "in png_set_compression_strategy");
  1065. if (png_ptr == NULL)
  1066. return;
  1067. /* The flag setting here prevents the libpng dynamic selection of strategy.
  1068. */
  1069. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  1070. png_ptr->zlib_strategy = strategy;
  1071. }
  1072. /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
  1073. * smaller value of window_bits if it can do so safely.
  1074. */
  1075. void PNGAPI
  1076. png_set_compression_window_bits(png_structrp png_ptr, int window_bits)
  1077. {
  1078. png_debug(1, "in png_set_compression_window_bits");
  1079. if (png_ptr == NULL)
  1080. return;
  1081. /* Prior to 1.6.0 this would warn but then set the window_bits value. This
  1082. * meant that negative window bits values could be selected that would cause
  1083. * libpng to write a non-standard PNG file with raw deflate or gzip
  1084. * compressed IDAT or ancillary chunks. Such files can be read and there is
  1085. * no warning on read, so this seems like a very bad idea.
  1086. */
  1087. if (window_bits > 15)
  1088. {
  1089. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  1090. window_bits = 15;
  1091. }
  1092. else if (window_bits < 8)
  1093. {
  1094. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  1095. window_bits = 8;
  1096. }
  1097. png_ptr->zlib_window_bits = window_bits;
  1098. }
  1099. void PNGAPI
  1100. png_set_compression_method(png_structrp png_ptr, int method)
  1101. {
  1102. png_debug(1, "in png_set_compression_method");
  1103. if (png_ptr == NULL)
  1104. return;
  1105. /* This would produce an invalid PNG file if it worked, but it doesn't and
  1106. * deflate will fault it, so it is harmless to just warn here.
  1107. */
  1108. if (method != 8)
  1109. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  1110. png_ptr->zlib_method = method;
  1111. }
  1112. #endif /* WRITE_CUSTOMIZE_COMPRESSION */
  1113. /* The following were added to libpng-1.5.4 */
  1114. #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
  1115. void PNGAPI
  1116. png_set_text_compression_level(png_structrp png_ptr, int level)
  1117. {
  1118. png_debug(1, "in png_set_text_compression_level");
  1119. if (png_ptr == NULL)
  1120. return;
  1121. png_ptr->zlib_text_level = level;
  1122. }
  1123. void PNGAPI
  1124. png_set_text_compression_mem_level(png_structrp png_ptr, int mem_level)
  1125. {
  1126. png_debug(1, "in png_set_text_compression_mem_level");
  1127. if (png_ptr == NULL)
  1128. return;
  1129. png_ptr->zlib_text_mem_level = mem_level;
  1130. }
  1131. void PNGAPI
  1132. png_set_text_compression_strategy(png_structrp png_ptr, int strategy)
  1133. {
  1134. png_debug(1, "in png_set_text_compression_strategy");
  1135. if (png_ptr == NULL)
  1136. return;
  1137. png_ptr->zlib_text_strategy = strategy;
  1138. }
  1139. /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
  1140. * smaller value of window_bits if it can do so safely.
  1141. */
  1142. void PNGAPI
  1143. png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits)
  1144. {
  1145. png_debug(1, "in png_set_text_compression_window_bits");
  1146. if (png_ptr == NULL)
  1147. return;
  1148. if (window_bits > 15)
  1149. {
  1150. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  1151. window_bits = 15;
  1152. }
  1153. else if (window_bits < 8)
  1154. {
  1155. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  1156. window_bits = 8;
  1157. }
  1158. png_ptr->zlib_text_window_bits = window_bits;
  1159. }
  1160. void PNGAPI
  1161. png_set_text_compression_method(png_structrp png_ptr, int method)
  1162. {
  1163. png_debug(1, "in png_set_text_compression_method");
  1164. if (png_ptr == NULL)
  1165. return;
  1166. if (method != 8)
  1167. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  1168. png_ptr->zlib_text_method = method;
  1169. }
  1170. #endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */
  1171. /* end of API added to libpng-1.5.4 */
  1172. void PNGAPI
  1173. png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn)
  1174. {
  1175. png_debug(1, "in png_set_write_status_fn");
  1176. if (png_ptr == NULL)
  1177. return;
  1178. png_ptr->write_row_fn = write_row_fn;
  1179. }
  1180. #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
  1181. void PNGAPI
  1182. png_set_write_user_transform_fn(png_structrp png_ptr, png_user_transform_ptr
  1183. write_user_transform_fn)
  1184. {
  1185. png_debug(1, "in png_set_write_user_transform_fn");
  1186. if (png_ptr == NULL)
  1187. return;
  1188. png_ptr->transformations |= PNG_USER_TRANSFORM;
  1189. png_ptr->write_user_transform_fn = write_user_transform_fn;
  1190. }
  1191. #endif
  1192. #ifdef PNG_INFO_IMAGE_SUPPORTED
  1193. void PNGAPI
  1194. png_write_png(png_structrp png_ptr, png_inforp info_ptr,
  1195. int transforms, voidp params)
  1196. {
  1197. png_debug(1, "in png_write_png");
  1198. if (png_ptr == NULL || info_ptr == NULL)
  1199. return;
  1200. if ((info_ptr->valid & PNG_INFO_IDAT) == 0)
  1201. {
  1202. png_app_error(png_ptr, "no rows for png_write_image to write");
  1203. return;
  1204. }
  1205. /* Write the file header information. */
  1206. png_write_info(png_ptr, info_ptr);
  1207. /* ------ these transformations don't touch the info structure ------- */
  1208. /* Invert monochrome pixels */
  1209. if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
  1210. #ifdef PNG_WRITE_INVERT_SUPPORTED
  1211. png_set_invert_mono(png_ptr);
  1212. #else
  1213. png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
  1214. #endif
  1215. /* Shift the pixels up to a legal bit depth and fill in
  1216. * as appropriate to correctly scale the image.
  1217. */
  1218. if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
  1219. #ifdef PNG_WRITE_SHIFT_SUPPORTED
  1220. if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
  1221. png_set_shift(png_ptr, &info_ptr->sig_bit);
  1222. #else
  1223. png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
  1224. #endif
  1225. /* Pack pixels into bytes */
  1226. if ((transforms & PNG_TRANSFORM_PACKING) != 0)
  1227. #ifdef PNG_WRITE_PACK_SUPPORTED
  1228. png_set_packing(png_ptr);
  1229. #else
  1230. png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
  1231. #endif
  1232. /* Swap location of alpha bytes from ARGB to RGBA */
  1233. if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
  1234. #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
  1235. png_set_swap_alpha(png_ptr);
  1236. #else
  1237. png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
  1238. #endif
  1239. /* Remove a filler (X) from XRGB/RGBX/AG/GA into to convert it into
  1240. * RGB, note that the code expects the input color type to be G or RGB; no
  1241. * alpha channel.
  1242. */
  1243. if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER|
  1244. PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
  1245. {
  1246. #ifdef PNG_WRITE_FILLER_SUPPORTED
  1247. if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0)
  1248. {
  1249. if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
  1250. png_app_error(png_ptr,
  1251. "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
  1252. /* Continue if ignored - this is the pre-1.6.10 behavior */
  1253. png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
  1254. }
  1255. else if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
  1256. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  1257. #else
  1258. png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_FILLER not supported");
  1259. #endif
  1260. }
  1261. /* Flip BGR pixels to RGB */
  1262. if ((transforms & PNG_TRANSFORM_BGR) != 0)
  1263. #ifdef PNG_WRITE_BGR_SUPPORTED
  1264. png_set_bgr(png_ptr);
  1265. #else
  1266. png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
  1267. #endif
  1268. /* Swap bytes of 16-bit files to most significant byte first */
  1269. if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
  1270. #ifdef PNG_WRITE_SWAP_SUPPORTED
  1271. png_set_swap(png_ptr);
  1272. #else
  1273. png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
  1274. #endif
  1275. /* Swap bits of 1-bit, 2-bit, 4-bit packed pixel formats */
  1276. if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
  1277. #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
  1278. png_set_packswap(png_ptr);
  1279. #else
  1280. png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
  1281. #endif
  1282. /* Invert the alpha channel from opacity to transparency */
  1283. if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
  1284. #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
  1285. png_set_invert_alpha(png_ptr);
  1286. #else
  1287. png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
  1288. #endif
  1289. /* ----------------------- end of transformations ------------------- */
  1290. /* Write the bits */
  1291. png_write_image(png_ptr, info_ptr->row_pointers);
  1292. /* It is REQUIRED to call this to finish writing the rest of the file */
  1293. png_write_end(png_ptr, info_ptr);
  1294. PNG_UNUSED(params)
  1295. }
  1296. #endif
  1297. #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
  1298. /* Initialize the write structure - general purpose utility. */
  1299. static int
  1300. png_image_write_init(png_imagep image)
  1301. {
  1302. png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
  1303. png_safe_error, png_safe_warning);
  1304. if (png_ptr != NULL)
  1305. {
  1306. png_infop info_ptr = png_create_info_struct(png_ptr);
  1307. if (info_ptr != NULL)
  1308. {
  1309. png_controlp control = png_voidcast(png_controlp,
  1310. png_malloc_warn(png_ptr, (sizeof *control)));
  1311. if (control != NULL)
  1312. {
  1313. memset(control, 0, (sizeof *control));
  1314. control->png_ptr = png_ptr;
  1315. control->info_ptr = info_ptr;
  1316. control->for_write = 1;
  1317. image->opaque = control;
  1318. return 1;
  1319. }
  1320. /* Error clean up */
  1321. png_destroy_info_struct(png_ptr, &info_ptr);
  1322. }
  1323. png_destroy_write_struct(&png_ptr, NULL);
  1324. }
  1325. return png_image_error(image, "png_image_write_: out of memory");
  1326. }
  1327. /* Arguments to png_image_write_main: */
  1328. typedef struct
  1329. {
  1330. /* Arguments: */
  1331. png_imagep image;
  1332. png_const_voidp buffer;
  1333. png_int_32 row_stride;
  1334. png_const_voidp colormap;
  1335. int convert_to_8bit;
  1336. /* Local variables: */
  1337. png_const_voidp first_row;
  1338. ptrdiff_t row_bytes;
  1339. png_voidp local_row;
  1340. /* Byte count for memory writing */
  1341. png_bytep memory;
  1342. png_alloc_size_t memory_bytes; /* not used for STDIO */
  1343. png_alloc_size_t output_bytes; /* running total */
  1344. } png_image_write_control;
  1345. /* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
  1346. * do any necessary byte swapping. The component order is defined by the
  1347. * png_image format value.
  1348. */
  1349. static int
  1350. png_write_image_16bit(png_voidp argument)
  1351. {
  1352. png_image_write_control *display = png_voidcast(png_image_write_control*,
  1353. argument);
  1354. png_imagep image = display->image;
  1355. png_structrp png_ptr = image->opaque->png_ptr;
  1356. png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
  1357. display->first_row);
  1358. png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row);
  1359. png_uint_16p row_end;
  1360. unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
  1361. 3 : 1;
  1362. int aindex = 0;
  1363. png_uint_32 y = image->height;
  1364. if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
  1365. {
  1366. # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
  1367. if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
  1368. {
  1369. aindex = -1;
  1370. ++input_row; /* To point to the first component */
  1371. ++output_row;
  1372. }
  1373. else
  1374. aindex = (int)channels;
  1375. # else
  1376. aindex = (int)channels;
  1377. # endif
  1378. }
  1379. else
  1380. png_error(png_ptr, "png_write_image: internal call error");
  1381. /* Work out the output row end and count over this, note that the increment
  1382. * above to 'row' means that row_end can actually be beyond the end of the
  1383. * row; this is correct.
  1384. */
  1385. row_end = output_row + image->width * (channels+1);
  1386. for (; y > 0; --y)
  1387. {
  1388. png_const_uint_16p in_ptr = input_row;
  1389. png_uint_16p out_ptr = output_row;
  1390. while (out_ptr < row_end)
  1391. {
  1392. png_uint_16 alpha = in_ptr[aindex];
  1393. png_uint_32 reciprocal = 0;
  1394. int c;
  1395. out_ptr[aindex] = alpha;
  1396. /* Calculate a reciprocal. The correct calculation is simply
  1397. * component/alpha*65535 << 15. (I.e. 15 bits of precision); this
  1398. * allows correct rounding by adding .5 before the shift. 'reciprocal'
  1399. * is only initialized when required.
  1400. */
  1401. if (alpha > 0 && alpha < 65535)
  1402. reciprocal = ((0xffff<<15)+(alpha>>1))/alpha;
  1403. c = (int)channels;
  1404. do /* always at least one channel */
  1405. {
  1406. png_uint_16 component = *in_ptr++;
  1407. /* The following gives 65535 for an alpha of 0, which is fine,
  1408. * otherwise if 0/0 is represented as some other value there is more
  1409. * likely to be a discontinuity which will probably damage
  1410. * compression when moving from a fully transparent area to a
  1411. * nearly transparent one. (The assumption here is that opaque
  1412. * areas tend not to be 0 intensity.)
  1413. */
  1414. if (component >= alpha)
  1415. component = 65535;
  1416. /* component<alpha, so component/alpha is less than one and
  1417. * component*reciprocal is less than 2^31.
  1418. */
  1419. else if (component > 0 && alpha < 65535)
  1420. {
  1421. png_uint_32 calc = component * reciprocal;
  1422. calc += 16384; /* round to nearest */
  1423. component = (png_uint_16)(calc >> 15);
  1424. }
  1425. *out_ptr++ = component;
  1426. }
  1427. while (--c > 0);
  1428. /* Skip to next component (skip the intervening alpha channel) */
  1429. ++in_ptr;
  1430. ++out_ptr;
  1431. }
  1432. png_write_row(png_ptr, png_voidcast(png_const_bytep, display->local_row));
  1433. input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
  1434. }
  1435. return 1;
  1436. }
  1437. /* Given 16-bit input (1 to 4 channels) write 8-bit output. If an alpha channel
  1438. * is present it must be removed from the components, the components are then
  1439. * written in sRGB encoding. No components are added or removed.
  1440. *
  1441. * Calculate an alpha reciprocal to reverse pre-multiplication. As above the
  1442. * calculation can be done to 15 bits of accuracy; however, the output needs to
  1443. * be scaled in the range 0..255*65535, so include that scaling here.
  1444. */
  1445. # define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+((alpha)>>1))/(alpha))
  1446. static png_byte
  1447. png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
  1448. png_uint_32 reciprocal/*from the above macro*/)
  1449. {
  1450. /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0
  1451. * is represented as some other value there is more likely to be a
  1452. * discontinuity which will probably damage compression when moving from a
  1453. * fully transparent area to a nearly transparent one. (The assumption here
  1454. * is that opaque areas tend not to be 0 intensity.)
  1455. *
  1456. * There is a rounding problem here; if alpha is less than 128 it will end up
  1457. * as 0 when scaled to 8 bits. To avoid introducing spurious colors into the
  1458. * output change for this too.
  1459. */
  1460. if (component >= alpha || alpha < 128)
  1461. return 255;
  1462. /* component<alpha, so component/alpha is less than one and
  1463. * component*reciprocal is less than 2^31.
  1464. */
  1465. else if (component > 0)
  1466. {
  1467. /* The test is that alpha/257 (rounded) is less than 255, the first value
  1468. * that becomes 255 is 65407.
  1469. * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore,
  1470. * be exact!) [Could also test reciprocal != 0]
  1471. */
  1472. if (alpha < 65407)
  1473. {
  1474. component *= reciprocal;
  1475. component += 64; /* round to nearest */
  1476. component >>= 7;
  1477. }
  1478. else
  1479. component *= 255;
  1480. /* Convert the component to sRGB. */
  1481. return (png_byte)PNG_sRGB_FROM_LINEAR(component);
  1482. }
  1483. else
  1484. return 0;
  1485. }
  1486. static int
  1487. png_write_image_8bit(png_voidp argument)
  1488. {
  1489. png_image_write_control *display = png_voidcast(png_image_write_control*,
  1490. argument);
  1491. png_imagep image = display->image;
  1492. png_structrp png_ptr = image->opaque->png_ptr;
  1493. png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
  1494. display->first_row);
  1495. png_bytep output_row = png_voidcast(png_bytep, display->local_row);
  1496. png_uint_32 y = image->height;
  1497. unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
  1498. 3 : 1;
  1499. if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
  1500. {
  1501. png_bytep row_end;
  1502. int aindex;
  1503. # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
  1504. if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
  1505. {
  1506. aindex = -1;
  1507. ++input_row; /* To point to the first component */
  1508. ++output_row;
  1509. }
  1510. else
  1511. # endif
  1512. aindex = (int)channels;
  1513. /* Use row_end in place of a loop counter: */
  1514. row_end = output_row + image->width * (channels+1);
  1515. for (; y > 0; --y)
  1516. {
  1517. png_const_uint_16p in_ptr = input_row;
  1518. png_bytep out_ptr = output_row;
  1519. while (out_ptr < row_end)
  1520. {
  1521. png_uint_16 alpha = in_ptr[aindex];
  1522. png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
  1523. png_uint_32 reciprocal = 0;
  1524. int c;
  1525. /* Scale and write the alpha channel. */
  1526. out_ptr[aindex] = alphabyte;
  1527. if (alphabyte > 0 && alphabyte < 255)
  1528. reciprocal = UNP_RECIPROCAL(alpha);
  1529. c = (int)channels;
  1530. do /* always at least one channel */
  1531. *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal);
  1532. while (--c > 0);
  1533. /* Skip to next component (skip the intervening alpha channel) */
  1534. ++in_ptr;
  1535. ++out_ptr;
  1536. } /* while out_ptr < row_end */
  1537. png_write_row(png_ptr, png_voidcast(png_const_bytep,
  1538. display->local_row));
  1539. input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
  1540. } /* while y */
  1541. }
  1542. else
  1543. {
  1544. /* No alpha channel, so the row_end really is the end of the row and it
  1545. * is sufficient to loop over the components one by one.
  1546. */
  1547. png_bytep row_end = output_row + image->width * channels;
  1548. for (; y > 0; --y)
  1549. {
  1550. png_const_uint_16p in_ptr = input_row;
  1551. png_bytep out_ptr = output_row;
  1552. while (out_ptr < row_end)
  1553. {
  1554. png_uint_32 component = *in_ptr++;
  1555. component *= 255;
  1556. *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component);
  1557. }
  1558. png_write_row(png_ptr, output_row);
  1559. input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
  1560. }
  1561. }
  1562. return 1;
  1563. }
  1564. static void
  1565. png_image_set_PLTE(png_image_write_control *display)
  1566. {
  1567. png_imagep image = display->image;
  1568. const void *cmap = display->colormap;
  1569. int entries = image->colormap_entries > 256 ? 256 :
  1570. (int)image->colormap_entries;
  1571. /* NOTE: the caller must check for cmap != NULL and entries != 0 */
  1572. png_uint_32 format = image->format;
  1573. unsigned int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
  1574. # if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
  1575. defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED)
  1576. int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
  1577. (format & PNG_FORMAT_FLAG_ALPHA) != 0;
  1578. # else
  1579. # define afirst 0
  1580. # endif
  1581. # ifdef PNG_FORMAT_BGR_SUPPORTED
  1582. int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
  1583. # else
  1584. # define bgr 0
  1585. # endif
  1586. int i, num_trans;
  1587. png_color palette[256];
  1588. png_byte tRNS[256];
  1589. memset(tRNS, 255, (sizeof tRNS));
  1590. memset(palette, 0, (sizeof palette));
  1591. for (i=num_trans=0; i<entries; ++i)
  1592. {
  1593. /* This gets automatically converted to sRGB with reversal of the
  1594. * pre-multiplication if the color-map has an alpha channel.
  1595. */
  1596. if ((format & PNG_FORMAT_FLAG_LINEAR) != 0)
  1597. {
  1598. png_const_uint_16p entry = png_voidcast(png_const_uint_16p, cmap);
  1599. entry += (unsigned int)i * channels;
  1600. if ((channels & 1) != 0) /* no alpha */
  1601. {
  1602. if (channels >= 3) /* RGB */
  1603. {
  1604. palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
  1605. entry[(2 ^ bgr)]);
  1606. palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
  1607. entry[1]);
  1608. palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
  1609. entry[bgr]);
  1610. }
  1611. else /* Gray */
  1612. palette[i].blue = palette[i].red = palette[i].green =
  1613. (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry);
  1614. }
  1615. else /* alpha */
  1616. {
  1617. png_uint_16 alpha = entry[afirst ? 0 : channels-1];
  1618. png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
  1619. png_uint_32 reciprocal = 0;
  1620. /* Calculate a reciprocal, as in the png_write_image_8bit code above
  1621. * this is designed to produce a value scaled to 255*65535 when
  1622. * divided by 128 (i.e. asr 7).
  1623. */
  1624. if (alphabyte > 0 && alphabyte < 255)
  1625. reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha;
  1626. tRNS[i] = alphabyte;
  1627. if (alphabyte < 255)
  1628. num_trans = i+1;
  1629. if (channels >= 3) /* RGB */
  1630. {
  1631. palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)],
  1632. alpha, reciprocal);
  1633. palette[i].green = png_unpremultiply(entry[afirst + 1], alpha,
  1634. reciprocal);
  1635. palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha,
  1636. reciprocal);
  1637. }
  1638. else /* gray */
  1639. palette[i].blue = palette[i].red = palette[i].green =
  1640. png_unpremultiply(entry[afirst], alpha, reciprocal);
  1641. }
  1642. }
  1643. else /* Color-map has sRGB values */
  1644. {
  1645. png_const_bytep entry = png_voidcast(png_const_bytep, cmap);
  1646. entry += (unsigned int)i * channels;
  1647. switch (channels)
  1648. {
  1649. case 4:
  1650. tRNS[i] = entry[afirst ? 0 : 3];
  1651. if (tRNS[i] < 255)
  1652. num_trans = i+1;
  1653. /* FALLTHROUGH */
  1654. case 3:
  1655. palette[i].blue = entry[afirst + (2 ^ bgr)];
  1656. palette[i].green = entry[afirst + 1];
  1657. palette[i].red = entry[afirst + bgr];
  1658. break;
  1659. case 2:
  1660. tRNS[i] = entry[1 ^ afirst];
  1661. if (tRNS[i] < 255)
  1662. num_trans = i+1;
  1663. /* FALLTHROUGH */
  1664. case 1:
  1665. palette[i].blue = palette[i].red = palette[i].green =
  1666. entry[afirst];
  1667. break;
  1668. default:
  1669. break;
  1670. }
  1671. }
  1672. }
  1673. # ifdef afirst
  1674. # undef afirst
  1675. # endif
  1676. # ifdef bgr
  1677. # undef bgr
  1678. # endif
  1679. png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
  1680. entries);
  1681. if (num_trans > 0)
  1682. png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS,
  1683. num_trans, NULL);
  1684. image->colormap_entries = (png_uint_32)entries;
  1685. }
  1686. static int
  1687. png_image_write_main(png_voidp argument)
  1688. {
  1689. png_image_write_control *display = png_voidcast(png_image_write_control*,
  1690. argument);
  1691. png_imagep image = display->image;
  1692. png_structrp png_ptr = image->opaque->png_ptr;
  1693. png_inforp info_ptr = image->opaque->info_ptr;
  1694. png_uint_32 format = image->format;
  1695. /* The following four ints are actually booleans */
  1696. int colormap = (format & PNG_FORMAT_FLAG_COLORMAP);
  1697. int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR); /* input */
  1698. int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA);
  1699. int write_16bit = linear && (display->convert_to_8bit == 0);
  1700. # ifdef PNG_BENIGN_ERRORS_SUPPORTED
  1701. /* Make sure we error out on any bad situation */
  1702. png_set_benign_errors(png_ptr, 0/*error*/);
  1703. # endif
  1704. /* Default the 'row_stride' parameter if required, also check the row stride
  1705. * and total image size to ensure that they are within the system limits.
  1706. */
  1707. {
  1708. unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
  1709. if (image->width <= 0x7fffffffU/channels) /* no overflow */
  1710. {
  1711. png_uint_32 check;
  1712. png_uint_32 png_row_stride = image->width * channels;
  1713. if (display->row_stride == 0)
  1714. display->row_stride = (png_int_32)/*SAFE*/png_row_stride;
  1715. if (display->row_stride < 0)
  1716. check = (png_uint_32)(-display->row_stride);
  1717. else
  1718. check = (png_uint_32)display->row_stride;
  1719. if (check >= png_row_stride)
  1720. {
  1721. /* Now check for overflow of the image buffer calculation; this
  1722. * limits the whole image size to 32 bits for API compatibility with
  1723. * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
  1724. */
  1725. if (image->height > 0xffffffffU/png_row_stride)
  1726. png_error(image->opaque->png_ptr, "memory image too large");
  1727. }
  1728. else
  1729. png_error(image->opaque->png_ptr, "supplied row stride too small");
  1730. }
  1731. else
  1732. png_error(image->opaque->png_ptr, "image row stride too large");
  1733. }
  1734. /* Set the required transforms then write the rows in the correct order. */
  1735. if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0)
  1736. {
  1737. if (display->colormap != NULL && image->colormap_entries > 0)
  1738. {
  1739. png_uint_32 entries = image->colormap_entries;
  1740. png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
  1741. entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)),
  1742. PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
  1743. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  1744. png_image_set_PLTE(display);
  1745. }
  1746. else
  1747. png_error(image->opaque->png_ptr,
  1748. "no color-map for color-mapped image");
  1749. }
  1750. else
  1751. png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
  1752. write_16bit ? 16 : 8,
  1753. ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) +
  1754. ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0),
  1755. PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  1756. /* Counter-intuitively the data transformations must be called *after*
  1757. * png_write_info, not before as in the read code, but the 'set' functions
  1758. * must still be called before. Just set the color space information, never
  1759. * write an interlaced image.
  1760. */
  1761. if (write_16bit != 0)
  1762. {
  1763. /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */
  1764. png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR);
  1765. if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
  1766. png_set_cHRM_fixed(png_ptr, info_ptr,
  1767. /* color x y */
  1768. /* white */ 31270, 32900,
  1769. /* red */ 64000, 33000,
  1770. /* green */ 30000, 60000,
  1771. /* blue */ 15000, 6000
  1772. );
  1773. }
  1774. else if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
  1775. png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);
  1776. /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit
  1777. * space must still be gamma encoded.
  1778. */
  1779. else
  1780. png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE);
  1781. /* Write the file header. */
  1782. png_write_info(png_ptr, info_ptr);
  1783. /* Now set up the data transformations (*after* the header is written),
  1784. * remove the handled transformations from the 'format' flags for checking.
  1785. *
  1786. * First check for a little endian system if writing 16-bit files.
  1787. */
  1788. if (write_16bit != 0)
  1789. {
  1790. png_uint_16 le = 0x0001;
  1791. if ((*(png_const_bytep) & le) != 0)
  1792. png_set_swap(png_ptr);
  1793. }
  1794. # ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
  1795. if ((format & PNG_FORMAT_FLAG_BGR) != 0)
  1796. {
  1797. if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0)
  1798. png_set_bgr(png_ptr);
  1799. format &= ~PNG_FORMAT_FLAG_BGR;
  1800. }
  1801. # endif
  1802. # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
  1803. if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
  1804. {
  1805. if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
  1806. png_set_swap_alpha(png_ptr);
  1807. format &= ~PNG_FORMAT_FLAG_AFIRST;
  1808. }
  1809. # endif
  1810. /* If there are 16 or fewer color-map entries we wrote a lower bit depth
  1811. * above, but the application data is still byte packed.
  1812. */
  1813. if (colormap != 0 && image->colormap_entries <= 16)
  1814. png_set_packing(png_ptr);
  1815. /* That should have handled all (both) the transforms. */
  1816. if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR |
  1817. PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0)
  1818. png_error(png_ptr, "png_write_image: unsupported transformation");
  1819. {
  1820. png_const_bytep row = png_voidcast(png_const_bytep, display->buffer);
  1821. ptrdiff_t row_bytes = display->row_stride;
  1822. if (linear != 0)
  1823. row_bytes *= (sizeof (png_uint_16));
  1824. if (row_bytes < 0)
  1825. row += (image->height-1) * (-row_bytes);
  1826. display->first_row = row;
  1827. display->row_bytes = row_bytes;
  1828. }
  1829. /* Apply 'fast' options if the flag is set. */
  1830. if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0)
  1831. {
  1832. png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS);
  1833. /* NOTE: determined by experiment using pngstest, this reflects some
  1834. * balance between the time to write the image once and the time to read
  1835. * it about 50 times. The speed-up in pngstest was about 10-20% of the
  1836. * total (user) time on a heavily loaded system.
  1837. */
  1838. # ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
  1839. png_set_compression_level(png_ptr, 3);
  1840. # endif
  1841. }
  1842. /* Check for the cases that currently require a pre-transform on the row
  1843. * before it is written. This only applies when the input is 16-bit and
  1844. * either there is an alpha channel or it is converted to 8-bit.
  1845. */
  1846. if ((linear != 0 && alpha != 0 ) ||
  1847. (colormap == 0 && display->convert_to_8bit != 0))
  1848. {
  1849. png_bytep row = png_voidcast(png_bytep, png_malloc(png_ptr,
  1850. png_get_rowbytes(png_ptr, info_ptr)));
  1851. int result;
  1852. display->local_row = row;
  1853. if (write_16bit != 0)
  1854. result = png_safe_execute(image, png_write_image_16bit, display);
  1855. else
  1856. result = png_safe_execute(image, png_write_image_8bit, display);
  1857. display->local_row = NULL;
  1858. png_free(png_ptr, row);
  1859. /* Skip the 'write_end' on error: */
  1860. if (result == 0)
  1861. return 0;
  1862. }
  1863. /* Otherwise this is the case where the input is in a format currently
  1864. * supported by the rest of the libpng write code; call it directly.
  1865. */
  1866. else
  1867. {
  1868. png_const_bytep row = png_voidcast(png_const_bytep, display->first_row);
  1869. ptrdiff_t row_bytes = display->row_bytes;
  1870. png_uint_32 y = image->height;
  1871. for (; y > 0; --y)
  1872. {
  1873. png_write_row(png_ptr, row);
  1874. row += row_bytes;
  1875. }
  1876. }
  1877. png_write_end(png_ptr, info_ptr);
  1878. return 1;
  1879. }
  1880. static void (PNGCBAPI
  1881. image_memory_write)(png_structp png_ptr, png_bytep/*const*/ data, size_t size)
  1882. {
  1883. png_image_write_control *display = png_voidcast(png_image_write_control*,
  1884. png_ptr->io_ptr/*backdoor: png_get_io_ptr(png_ptr)*/);
  1885. png_alloc_size_t ob = display->output_bytes;
  1886. /* Check for overflow; this should never happen: */
  1887. if (size <= ((png_alloc_size_t)-1) - ob)
  1888. {
  1889. /* I don't think libpng ever does this, but just in case: */
  1890. if (size > 0)
  1891. {
  1892. if (display->memory_bytes >= ob+size) /* writing */
  1893. memcpy(display->memory+ob, data, size);
  1894. /* Always update the size: */
  1895. display->output_bytes = ob+size;
  1896. }
  1897. }
  1898. else
  1899. png_error(png_ptr, "png_image_write_to_memory: PNG too big");
  1900. }
  1901. static void (PNGCBAPI
  1902. image_memory_flush)(png_structp png_ptr)
  1903. {
  1904. PNG_UNUSED(png_ptr)
  1905. }
  1906. static int
  1907. png_image_write_memory(png_voidp argument)
  1908. {
  1909. png_image_write_control *display = png_voidcast(png_image_write_control*,
  1910. argument);
  1911. /* The rest of the memory-specific init and write_main in an error protected
  1912. * environment. This case needs to use callbacks for the write operations
  1913. * since libpng has no built in support for writing to memory.
  1914. */
  1915. png_set_write_fn(display->image->opaque->png_ptr, display/*io_ptr*/,
  1916. image_memory_write, image_memory_flush);
  1917. return png_image_write_main(display);
  1918. }
  1919. int PNGAPI
  1920. png_image_write_to_memory(png_imagep image, void *memory,
  1921. png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8bit,
  1922. const void *buffer, png_int_32 row_stride, const void *colormap)
  1923. {
  1924. /* Write the image to the given buffer, or count the bytes if it is NULL */
  1925. if (image != NULL && image->version == PNG_IMAGE_VERSION)
  1926. {
  1927. if (memory_bytes != NULL && buffer != NULL)
  1928. {
  1929. /* This is to give the caller an easier error detection in the NULL
  1930. * case and guard against uninitialized variable problems:
  1931. */
  1932. if (memory == NULL)
  1933. *memory_bytes = 0;
  1934. if (png_image_write_init(image) != 0)
  1935. {
  1936. png_image_write_control display;
  1937. int result;
  1938. memset(&display, 0, (sizeof display));
  1939. display.image = image;
  1940. display.buffer = buffer;
  1941. display.row_stride = row_stride;
  1942. display.colormap = colormap;
  1943. display.convert_to_8bit = convert_to_8bit;
  1944. display.memory = png_voidcast(png_bytep, memory);
  1945. display.memory_bytes = *memory_bytes;
  1946. display.output_bytes = 0;
  1947. result = png_safe_execute(image, png_image_write_memory, &display);
  1948. png_image_free(image);
  1949. /* write_memory returns true even if we ran out of buffer. */
  1950. if (result)
  1951. {
  1952. /* On out-of-buffer this function returns '0' but still updates
  1953. * memory_bytes:
  1954. */
  1955. if (memory != NULL && display.output_bytes > *memory_bytes)
  1956. result = 0;
  1957. *memory_bytes = display.output_bytes;
  1958. }
  1959. return result;
  1960. }
  1961. else
  1962. return 0;
  1963. }
  1964. else
  1965. return png_image_error(image,
  1966. "png_image_write_to_memory: invalid argument");
  1967. }
  1968. else if (image != NULL)
  1969. return png_image_error(image,
  1970. "png_image_write_to_memory: incorrect PNG_IMAGE_VERSION");
  1971. else
  1972. return 0;
  1973. }
  1974. #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
  1975. int PNGAPI
  1976. png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit,
  1977. const void *buffer, png_int_32 row_stride, const void *colormap)
  1978. {
  1979. /* Write the image to the given FILE object. */
  1980. if (image != NULL && image->version == PNG_IMAGE_VERSION)
  1981. {
  1982. if (file != NULL && buffer != NULL)
  1983. {
  1984. if (png_image_write_init(image) != 0)
  1985. {
  1986. png_image_write_control display;
  1987. int result;
  1988. /* This is slightly evil, but png_init_io doesn't do anything other
  1989. * than this and we haven't changed the standard IO functions so
  1990. * this saves a 'safe' function.
  1991. */
  1992. image->opaque->png_ptr->io_ptr = file;
  1993. memset(&display, 0, (sizeof display));
  1994. display.image = image;
  1995. display.buffer = buffer;
  1996. display.row_stride = row_stride;
  1997. display.colormap = colormap;
  1998. display.convert_to_8bit = convert_to_8bit;
  1999. result = png_safe_execute(image, png_image_write_main, &display);
  2000. png_image_free(image);
  2001. return result;
  2002. }
  2003. else
  2004. return 0;
  2005. }
  2006. else
  2007. return png_image_error(image,
  2008. "png_image_write_to_stdio: invalid argument");
  2009. }
  2010. else if (image != NULL)
  2011. return png_image_error(image,
  2012. "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION");
  2013. else
  2014. return 0;
  2015. }
  2016. int PNGAPI
  2017. png_image_write_to_file(png_imagep image, const char *file_name,
  2018. int convert_to_8bit, const void *buffer, png_int_32 row_stride,
  2019. const void *colormap)
  2020. {
  2021. /* Write the image to the named file. */
  2022. if (image != NULL && image->version == PNG_IMAGE_VERSION)
  2023. {
  2024. if (file_name != NULL && buffer != NULL)
  2025. {
  2026. FILE *fp = fopen(file_name, "wb");
  2027. if (fp != NULL)
  2028. {
  2029. if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer,
  2030. row_stride, colormap) != 0)
  2031. {
  2032. int error; /* from fflush/fclose */
  2033. /* Make sure the file is flushed correctly. */
  2034. if (fflush(fp) == 0 && ferror(fp) == 0)
  2035. {
  2036. if (fclose(fp) == 0)
  2037. return 1;
  2038. error = errno; /* from fclose */
  2039. }
  2040. else
  2041. {
  2042. error = errno; /* from fflush or ferror */
  2043. (void)fclose(fp);
  2044. }
  2045. (void)remove(file_name);
  2046. /* The image has already been cleaned up; this is just used to
  2047. * set the error (because the original write succeeded).
  2048. */
  2049. return png_image_error(image, strerror(error));
  2050. }
  2051. else
  2052. {
  2053. /* Clean up: just the opened file. */
  2054. (void)fclose(fp);
  2055. (void)remove(file_name);
  2056. return 0;
  2057. }
  2058. }
  2059. else
  2060. return png_image_error(image, strerror(errno));
  2061. }
  2062. else
  2063. return png_image_error(image,
  2064. "png_image_write_to_file: invalid argument");
  2065. }
  2066. else if (image != NULL)
  2067. return png_image_error(image,
  2068. "png_image_write_to_file: incorrect PNG_IMAGE_VERSION");
  2069. else
  2070. return 0;
  2071. }
  2072. #endif /* SIMPLIFIED_WRITE_STDIO */
  2073. #endif /* SIMPLIFIED_WRITE */
  2074. #endif /* WRITE */