ImagingNetworkGraphics.pas 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573
  1. {
  2. $Id$
  3. Vampyre Imaging Library
  4. by Marek Mauder
  5. http://imaginglib.sourceforge.net
  6. The contents of this file are used with permission, subject to the Mozilla
  7. Public License Version 1.1 (the "License"); you may not use this file except
  8. in compliance with the License. You may obtain a copy of the License at
  9. http://www.mozilla.org/MPL/MPL-1.1.html
  10. Software distributed under the License is distributed on an "AS IS" basis,
  11. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
  12. the specific language governing rights and limitations under the License.
  13. Alternatively, the contents of this file may be used under the terms of the
  14. GNU Lesser General Public License (the "LGPL License"), in which case the
  15. provisions of the LGPL License are applicable instead of those above.
  16. If you wish to allow use of your version of this file only under the terms
  17. of the LGPL License and not to allow others to use your version of this file
  18. under the MPL, indicate your decision by deleting the provisions above and
  19. replace them with the notice and other provisions required by the LGPL
  20. License. If you do not delete the provisions above, a recipient may use
  21. your version of this file under either the MPL or the LGPL License.
  22. For more information about the LGPL: http://www.gnu.org/copyleft/lesser.html
  23. }
  24. { This unit contains image format loaders/savers for Network Graphics image
  25. file formats PNG, MNG, and JNG.}
  26. unit ImagingNetworkGraphics;
  27. interface
  28. {$I ImagingOptions.inc}
  29. { If MN support is enabled we must make sure PNG and JNG are enabled too.}
  30. {$IFNDEF DONT_LINK_MNG}
  31. {$UNDEF DONT_LINK_PNG}
  32. {$UNDEF DONT_LINK_JNG}
  33. {$ENDIF}
  34. uses
  35. Types, SysUtils, Classes, ImagingTypes, Imaging, ImagingUtility, ImagingFormats, dzlib;
  36. type
  37. { Basic class for Network Graphics file formats loaders/savers.}
  38. TNetworkGraphicsFileFormat = class(TImageFileFormat)
  39. protected
  40. FSignature: TChar8;
  41. FPreFilter: LongInt;
  42. FCompressLevel: LongInt;
  43. FLossyCompression: LongBool;
  44. FLossyAlpha: LongBool;
  45. FQuality: LongInt;
  46. FProgressive: LongBool;
  47. function GetSupportedFormats: TImageFormats; override;
  48. procedure ConvertToSupported(var Image: TImageData;
  49. const Info: TImageFormatInfo); override;
  50. public
  51. constructor Create; override;
  52. function TestFormat(Handle: TImagingHandle): Boolean; override;
  53. procedure CheckOptionsValidity; override;
  54. published
  55. { Sets precompression filter used when saving images with lossless compression.
  56. Allowed values are: 0 (none), 1 (sub), 2 (up), 3 (average), 4 (paeth),
  57. 5 (use 0 for indexed/gray images and 4 for RGB/ARGB images),
  58. 6 (adaptive filtering - use best filter for each scanline - very slow).
  59. Note that filters 3 and 4 are much slower than filters 1 and 2.
  60. Default value is 5.}
  61. property PreFilter: LongInt read FPreFilter write FPreFilter;
  62. { Sets ZLib compression level used when saving images with lossless compression.
  63. Allowed values are in range 0 (no compresstion) to 9 (best compression).
  64. Default value is 5.}
  65. property CompressLevel: LongInt read FCompressLevel write FCompressLevel;
  66. { Specifies whether MNG animation frames are saved with lossy or lossless
  67. compression. Lossless frames are saved as PNG images and lossy frames are
  68. saved as JNG images. Allowed values are 0 (False) and 1 (True).
  69. Default value is 0.}
  70. property LossyCompression: LongBool read FLossyCompression write FLossyCompression;
  71. { Defines whether alpha channel of lossy MNG frames or JNG images
  72. is lossy compressed too. Allowed values are 0 (False) and 1 (True).
  73. Default value is 0.}
  74. property LossyAlpha: LongBool read FLossyAlpha write FLossyAlpha;
  75. { Specifies compression quality used when saving lossy MNG frames or JNG images.
  76. For details look at ImagingJpegQuality option.}
  77. property Quality: LongInt read FQuality write FQuality;
  78. { Specifies whether images are saved in progressive format when saving lossy
  79. MNG frames or JNG images. For details look at ImagingJpegProgressive.}
  80. property Progressive: LongBool read FProgressive write FProgressive;
  81. end;
  82. { Class for loading Portable Network Graphics Images.
  83. Loads all types of this image format (all images in png test suite)
  84. and saves all types with bitcount >= 8 (non-interlaced only).
  85. Compression level and filtering can be set by options interface.
  86. Supported ancillary chunks (loading):
  87. tRNS, bKGD
  88. (for indexed images transparency contains alpha values for palette,
  89. RGB/Gray images with transparency are converted to formats with alpha
  90. and pixels with transparent color are replaced with background color
  91. with alpha = 0).}
  92. TPNGFileFormat = class(TNetworkGraphicsFileFormat)
  93. private
  94. FLoadAnimated: LongBool;
  95. protected
  96. function LoadData(Handle: TImagingHandle; var Images: TDynImageDataArray;
  97. OnlyFirstLevel: Boolean): Boolean; override;
  98. function SaveData(Handle: TImagingHandle; const Images: TDynImageDataArray;
  99. Index: LongInt): Boolean; override;
  100. public
  101. constructor Create; override;
  102. published
  103. property LoadAnimated: LongBool read FLoadAnimated write FLoadAnimated;
  104. end;
  105. {$IFNDEF DONT_LINK_MNG}
  106. { Class for loading Multiple Network Graphics files.
  107. This format has complex animation capabilities but Imaging only
  108. extracts frames. Individual frames are stored as standard PNG or JNG
  109. images. Loads all types of these frames stored in IHDR-IEND and
  110. JHDR-IEND streams (Note that there are MNG chunks
  111. like BASI which define images but does not contain image data itself,
  112. those are ignored).
  113. Imaging saves MNG files as MNG-VLC (very low complexity) so it is basicaly
  114. an array of image frames without MNG animation chunks. Frames can be saved
  115. as lossless PNG or lossy JNG images (look at TPNGFileFormat and
  116. TJNGFileFormat for info). Every frame can be in different data format.
  117. Many frame compression settings can be modified by options interface.}
  118. TMNGFileFormat = class(TNetworkGraphicsFileFormat)
  119. protected
  120. function LoadData(Handle: TImagingHandle; var Images: TDynImageDataArray;
  121. OnlyFirstLevel: Boolean): Boolean; override;
  122. function SaveData(Handle: TImagingHandle; const Images: TDynImageDataArray;
  123. Index: LongInt): Boolean; override;
  124. public
  125. constructor Create; override;
  126. end;
  127. {$ENDIF}
  128. {$IFNDEF DONT_LINK_JNG}
  129. { Class for loading JPEG Network Graphics Images.
  130. Loads all types of this image format (all images in jng test suite)
  131. and saves all types except 12 bit JPEGs.
  132. Alpha channel in JNG images is stored separately from color/gray data and
  133. can be lossy (as JPEG image) or lossless (as PNG image) compressed.
  134. Type of alpha compression, compression level and quality,
  135. and filtering can be set by options interface.
  136. Supported ancillary chunks (loading):
  137. tRNS, bKGD
  138. (Images with transparency are converted to formats with alpha
  139. and pixels with transparent color are replaced with background color
  140. with alpha = 0).}
  141. TJNGFileFormat = class(TNetworkGraphicsFileFormat)
  142. protected
  143. function LoadData(Handle: TImagingHandle; var Images: TDynImageDataArray;
  144. OnlyFirstLevel: Boolean): Boolean; override;
  145. function SaveData(Handle: TImagingHandle; const Images: TDynImageDataArray;
  146. Index: LongInt): Boolean; override;
  147. public
  148. constructor Create; override;
  149. end;
  150. {$ENDIF}
  151. implementation
  152. uses
  153. {$IFNDEF DONT_LINK_JNG}
  154. ImagingJpeg, ImagingIO,
  155. {$ENDIF}
  156. ImagingCanvases;
  157. const
  158. NGDefaultPreFilter = 5;
  159. NGDefaultCompressLevel = 5;
  160. NGDefaultLossyAlpha = False;
  161. NGDefaultLossyCompression = False;
  162. NGDefaultProgressive = False;
  163. NGDefaultQuality = 90;
  164. NGLosslessFormats: TImageFormats = [ifIndex8, ifGray8, ifA8Gray8, ifGray16,
  165. ifA16Gray16, ifR8G8B8, ifA8R8G8B8, ifR16G16B16, ifA16R16G16B16, ifB16G16R16,
  166. ifA16B16G16R16];
  167. NGLossyFormats: TImageFormats = [ifGray8, ifA8Gray8, ifR8G8B8, ifA8R8G8B8];
  168. PNGDefaultLoadAnimated = True;
  169. SPNGFormatName = 'Portable Network Graphics';
  170. SPNGMasks = '*.png';
  171. SMNGFormatName = 'Multiple Network Graphics';
  172. SMNGMasks = '*.mng';
  173. SJNGFormatName = 'JPEG Network Graphics';
  174. SJNGMasks = '*.jng';
  175. resourcestring
  176. SErrorLoadingChunk = 'Error when reading %s chunk data. File may be corrupted.';
  177. type
  178. { Chunk header.}
  179. TChunkHeader = packed record
  180. DataSize: LongWord;
  181. ChunkID: TChar4;
  182. end;
  183. { IHDR chunk format - PNG header.}
  184. TIHDR = packed record
  185. Width: LongWord; // Image width
  186. Height: LongWord; // Image height
  187. BitDepth: Byte; // Bits per pixel or bits per sample (for truecolor)
  188. ColorType: Byte; // 0 = grayscale, 2 = truecolor, 3 = palette,
  189. // 4 = gray + alpha, 6 = truecolor + alpha
  190. Compression: Byte; // Compression type: 0 = ZLib
  191. Filter: Byte; // Used precompress filter
  192. Interlacing: Byte; // Used interlacing: 0 = no int, 1 = Adam7
  193. end;
  194. PIHDR = ^TIHDR;
  195. { MHDR chunk format - MNG header.}
  196. TMHDR = packed record
  197. FrameWidth: LongWord; // Frame width
  198. FrameHeight: LongWord; // Frame height
  199. TicksPerSecond: LongWord; // FPS of animation
  200. NominalLayerCount: LongWord; // Number of layers in file
  201. NominalFrameCount: LongWord; // Number of frames in file
  202. NominalPlayTime: LongWord; // Play time of animation in ticks
  203. SimplicityProfile: LongWord; // Defines which MNG features are used in this file
  204. end;
  205. PMHDR = ^TMHDR;
  206. { JHDR chunk format - JNG header.}
  207. TJHDR = packed record
  208. Width: LongWord; // Image width
  209. Height: LongWord; // Image height
  210. ColorType: Byte; // 8 = grayscale (Y), 10 = color (YCbCr),
  211. // 12 = gray + alpha (Y-alpha), 14 = color + alpha (YCbCr-alpha)
  212. SampleDepth: Byte; // 8, 12 or 20 (8 and 12 samples together) bit
  213. Compression: Byte; // Compression type: 8 = Huffman coding
  214. Interlacing: Byte; // 0 = single scan, 8 = progressive
  215. AlphaSampleDepth: Byte; // 0, 1, 2, 4, 8, 16 if alpha compression is 0 (PNG)
  216. // 8 if alpha compression is 8 (JNG)
  217. AlphaCompression: Byte; // 0 = PNG graysscale IDAT, 8 = grayscale 8-bit JPEG
  218. AlphaFilter: Byte; // 0 = PNG filter or no filter (JPEG)
  219. AlphaInterlacing: Byte; // 0 = non interlaced
  220. end;
  221. PJHDR = ^TJHDR;
  222. { acTL chunk format - APNG animation control.}
  223. TacTL = packed record
  224. NumFrames: LongWord; // Number of frames
  225. NumPlay: LongWord; // Number of times to loop the animation (0 = inf)
  226. end;
  227. PacTL =^TacTL;
  228. { fcTL chunk format - APNG frame control.}
  229. TfcTL = packed record
  230. SeqNumber: LongWord; // Sequence number of the animation chunk, starting from 0
  231. Width: LongWord; // Width of the following frame
  232. Height: LongWord; // Height of the following frame
  233. XOffset: LongWord; // X position at which to render the following frame
  234. YOffset: LongWord; // Y position at which to render the following frame
  235. DelayNumer: Word; // Frame delay fraction numerator
  236. DelayDenom: Word; // Frame delay fraction denominator
  237. DisposeOp: Byte; // Type of frame area disposal to be done after rendering this frame
  238. BlendOp: Byte; // Type of frame area rendering for this frame
  239. end;
  240. PfcTL = ^TfcTL;
  241. const
  242. { PNG file identifier.}
  243. PNGSignature: TChar8 = #$89'PNG'#$0D#$0A#$1A#$0A;
  244. { MNG file identifier.}
  245. MNGSignature: TChar8 = #$8A'MNG'#$0D#$0A#$1A#$0A;
  246. { JNG file identifier.}
  247. JNGSignature: TChar8 = #$8B'JNG'#$0D#$0A#$1A#$0A;
  248. { Constants for chunk identifiers and signature identifiers.
  249. They are in big-endian format.}
  250. IHDRChunk: TChar4 = 'IHDR';
  251. IENDChunk: TChar4 = 'IEND';
  252. MHDRChunk: TChar4 = 'MHDR';
  253. MENDChunk: TChar4 = 'MEND';
  254. JHDRChunk: TChar4 = 'JHDR';
  255. IDATChunk: TChar4 = 'IDAT';
  256. JDATChunk: TChar4 = 'JDAT';
  257. JDAAChunk: TChar4 = 'JDAA';
  258. JSEPChunk: TChar4 = 'JSEP';
  259. PLTEChunk: TChar4 = 'PLTE';
  260. BACKChunk: TChar4 = 'BACK';
  261. DEFIChunk: TChar4 = 'DEFI';
  262. TERMChunk: TChar4 = 'TERM';
  263. tRNSChunk: TChar4 = 'tRNS';
  264. bKGDChunk: TChar4 = 'bKGD';
  265. gAMAChunk: TChar4 = 'gAMA';
  266. acTLChunk: TChar4 = 'acTL';
  267. fcTLChunk: TChar4 = 'fcTL';
  268. fdATChunk: TChar4 = 'fdAT';
  269. { APNG frame dispose operations.}
  270. DisposeOpNone = 0;
  271. DisposeOpBackground = 1;
  272. DisposeOpPrevious = 2;
  273. { APNG frame blending modes}
  274. BlendOpSource = 0;
  275. BlendOpOver = 1;
  276. { Interlace start and offsets.}
  277. RowStart: array[0..6] of LongInt = (0, 0, 4, 0, 2, 0, 1);
  278. ColumnStart: array[0..6] of LongInt = (0, 4, 0, 2, 0, 1, 0);
  279. RowIncrement: array[0..6] of LongInt = (8, 8, 8, 4, 4, 2, 2);
  280. ColumnIncrement: array[0..6] of LongInt = (8, 8, 4, 4, 2, 2, 1);
  281. type
  282. { Helper class that holds information about MNG frame in PNG or JNG format.}
  283. TFrameInfo = class(TObject)
  284. public
  285. FrameWidth, FrameHeight: LongInt;
  286. IsJpegFrame: Boolean;
  287. IHDR: TIHDR;
  288. JHDR: TJHDR;
  289. fcTL: TfcTL;
  290. Palette: PPalette24;
  291. PaletteEntries: LongInt;
  292. Transparency: Pointer;
  293. TransparencySize: LongInt;
  294. Background: Pointer;
  295. BackgroundSize: LongInt;
  296. IDATMemory: TMemoryStream;
  297. JDATMemory: TMemoryStream;
  298. JDAAMemory: TMemoryStream;
  299. constructor Create;
  300. destructor Destroy; override;
  301. procedure AssignSharedProps(Source: TFrameInfo);
  302. end;
  303. { Defines type of Network Graphics file.}
  304. TNGFileType = (ngPNG, ngAPNG, ngMNG, ngJNG);
  305. TNGFileHandler = class(TObject)
  306. public
  307. FileType: TNGFileType;
  308. Frames: array of TFrameInfo;
  309. MHDR: TMHDR; // Main header for MNG files
  310. acTL: TacTL; // Global anim control for APNG files
  311. GlobalPalette: PPalette24;
  312. GlobalPaletteEntries: LongInt;
  313. GlobalTransparency: Pointer;
  314. GlobalTransparencySize: LongInt;
  315. destructor Destroy; override;
  316. procedure Clear;
  317. function GetLastFrame: TFrameInfo;
  318. function AddFrameInfo: TFrameInfo;
  319. end;
  320. { Network Graphics file parser and frame converter.}
  321. TNGFileLoader = class(TNGFileHandler)
  322. public
  323. function LoadFile(Handle: TImagingHandle): Boolean;
  324. procedure LoadImageFromPNGFrame(FrameWidth, FrameHeight: LongInt; const IHDR: TIHDR; IDATStream: TMemoryStream; var Image: TImageData);
  325. {$IFNDEF DONT_LINK_JNG}
  326. procedure LoadImageFromJNGFrame(FrameWidth, FrameHeight: LongInt; const JHDR: TJHDR; IDATStream, JDATStream, JDAAStream: TMemoryStream; var Image: TImageData);
  327. {$ENDIF}
  328. procedure ApplyFrameSettings(Frame: TFrameInfo; var Image: TImageData);
  329. end;
  330. TNGFileSaver = class(TNGFileHandler)
  331. public
  332. PreFilter: LongInt;
  333. CompressLevel: LongInt;
  334. LossyAlpha: Boolean;
  335. Quality: LongInt;
  336. Progressive: Boolean;
  337. function SaveFile(Handle: TImagingHandle): Boolean;
  338. procedure AddFrame(const Image: TImageData; IsJpegFrame: Boolean);
  339. procedure StoreImageToPNGFrame(const IHDR: TIHDR; Bits: Pointer; FmtInfo: TImageFormatInfo; IDATStream: TMemoryStream);
  340. {$IFNDEF DONT_LINK_JNG}
  341. procedure StoreImageToJNGFrame(const JHDR: TJHDR; const Image: TImageData; IDATStream, JDATStream, JDAAStream: TMemoryStream);
  342. {$ENDIF}
  343. procedure SetFileOptions(FileFormat: TNetworkGraphicsFileFormat);
  344. end;
  345. {$IFNDEF DONT_LINK_JNG}
  346. TCustomIOJpegFileFormat = class(TJpegFileFormat)
  347. protected
  348. FCustomIO: TIOFunctions;
  349. procedure SetJpegIO(const JpegIO: TIOFunctions); override;
  350. procedure SetCustomIO(const CustomIO: TIOFunctions);
  351. end;
  352. {$ENDIF}
  353. TAPNGAnimator = class
  354. public
  355. class procedure Animate(var Images: TDynImageDataArray; const acTL: TacTL; const SrcFrames: array of TFrameInfo);
  356. end;
  357. { Helper routines }
  358. function PaethPredictor(A, B, C: LongInt): LongInt; {$IFDEF USE_INLINE}inline;{$ENDIF}
  359. var
  360. P, PA, PB, PC: LongInt;
  361. begin
  362. P := A + B - C;
  363. PA := Abs(P - A);
  364. PB := Abs(P - B);
  365. PC := Abs(P - C);
  366. if (PA <= PB) and (PA <= PC) then
  367. Result := A
  368. else
  369. if PB <= PC then
  370. Result := B
  371. else
  372. Result := C;
  373. end;
  374. procedure SwapRGB(Line: PByte; Width, SampleDepth, BytesPerPixel: LongInt);
  375. var
  376. I: LongInt;
  377. Tmp: Word;
  378. begin
  379. case SampleDepth of
  380. 8:
  381. for I := 0 to Width - 1 do
  382. with PColor24Rec(Line)^ do
  383. begin
  384. Tmp := R;
  385. R := B;
  386. B := Tmp;
  387. Inc(Line, BytesPerPixel);
  388. end;
  389. 16:
  390. for I := 0 to Width - 1 do
  391. with PColor48Rec(Line)^ do
  392. begin
  393. Tmp := R;
  394. R := B;
  395. B := Tmp;
  396. Inc(Line, BytesPerPixel);
  397. end;
  398. end;
  399. end;
  400. const
  401. { Helper constants for 1/2/4 bit to 8 bit conversions.}
  402. Mask1: array[0..7] of Byte = ($80, $40, $20, $10, $08, $04, $02, $01);
  403. Shift1: array[0..7] of Byte = (7, 6, 5, 4, 3, 2, 1, 0);
  404. Mask2: array[0..3] of Byte = ($C0, $30, $0C, $03);
  405. Shift2: array[0..3] of Byte = (6, 4, 2, 0);
  406. Mask4: array[0..1] of Byte = ($F0, $0F);
  407. Shift4: array[0..1] of Byte = (4, 0);
  408. function Get1BitPixel(Line: PByteArray; X: LongInt): Byte;
  409. begin
  410. Result := (Line[X shr 3] and Mask1[X and 7]) shr
  411. Shift1[X and 7];
  412. end;
  413. function Get2BitPixel(Line: PByteArray; X: LongInt): Byte;
  414. begin
  415. Result := (Line[X shr 2] and Mask2[X and 3]) shr
  416. Shift2[X and 3];
  417. end;
  418. function Get4BitPixel(Line: PByteArray; X: LongInt): Byte;
  419. begin
  420. Result := (Line[X shr 1] and Mask4[X and 1]) shr
  421. Shift4[X and 1];
  422. end;
  423. {$IFNDEF DONT_LINK_JNG}
  424. { TCustomIOJpegFileFormat class implementation }
  425. procedure TCustomIOJpegFileFormat.SetCustomIO(const CustomIO: TIOFunctions);
  426. begin
  427. FCustomIO := CustomIO;
  428. end;
  429. procedure TCustomIOJpegFileFormat.SetJpegIO(const JpegIO: TIOFunctions);
  430. begin
  431. inherited SetJpegIO(FCustomIO);
  432. end;
  433. {$ENDIF}
  434. { TFrameInfo class implementation }
  435. constructor TFrameInfo.Create;
  436. begin
  437. IDATMemory := TMemoryStream.Create;
  438. JDATMemory := TMemoryStream.Create;
  439. JDAAMemory := TMemoryStream.Create;
  440. end;
  441. destructor TFrameInfo.Destroy;
  442. begin
  443. FreeMem(Palette);
  444. FreeMem(Transparency);
  445. FreeMem(Background);
  446. IDATMemory.Free;
  447. JDATMemory.Free;
  448. JDAAMemory.Free;
  449. inherited Destroy;
  450. end;
  451. procedure TFrameInfo.AssignSharedProps(Source: TFrameInfo);
  452. begin
  453. IHDR := Source.IHDR;
  454. JHDR := Source.JHDR;
  455. PaletteEntries := Source.PaletteEntries;
  456. GetMem(Palette, PaletteEntries * SizeOf(TColor24Rec));
  457. Move(Source.Palette^, Palette^, PaletteEntries * SizeOf(TColor24Rec));
  458. TransparencySize := Source.TransparencySize;
  459. GetMem(Transparency, TransparencySize);
  460. Move(Source.Transparency^, Transparency^, TransparencySize);
  461. end;
  462. { TNGFileHandler class implementation}
  463. destructor TNGFileHandler.Destroy;
  464. begin
  465. Clear;
  466. inherited Destroy;
  467. end;
  468. procedure TNGFileHandler.Clear;
  469. var
  470. I: LongInt;
  471. begin
  472. for I := 0 to Length(Frames) - 1 do
  473. Frames[I].Free;
  474. SetLength(Frames, 0);
  475. FreeMemNil(GlobalPalette);
  476. GlobalPaletteEntries := 0;
  477. FreeMemNil(GlobalTransparency);
  478. GlobalTransparencySize := 0;
  479. end;
  480. function TNGFileHandler.GetLastFrame: TFrameInfo;
  481. var
  482. Len: LongInt;
  483. begin
  484. Len := Length(Frames);
  485. if Len > 0 then
  486. Result := Frames[Len - 1]
  487. else
  488. Result := nil;
  489. end;
  490. function TNGFileHandler.AddFrameInfo: TFrameInfo;
  491. var
  492. Len: LongInt;
  493. begin
  494. Len := Length(Frames);
  495. SetLength(Frames, Len + 1);
  496. Result := TFrameInfo.Create;
  497. Frames[Len] := Result;
  498. end;
  499. { TNGFileLoader class implementation}
  500. function TNGFileLoader.LoadFile(Handle: TImagingHandle): Boolean;
  501. var
  502. Sig: TChar8;
  503. Chunk: TChunkHeader;
  504. ChunkData: Pointer;
  505. ChunkCrc: LongWord;
  506. procedure ReadChunk;
  507. begin
  508. GetIO.Read(Handle, @Chunk, SizeOf(Chunk));
  509. Chunk.DataSize := SwapEndianLongWord(Chunk.DataSize);
  510. end;
  511. procedure ReadChunkData;
  512. var
  513. ReadBytes: LongWord;
  514. begin
  515. FreeMemNil(ChunkData);
  516. GetMem(ChunkData, Chunk.DataSize);
  517. ReadBytes := GetIO.Read(Handle, ChunkData, Chunk.DataSize);
  518. GetIO.Read(Handle, @ChunkCrc, SizeOf(ChunkCrc));
  519. if ReadBytes <> Chunk.DataSize then
  520. RaiseImaging(SErrorLoadingChunk, [string(Chunk.ChunkID)]);
  521. end;
  522. procedure SkipChunkData;
  523. begin
  524. GetIO.Seek(Handle, Chunk.DataSize + SizeOf(ChunkCrc), smFromCurrent);
  525. end;
  526. procedure StartNewPNGImage;
  527. var
  528. Frame: TFrameInfo;
  529. begin
  530. ReadChunkData;
  531. if Chunk.ChunkID = fcTLChunk then
  532. begin
  533. if (Length(Frames) = 1) and (Frames[0].IDATMemory.Size = 0) then
  534. begin
  535. // First fcTL chunk maybe for first IDAT frame which is alredy created
  536. Frame := Frames[0];
  537. end
  538. else
  539. begin
  540. // Subsequent APNG frames with data in fdAT
  541. Frame := AddFrameInfo;
  542. // Copy some shared props from first frame (IHDR is the same for all APNG frames, palette etc)
  543. Frame.AssignSharedProps(Frames[0]);
  544. end;
  545. Frame.fcTL := PfcTL(ChunkData)^;
  546. SwapEndianLongWord(@Frame.fcTL, 5);
  547. Frame.fcTL.DelayNumer := SwapEndianWord(Frame.fcTL.DelayNumer);
  548. Frame.fcTL.DelayDenom := SwapEndianWord(Frame.fcTL.DelayDenom);
  549. Frame.FrameWidth := Frame.fcTL.Width;
  550. Frame.FrameHeight := Frame.fcTL.Height;
  551. end
  552. else
  553. begin
  554. // This is frame defined by IHDR chunk
  555. Frame := AddFrameInfo;
  556. Frame.IHDR := PIHDR(ChunkData)^;
  557. SwapEndianLongWord(@Frame.IHDR, 2);
  558. Frame.FrameWidth := Frame.IHDR.Width;
  559. Frame.FrameHeight := Frame.IHDR.Height;
  560. end;
  561. Frame.IsJpegFrame := False;
  562. end;
  563. procedure StartNewJNGImage;
  564. var
  565. Frame: TFrameInfo;
  566. begin
  567. ReadChunkData;
  568. Frame := AddFrameInfo;
  569. Frame.IsJpegFrame := True;
  570. Frame.JHDR := PJHDR(ChunkData)^;
  571. SwapEndianLongWord(@Frame.JHDR, 2);
  572. Frame.FrameWidth := Frame.JHDR.Width;
  573. Frame.FrameHeight := Frame.JHDR.Height;
  574. end;
  575. procedure AppendIDAT;
  576. begin
  577. ReadChunkData;
  578. // Append current IDAT/fdAT chunk to storage stream
  579. if Chunk.ChunkID = IDATChunk then
  580. GetLastFrame.IDATMemory.Write(ChunkData^, Chunk.DataSize)
  581. else if Chunk.ChunkID = fdATChunk then
  582. GetLastFrame.IDATMemory.Write(PByteArray(ChunkData)[4], Chunk.DataSize - SizeOf(LongWord));
  583. end;
  584. procedure AppendJDAT;
  585. begin
  586. ReadChunkData;
  587. // Append current JDAT chunk to storage stream
  588. GetLastFrame.JDATMemory.Write(ChunkData^, Chunk.DataSize);
  589. end;
  590. procedure AppendJDAA;
  591. begin
  592. ReadChunkData;
  593. // Append current JDAA chunk to storage stream
  594. GetLastFrame.JDAAMemory.Write(ChunkData^, Chunk.DataSize);
  595. end;
  596. procedure LoadPLTE;
  597. begin
  598. ReadChunkData;
  599. if GetLastFrame = nil then
  600. begin
  601. // Load global palette
  602. GetMem(GlobalPalette, Chunk.DataSize);
  603. Move(ChunkData^, GlobalPalette^, Chunk.DataSize);
  604. GlobalPaletteEntries := Chunk.DataSize div 3;
  605. end
  606. else if GetLastFrame.Palette = nil then
  607. begin
  608. if (Chunk.DataSize = 0) and (GlobalPalette <> nil) then
  609. begin
  610. // Use global palette
  611. GetMem(GetLastFrame.Palette, GlobalPaletteEntries * SizeOf(TColor24Rec));
  612. Move(GlobalPalette^, GetLastFrame.Palette^, GlobalPaletteEntries * SizeOf(TColor24Rec));
  613. GetLastFrame.PaletteEntries := GlobalPaletteEntries;
  614. end
  615. else
  616. begin
  617. // Load pal from PLTE chunk
  618. GetMem(GetLastFrame.Palette, Chunk.DataSize);
  619. Move(ChunkData^, GetLastFrame.Palette^, Chunk.DataSize);
  620. GetLastFrame.PaletteEntries := Chunk.DataSize div 3;
  621. end;
  622. end;
  623. end;
  624. procedure LoadtRNS;
  625. begin
  626. ReadChunkData;
  627. if GetLastFrame = nil then
  628. begin
  629. // Load global transparency
  630. GetMem(GlobalTransparency, Chunk.DataSize);
  631. Move(ChunkData^, GlobalTransparency^, Chunk.DataSize);
  632. GlobalTransparencySize := Chunk.DataSize;
  633. end
  634. else if GetLastFrame.Transparency = nil then
  635. begin
  636. if (Chunk.DataSize = 0) and (GlobalTransparency <> nil) then
  637. begin
  638. // Use global transparency
  639. GetMem(GetLastFrame.Transparency, GlobalTransparencySize);
  640. Move(GlobalTransparency^, GetLastFrame.Transparency^, Chunk.DataSize);
  641. GetLastFrame.TransparencySize := GlobalTransparencySize;
  642. end
  643. else
  644. begin
  645. // Load pal from tRNS chunk
  646. GetMem(GetLastFrame.Transparency, Chunk.DataSize);
  647. Move(ChunkData^, GetLastFrame.Transparency^, Chunk.DataSize);
  648. GetLastFrame.TransparencySize := Chunk.DataSize;
  649. end;
  650. end;
  651. end;
  652. procedure LoadbKGD;
  653. begin
  654. ReadChunkData;
  655. if GetLastFrame.Background = nil then
  656. begin
  657. GetMem(GetLastFrame.Background, Chunk.DataSize);
  658. Move(ChunkData^, GetLastFrame.Background^, Chunk.DataSize);
  659. GetLastFrame.BackgroundSize := Chunk.DataSize;
  660. end;
  661. end;
  662. procedure HandleacTL;
  663. begin
  664. FileType := ngAPNG;
  665. ReadChunkData;
  666. acTL := PacTL(ChunkData)^;
  667. SwapEndianLongWord(@acTL, SizeOf(acTL) div SizeOf(LongWord));
  668. end;
  669. begin
  670. Result := False;
  671. Clear;
  672. ChunkData := nil;
  673. with GetIO do
  674. try
  675. Read(Handle, @Sig, SizeOf(Sig));
  676. // Set file type according to the signature
  677. if Sig = PNGSignature then FileType := ngPNG
  678. else if Sig = MNGSignature then FileType := ngMNG
  679. else if Sig = JNGSignature then FileType := ngJNG
  680. else Exit;
  681. if FileType = ngMNG then
  682. begin
  683. // Store MNG header if present
  684. ReadChunk;
  685. ReadChunkData;
  686. MHDR := PMHDR(ChunkData)^;
  687. SwapEndianLongWord(@MHDR, SizeOf(MHDR) div SizeOf(LongWord));
  688. end;
  689. // Read chunks until ending chunk or EOF is reached
  690. repeat
  691. ReadChunk;
  692. if (Chunk.ChunkID = IHDRChunk) or (Chunk.ChunkID = fcTLChunk) then StartNewPNGImage
  693. else if Chunk.ChunkID = JHDRChunk then StartNewJNGImage
  694. else if (Chunk.ChunkID = IDATChunk) or (Chunk.ChunkID = fdATChunk) then AppendIDAT
  695. else if Chunk.ChunkID = JDATChunk then AppendJDAT
  696. else if Chunk.ChunkID = JDAAChunk then AppendJDAA
  697. else if Chunk.ChunkID = PLTEChunk then LoadPLTE
  698. else if Chunk.ChunkID = tRNSChunk then LoadtRNS
  699. else if Chunk.ChunkID = bKGDChunk then LoadbKGD
  700. else if Chunk.ChunkID = acTLChunk then HandleacTL
  701. else SkipChunkData;
  702. until Eof(Handle) or (Chunk.ChunkID = MENDChunk) or
  703. ((FileType <> ngMNG) and (Chunk.ChunkID = IENDChunk));
  704. Result := True;
  705. finally
  706. FreeMemNil(ChunkData);
  707. end;
  708. end;
  709. procedure TNGFileLoader.LoadImageFromPNGFrame(FrameWidth, FrameHeight: LongInt; const IHDR: TIHDR;
  710. IDATStream: TMemoryStream; var Image: TImageData);
  711. type
  712. TGetPixelFunc = function(Line: PByteArray; X: LongInt): Byte;
  713. var
  714. LineBuffer: array[Boolean] of PByteArray;
  715. ActLine: Boolean;
  716. Data, TotalBuffer, ZeroLine, PrevLine: Pointer;
  717. BitCount, TotalSize, TotalPos, BytesPerPixel, I, Pass,
  718. SrcDataSize, BytesPerLine, InterlaceLineBytes, InterlaceWidth: LongInt;
  719. procedure DecodeAdam7;
  720. const
  721. BitTable: array[1..8] of LongInt = ($1, $3, 0, $F, 0, 0, 0, $FF);
  722. StartBit: array[1..8] of LongInt = (7, 6, 0, 4, 0, 0, 0, 0);
  723. var
  724. Src, Dst, Dst2: PByte;
  725. CurBit, Col: LongInt;
  726. begin
  727. Src := @LineBuffer[ActLine][1];
  728. Col := ColumnStart[Pass];
  729. with Image do
  730. case BitCount of
  731. 1, 2, 4:
  732. begin
  733. Dst := @PByteArray(Data)[I * BytesPerLine];
  734. repeat
  735. CurBit := StartBit[BitCount];
  736. repeat
  737. Dst2 := @PByteArray(Dst)[(BitCount * Col) shr 3];
  738. Dst2^ := Dst2^ or ((Src^ shr CurBit) and BitTable[BitCount])
  739. shl (StartBit[BitCount] - (Col * BitCount mod 8));
  740. Inc(Col, ColumnIncrement[Pass]);
  741. Dec(CurBit, BitCount);
  742. until CurBit < 0;
  743. Inc(Src);
  744. until Col >= Width;
  745. end;
  746. else
  747. begin
  748. Dst := @PByteArray(Data)[I * BytesPerLine + Col * BytesPerPixel];
  749. repeat
  750. CopyPixel(Src, Dst, BytesPerPixel);
  751. Inc(Dst, BytesPerPixel);
  752. Inc(Src, BytesPerPixel);
  753. Inc(Dst, ColumnIncrement[Pass] * BytesPerPixel - BytesPerPixel);
  754. Inc(Col, ColumnIncrement[Pass]);
  755. until Col >= Width;
  756. end;
  757. end;
  758. end;
  759. procedure FilterScanline(Filter: Byte; BytesPerPixel: LongInt; Line, PrevLine, Target: PByteArray;
  760. BytesPerLine: LongInt);
  761. var
  762. I: LongInt;
  763. begin
  764. case Filter of
  765. 0:
  766. begin
  767. // No filter
  768. Move(Line^, Target^, BytesPerLine);
  769. end;
  770. 1:
  771. begin
  772. // Sub filter
  773. Move(Line^, Target^, BytesPerPixel);
  774. for I := BytesPerPixel to BytesPerLine - 1 do
  775. Target[I] := (Line[I] + Target[I - BytesPerPixel]) and $FF;
  776. end;
  777. 2:
  778. begin
  779. // Up filter
  780. for I := 0 to BytesPerLine - 1 do
  781. Target[I] := (Line[I] + PrevLine[I]) and $FF;
  782. end;
  783. 3:
  784. begin
  785. // Average filter
  786. for I := 0 to BytesPerPixel - 1 do
  787. Target[I] := (Line[I] + PrevLine[I] shr 1) and $FF;
  788. for I := BytesPerPixel to BytesPerLine - 1 do
  789. Target[I] := (Line[I] + (Target[I - BytesPerPixel] + PrevLine[I]) shr 1) and $FF;
  790. end;
  791. 4:
  792. begin
  793. // Paeth filter
  794. for I := 0 to BytesPerPixel - 1 do
  795. Target[I] := (Line[I] + PaethPredictor(0, PrevLine[I], 0)) and $FF;
  796. for I := BytesPerPixel to BytesPerLine - 1 do
  797. Target[I] := (Line[I] + PaethPredictor(Target[I - BytesPerPixel], PrevLine[I], PrevLine[I - BytesPerPixel])) and $FF;
  798. end;
  799. end;
  800. end;
  801. procedure Convert124To8(DataIn: Pointer; DataOut: Pointer; Width, Height,
  802. WidthBytes: LongInt; Indexed: Boolean);
  803. var
  804. X, Y, Mul: LongInt;
  805. GetPixel: TGetPixelFunc;
  806. begin
  807. GetPixel := Get1BitPixel;
  808. Mul := 255;
  809. case IHDR.BitDepth of
  810. 2:
  811. begin
  812. Mul := 85;
  813. GetPixel := Get2BitPixel;
  814. end;
  815. 4:
  816. begin
  817. Mul := 17;
  818. GetPixel := Get4BitPixel;
  819. end;
  820. end;
  821. if Indexed then Mul := 1;
  822. for Y := 0 to Height - 1 do
  823. for X := 0 to Width - 1 do
  824. PByteArray(DataOut)[Y * Width + X] :=
  825. GetPixel(@PByteArray(DataIn)[Y * WidthBytes], X) * Mul;
  826. end;
  827. procedure TransformLOCOToRGB(Data: PByte; NumPixels, BytesPerPixel: LongInt);
  828. var
  829. I: LongInt;
  830. begin
  831. for I := 0 to NumPixels - 1 do
  832. begin
  833. if IHDR.BitDepth = 8 then
  834. begin
  835. PColor32Rec(Data).R := Byte(PColor32Rec(Data).R + PColor32Rec(Data).G);
  836. PColor32Rec(Data).B := Byte(PColor32Rec(Data).B + PColor32Rec(Data).G);
  837. end
  838. else
  839. begin
  840. PColor64Rec(Data).R := Word(PColor64Rec(Data).R + PColor64Rec(Data).G);
  841. PColor64Rec(Data).B := Word(PColor64Rec(Data).B + PColor64Rec(Data).G);
  842. end;
  843. Inc(Data, BytesPerPixel);
  844. end;
  845. end;
  846. begin
  847. Image.Width := FrameWidth;
  848. Image.Height := FrameHeight;
  849. Image.Format := ifUnknown;
  850. case IHDR.ColorType of
  851. 0:
  852. begin
  853. // Gray scale image
  854. case IHDR.BitDepth of
  855. 1, 2, 4, 8: Image.Format := ifGray8;
  856. 16: Image.Format := ifGray16;
  857. end;
  858. BitCount := IHDR.BitDepth;
  859. end;
  860. 2:
  861. begin
  862. // RGB image
  863. case IHDR.BitDepth of
  864. 8: Image.Format := ifR8G8B8;
  865. 16: Image.Format := ifR16G16B16;
  866. end;
  867. BitCount := IHDR.BitDepth * 3;
  868. end;
  869. 3:
  870. begin
  871. // Indexed image
  872. case IHDR.BitDepth of
  873. 1, 2, 4, 8: Image.Format := ifIndex8;
  874. end;
  875. BitCount := IHDR.BitDepth;
  876. end;
  877. 4:
  878. begin
  879. // Grayscale + alpha image
  880. case IHDR.BitDepth of
  881. 8: Image.Format := ifA8Gray8;
  882. 16: Image.Format := ifA16Gray16;
  883. end;
  884. BitCount := IHDR.BitDepth * 2;
  885. end;
  886. 6:
  887. begin
  888. // ARGB image
  889. case IHDR.BitDepth of
  890. 8: Image.Format := ifA8R8G8B8;
  891. 16: Image.Format := ifA16R16G16B16;
  892. end;
  893. BitCount := IHDR.BitDepth * 4;
  894. end;
  895. end;
  896. // Start decoding
  897. LineBuffer[True] := nil;
  898. LineBuffer[False] := nil;
  899. TotalBuffer := nil;
  900. ZeroLine := nil;
  901. BytesPerPixel := (BitCount + 7) div 8;
  902. ActLine := True;
  903. with Image do
  904. try
  905. BytesPerLine := (Width * BitCount + 7) div 8;
  906. SrcDataSize := Height * BytesPerLine;
  907. GetMem(Data, SrcDataSize);
  908. FillChar(Data^, SrcDataSize, 0);
  909. GetMem(ZeroLine, BytesPerLine);
  910. FillChar(ZeroLine^, BytesPerLine, 0);
  911. if IHDR.Interlacing = 1 then
  912. begin
  913. // Decode interlaced images
  914. TotalPos := 0;
  915. DecompressBuf(IDATStream.Memory, IDATStream.Size, 0,
  916. Pointer(TotalBuffer), TotalSize);
  917. GetMem(LineBuffer[True], BytesPerLine + 1);
  918. GetMem(LineBuffer[False], BytesPerLine + 1);
  919. for Pass := 0 to 6 do
  920. begin
  921. // Prepare next interlace run
  922. if Width <= ColumnStart[Pass] then
  923. Continue;
  924. InterlaceWidth := (Width + ColumnIncrement[Pass] - 1 -
  925. ColumnStart[Pass]) div ColumnIncrement[Pass];
  926. InterlaceLineBytes := (InterlaceWidth * BitCount + 7) shr 3;
  927. I := RowStart[Pass];
  928. FillChar(LineBuffer[True][0], BytesPerLine + 1, 0);
  929. FillChar(LineBuffer[False][0], BytesPerLine + 1, 0);
  930. while I < Height do
  931. begin
  932. // Copy line from decompressed data to working buffer
  933. Move(PByteArray(TotalBuffer)[TotalPos],
  934. LineBuffer[ActLine][0], InterlaceLineBytes + 1);
  935. Inc(TotalPos, InterlaceLineBytes + 1);
  936. // Swap red and blue channels if necessary
  937. if (IHDR.ColorType in [2, 6]) then
  938. SwapRGB(@LineBuffer[ActLine][1], InterlaceWidth, IHDR.BitDepth, BytesPerPixel);
  939. // Reverse-filter current scanline
  940. FilterScanline(LineBuffer[ActLine][0], BytesPerPixel,
  941. @LineBuffer[ActLine][1], @LineBuffer[not ActLine][1],
  942. @LineBuffer[ActLine][1], InterlaceLineBytes);
  943. // Decode Adam7 interlacing
  944. DecodeAdam7;
  945. ActLine := not ActLine;
  946. // Continue with next row in interlaced order
  947. Inc(I, RowIncrement[Pass]);
  948. end;
  949. end;
  950. end
  951. else
  952. begin
  953. // Decode non-interlaced images
  954. PrevLine := ZeroLine;
  955. DecompressBuf(IDATStream.Memory, IDATStream.Size, SrcDataSize + Height,
  956. Pointer(TotalBuffer), TotalSize);
  957. for I := 0 to Height - 1 do
  958. begin
  959. // Swap red and blue channels if necessary
  960. if IHDR.ColorType in [2, 6] then
  961. SwapRGB(@PByteArray(TotalBuffer)[I * (BytesPerLine + 1) + 1], Width,
  962. IHDR.BitDepth, BytesPerPixel);
  963. // reverse-filter current scanline
  964. FilterScanline(PByteArray(TotalBuffer)[I * (BytesPerLine + 1)],
  965. BytesPerPixel, @PByteArray(TotalBuffer)[I * (BytesPerLine + 1) + 1],
  966. PrevLine, @PByteArray(Data)[I * BytesPerLine], BytesPerLine);
  967. PrevLine := @PByteArray(Data)[I * BytesPerLine];
  968. end;
  969. end;
  970. Size := Width * Height * BytesPerPixel;
  971. if Size <> SrcDataSize then
  972. begin
  973. // If source data size is different from size of image in assigned
  974. // format we must convert it (it is in 1/2/4 bit count)
  975. GetMem(Bits, Size);
  976. case IHDR.ColorType of
  977. 0: Convert124To8(Data, Bits, Width, Height, BytesPerLine, False);
  978. 3: Convert124To8(Data, Bits, Width, Height, BytesPerLine, True);
  979. end;
  980. FreeMem(Data);
  981. end
  982. else
  983. begin
  984. // If source data size is the same as size of
  985. // image Bits in assigned format we simply copy pointer reference
  986. Bits := Data;
  987. end;
  988. // LOCO transformation was used too (only for color types 2 and 6)
  989. if (IHDR.Filter = 64) and (IHDR.ColorType in [2, 6]) then
  990. TransformLOCOToRGB(Bits, Width * Height, BytesPerPixel);
  991. // Images with 16 bit channels must be swapped because of PNG's big endianity
  992. if IHDR.BitDepth = 16 then
  993. SwapEndianWord(Bits, Width * Height * BytesPerPixel div SizeOf(Word));
  994. finally
  995. FreeMem(LineBuffer[True]);
  996. FreeMem(LineBuffer[False]);
  997. FreeMem(TotalBuffer);
  998. FreeMem(ZeroLine);
  999. end;
  1000. end;
  1001. {$IFNDEF DONT_LINK_JNG}
  1002. procedure TNGFileLoader.LoadImageFromJNGFrame(FrameWidth, FrameHeight: LongInt; const JHDR: TJHDR; IDATStream,
  1003. JDATStream, JDAAStream: TMemoryStream; var Image: TImageData);
  1004. var
  1005. AlphaImage: TImageData;
  1006. FakeIHDR: TIHDR;
  1007. FmtInfo: TImageFormatInfo;
  1008. I: LongInt;
  1009. AlphaPtr: PByte;
  1010. GrayPtr: PWordRec;
  1011. ColorPtr: PColor32Rec;
  1012. procedure LoadJpegFromStream(Stream: TStream; var DestImage: TImageData);
  1013. var
  1014. JpegFormat: TCustomIOJpegFileFormat;
  1015. Handle: TImagingHandle;
  1016. DynImages: TDynImageDataArray;
  1017. begin
  1018. if JHDR.SampleDepth <> 12 then
  1019. begin
  1020. JpegFormat := TCustomIOJpegFileFormat.Create;
  1021. JpegFormat.SetCustomIO(StreamIO);
  1022. Stream.Position := 0;
  1023. Handle := StreamIO.OpenRead(Pointer(Stream));
  1024. try
  1025. JpegFormat.LoadData(Handle, DynImages, True);
  1026. DestImage := DynImages[0];
  1027. finally
  1028. StreamIO.Close(Handle);
  1029. JpegFormat.Free;
  1030. SetLength(DynImages, 0);
  1031. end;
  1032. end
  1033. else
  1034. NewImage(FrameWidth, FrameHeight, ifR8G8B8, DestImage);
  1035. end;
  1036. begin
  1037. LoadJpegFromStream(JDATStream, Image);
  1038. // If present separate alpha channel is processed
  1039. if (JHDR.ColorType in [12, 14]) and (Image.Format in [ifGray8, ifR8G8B8]) then
  1040. begin
  1041. InitImage(AlphaImage);
  1042. if JHDR.AlphaCompression = 0 then
  1043. begin
  1044. // Alpha channel is PNG compressed
  1045. FakeIHDR.Width := JHDR.Width;
  1046. FakeIHDR.Height := JHDR.Height;
  1047. FakeIHDR.ColorType := 0;
  1048. FakeIHDR.BitDepth := JHDR.AlphaSampleDepth;
  1049. FakeIHDR.Filter := JHDR.AlphaFilter;
  1050. FakeIHDR.Interlacing := JHDR.AlphaInterlacing;
  1051. LoadImageFromPNGFrame(FrameWidth, FrameHeight, FakeIHDR, IDATStream, AlphaImage);
  1052. end
  1053. else
  1054. begin
  1055. // Alpha channel is JPEG compressed
  1056. LoadJpegFromStream(JDAAStream, AlphaImage);
  1057. end;
  1058. // Check if alpha channel is the same size as image
  1059. if (Image.Width <> AlphaImage.Width) and (Image.Height <> AlphaImage.Height) then
  1060. ResizeImage(AlphaImage, Image.Width, Image.Height, rfNearest);
  1061. // Check alpha channels data format
  1062. GetImageFormatInfo(AlphaImage.Format, FmtInfo);
  1063. if (FmtInfo.BytesPerPixel > 1) or (not FmtInfo.HasGrayChannel) then
  1064. ConvertImage(AlphaImage, ifGray8);
  1065. // Convert image to fromat with alpha channel
  1066. if Image.Format = ifGray8 then
  1067. ConvertImage(Image, ifA8Gray8)
  1068. else
  1069. ConvertImage(Image, ifA8R8G8B8);
  1070. // Combine alpha channel with image
  1071. AlphaPtr := AlphaImage.Bits;
  1072. if Image.Format = ifA8Gray8 then
  1073. begin
  1074. GrayPtr := Image.Bits;
  1075. for I := 0 to Image.Width * Image.Height - 1 do
  1076. begin
  1077. GrayPtr.High := AlphaPtr^;
  1078. Inc(GrayPtr);
  1079. Inc(AlphaPtr);
  1080. end;
  1081. end
  1082. else
  1083. begin
  1084. ColorPtr := Image.Bits;
  1085. for I := 0 to Image.Width * Image.Height - 1 do
  1086. begin
  1087. ColorPtr.A := AlphaPtr^;
  1088. Inc(ColorPtr);
  1089. Inc(AlphaPtr);
  1090. end;
  1091. end;
  1092. FreeImage(AlphaImage);
  1093. end;
  1094. end;
  1095. {$ENDIF}
  1096. procedure TNGFileLoader.ApplyFrameSettings(Frame: TFrameInfo; var Image: TImageData);
  1097. var
  1098. FmtInfo: TImageFormatInfo;
  1099. BackGroundColor: TColor64Rec;
  1100. ColorKey: TColor64Rec;
  1101. Alphas: PByteArray;
  1102. AlphasSize: LongInt;
  1103. IsColorKeyPresent: Boolean;
  1104. IsBackGroundPresent: Boolean;
  1105. IsColorFormat: Boolean;
  1106. procedure ConverttRNS;
  1107. begin
  1108. if FmtInfo.IsIndexed then
  1109. begin
  1110. if Alphas = nil then
  1111. begin
  1112. GetMem(Alphas, Frame.TransparencySize);
  1113. Move(Frame.Transparency^, Alphas^, Frame.TransparencySize);
  1114. AlphasSize := Frame.TransparencySize;
  1115. end;
  1116. end
  1117. else if not FmtInfo.HasAlphaChannel then
  1118. begin
  1119. FillChar(ColorKey, SizeOf(ColorKey), 0);
  1120. Move(Frame.Transparency^, ColorKey, Min(Frame.TransparencySize, SizeOf(ColorKey)));
  1121. if IsColorFormat then
  1122. SwapValues(ColorKey.R, ColorKey.B);
  1123. SwapEndianWord(@ColorKey, 3);
  1124. // 1/2/4 bit images were converted to 8 bit so we must convert color key too
  1125. if (not Frame.IsJpegFrame) and (Frame.IHDR.ColorType in [0, 4]) then
  1126. case Frame.IHDR.BitDepth of
  1127. 1: ColorKey.B := Word(ColorKey.B * 255);
  1128. 2: ColorKey.B := Word(ColorKey.B * 85);
  1129. 4: ColorKey.B := Word(ColorKey.B * 17);
  1130. end;
  1131. IsColorKeyPresent := True;
  1132. end;
  1133. end;
  1134. procedure ConvertbKGD;
  1135. begin
  1136. FillChar(BackGroundColor, SizeOf(BackGroundColor), 0);
  1137. Move(Frame.Background^, BackGroundColor, Min(Frame.BackgroundSize,
  1138. SizeOf(BackGroundColor)));
  1139. if IsColorFormat then
  1140. SwapValues(BackGroundColor.R, BackGroundColor.B);
  1141. SwapEndianWord(@BackGroundColor, 3);
  1142. // 1/2/4 bit images were converted to 8 bit so we must convert back color too
  1143. if (not Frame.IsJpegFrame) and (Frame.IHDR.ColorType in [0, 4]) then
  1144. case Frame.IHDR.BitDepth of
  1145. 1: BackGroundColor.B := Word(BackGroundColor.B * 255);
  1146. 2: BackGroundColor.B := Word(BackGroundColor.B * 85);
  1147. 4: BackGroundColor.B := Word(BackGroundColor.B * 17);
  1148. end;
  1149. IsBackGroundPresent := True;
  1150. end;
  1151. procedure ReconstructPalette;
  1152. var
  1153. I: LongInt;
  1154. begin
  1155. with Image do
  1156. begin
  1157. GetMem(Palette, FmtInfo.PaletteEntries * SizeOf(TColor32Rec));
  1158. FillChar(Palette^, FmtInfo.PaletteEntries * SizeOf(TColor32Rec), $FF);
  1159. // if RGB palette was loaded from file then use it
  1160. if Frame.Palette <> nil then
  1161. for I := 0 to Min(Frame.PaletteEntries, FmtInfo.PaletteEntries) - 1 do
  1162. with Palette[I] do
  1163. begin
  1164. R := Frame.Palette[I].B;
  1165. G := Frame.Palette[I].G;
  1166. B := Frame.Palette[I].R;
  1167. end;
  1168. // if palette alphas were loaded from file then use them
  1169. if Alphas <> nil then
  1170. for I := 0 to Min(AlphasSize, FmtInfo.PaletteEntries) - 1 do
  1171. Palette[I].A := Alphas[I];
  1172. end;
  1173. end;
  1174. procedure ApplyColorKey;
  1175. var
  1176. DestFmt: TImageFormat;
  1177. OldPixel, NewPixel: Pointer;
  1178. begin
  1179. case Image.Format of
  1180. ifGray8: DestFmt := ifA8Gray8;
  1181. ifGray16: DestFmt := ifA16Gray16;
  1182. ifR8G8B8: DestFmt := ifA8R8G8B8;
  1183. ifR16G16B16: DestFmt := ifA16R16G16B16;
  1184. else
  1185. DestFmt := ifUnknown;
  1186. end;
  1187. if DestFmt <> ifUnknown then
  1188. begin
  1189. if not IsBackGroundPresent then
  1190. BackGroundColor := ColorKey;
  1191. ConvertImage(Image, DestFmt);
  1192. OldPixel := @ColorKey;
  1193. NewPixel := @BackGroundColor;
  1194. // Now back color and color key must be converted to image's data format, looks ugly
  1195. case Image.Format of
  1196. ifA8Gray8:
  1197. begin
  1198. TColor32Rec(TInt64Rec(ColorKey).Low).B := Byte(ColorKey.B);
  1199. TColor32Rec(TInt64Rec(ColorKey).Low).G := $FF;
  1200. TColor32Rec(TInt64Rec(BackGroundColor).Low).B := Byte(BackGroundColor.B);
  1201. end;
  1202. ifA16Gray16:
  1203. begin
  1204. ColorKey.G := $FFFF;
  1205. end;
  1206. ifA8R8G8B8:
  1207. begin
  1208. TColor32Rec(TInt64Rec(ColorKey).Low).R := Byte(ColorKey.R);
  1209. TColor32Rec(TInt64Rec(ColorKey).Low).G := Byte(ColorKey.G);
  1210. TColor32Rec(TInt64Rec(ColorKey).Low).B := Byte(ColorKey.B);
  1211. TColor32Rec(TInt64Rec(ColorKey).Low).A := $FF;
  1212. TColor32Rec(TInt64Rec(BackGroundColor).Low).R := Byte(BackGroundColor.R);
  1213. TColor32Rec(TInt64Rec(BackGroundColor).Low).G := Byte(BackGroundColor.G);
  1214. TColor32Rec(TInt64Rec(BackGroundColor).Low).B := Byte(BackGroundColor.B);
  1215. end;
  1216. ifA16R16G16B16:
  1217. begin
  1218. ColorKey.A := $FFFF;
  1219. end;
  1220. end;
  1221. ReplaceColor(Image, 0, 0, Image.Width, Image.Height, OldPixel, NewPixel);
  1222. end;
  1223. end;
  1224. begin
  1225. Alphas := nil;
  1226. IsColorKeyPresent := False;
  1227. IsBackGroundPresent := False;
  1228. GetImageFormatInfo(Image.Format, FmtInfo);
  1229. IsColorFormat := (Frame.IsJpegFrame and (Frame.JHDR.ColorType in [10, 14])) or
  1230. (not Frame.IsJpegFrame and (Frame.IHDR.ColorType in [2, 6]));
  1231. // Convert some chunk data to useful format
  1232. if Frame.Transparency <> nil then
  1233. ConverttRNS;
  1234. if Frame.Background <> nil then
  1235. ConvertbKGD;
  1236. // Build palette for indexed images
  1237. if FmtInfo.IsIndexed then
  1238. ReconstructPalette;
  1239. // Apply color keying
  1240. if IsColorKeyPresent and not FmtInfo.HasAlphaChannel then
  1241. ApplyColorKey;
  1242. FreeMemNil(Alphas);
  1243. end;
  1244. { TNGFileSaver class implementation }
  1245. procedure TNGFileSaver.StoreImageToPNGFrame(const IHDR: TIHDR; Bits: Pointer;
  1246. FmtInfo: TImageFormatInfo; IDATStream: TMemoryStream);
  1247. var
  1248. TotalBuffer, CompBuffer, ZeroLine, PrevLine: Pointer;
  1249. FilterLines: array[0..4] of PByteArray;
  1250. TotalSize, CompSize, I, BytesPerLine, BytesPerPixel: LongInt;
  1251. Filter: Byte;
  1252. Adaptive: Boolean;
  1253. procedure FilterScanline(Filter: Byte; BytesPerPixel: LongInt; Line, PrevLine, Target: PByteArray);
  1254. var
  1255. I: LongInt;
  1256. begin
  1257. case Filter of
  1258. 0:
  1259. begin
  1260. // No filter
  1261. Move(Line^, Target^, BytesPerLine);
  1262. end;
  1263. 1:
  1264. begin
  1265. // Sub filter
  1266. Move(Line^, Target^, BytesPerPixel);
  1267. for I := BytesPerPixel to BytesPerLine - 1 do
  1268. Target[I] := (Line[I] - Line[I - BytesPerPixel]) and $FF;
  1269. end;
  1270. 2:
  1271. begin
  1272. // Up filter
  1273. for I := 0 to BytesPerLine - 1 do
  1274. Target[I] := (Line[I] - PrevLine[I]) and $FF;
  1275. end;
  1276. 3:
  1277. begin
  1278. // Average filter
  1279. for I := 0 to BytesPerPixel - 1 do
  1280. Target[I] := (Line[I] - PrevLine[I] shr 1) and $FF;
  1281. for I := BytesPerPixel to BytesPerLine - 1 do
  1282. Target[I] := (Line[I] - (Line[I - BytesPerPixel] + PrevLine[I]) shr 1) and $FF;
  1283. end;
  1284. 4:
  1285. begin
  1286. // Paeth filter
  1287. for I := 0 to BytesPerPixel - 1 do
  1288. Target[I] := (Line[I] - PaethPredictor(0, PrevLine[I], 0)) and $FF;
  1289. for I := BytesPerPixel to BytesPerLine - 1 do
  1290. Target[I] := (Line[I] - PaethPredictor(Line[I - BytesPerPixel], PrevLine[I], PrevLine[I - BytesPerPixel])) and $FF;
  1291. end;
  1292. end;
  1293. end;
  1294. procedure AdaptiveFilter(var Filter: Byte; BytesPerPixel: LongInt; Line, PrevLine, Target: PByteArray);
  1295. var
  1296. I, J, BestTest: LongInt;
  1297. Sums: array[0..4] of LongInt;
  1298. begin
  1299. // Compute the output scanline using all five filters,
  1300. // and select the filter that gives the smallest sum of
  1301. // absolute values of outputs
  1302. FillChar(Sums, SizeOf(Sums), 0);
  1303. BestTest := MaxInt;
  1304. for I := 0 to 4 do
  1305. begin
  1306. FilterScanline(I, BytesPerPixel, Line, PrevLine, FilterLines[I]);
  1307. for J := 0 to BytesPerLine - 1 do
  1308. Sums[I] := Sums[I] + Abs(ShortInt(FilterLines[I][J]));
  1309. if Sums[I] < BestTest then
  1310. begin
  1311. Filter := I;
  1312. BestTest := Sums[I];
  1313. end;
  1314. end;
  1315. Move(FilterLines[Filter]^, Target^, BytesPerLine);
  1316. end;
  1317. begin
  1318. // Select precompression filter and compression level
  1319. Adaptive := False;
  1320. Filter := 0;
  1321. case PreFilter of
  1322. 6:
  1323. if not ((IHDR.BitDepth < 8) or (IHDR.ColorType = 3))
  1324. then Adaptive := True;
  1325. 0..4: Filter := PreFilter;
  1326. else
  1327. if IHDR.ColorType in [2, 6] then
  1328. Filter := 4
  1329. end;
  1330. // Prepare data for compression
  1331. CompBuffer := nil;
  1332. FillChar(FilterLines, SizeOf(FilterLines), 0);
  1333. BytesPerPixel := FmtInfo.BytesPerPixel;
  1334. BytesPerLine := LongInt(IHDR.Width) * BytesPerPixel;
  1335. TotalSize := (BytesPerLine + 1) * LongInt(IHDR.Height);
  1336. GetMem(TotalBuffer, TotalSize);
  1337. GetMem(ZeroLine, BytesPerLine);
  1338. FillChar(ZeroLine^, BytesPerLine, 0);
  1339. if Adaptive then
  1340. for I := 0 to 4 do
  1341. GetMem(FilterLines[I], BytesPerLine);
  1342. PrevLine := ZeroLine;
  1343. try
  1344. // Process next scanlines
  1345. for I := 0 to IHDR.Height - 1 do
  1346. begin
  1347. // Filter scanline
  1348. if Adaptive then
  1349. AdaptiveFilter(Filter, BytesPerPixel, @PByteArray(Bits)[I * BytesPerLine],
  1350. PrevLine, @PByteArray(TotalBuffer)[I * (BytesPerLine + 1) + 1])
  1351. else
  1352. FilterScanline(Filter, BytesPerPixel, @PByteArray(Bits)[I * BytesPerLine],
  1353. PrevLine, @PByteArray(TotalBuffer)[I * (BytesPerLine + 1) + 1]);
  1354. PrevLine := @PByteArray(Bits)[I * BytesPerLine];
  1355. // Swap red and blue if necessary
  1356. if (IHDR.ColorType in [2, 6]) and not FmtInfo.IsRBSwapped then
  1357. SwapRGB(@PByteArray(TotalBuffer)[I * (BytesPerLine + 1) + 1],
  1358. IHDR.Width, IHDR.BitDepth, FmtInfo.BytesPerPixel);
  1359. // Images with 16 bit channels must be swapped because of PNG's big endianess
  1360. if IHDR.BitDepth = 16 then
  1361. SwapEndianWord(@PByteArray(TotalBuffer)[I * (BytesPerLine + 1) + 1],
  1362. BytesPerLine div SizeOf(Word));
  1363. // Set filter used for this scanline
  1364. PByteArray(TotalBuffer)[I * (BytesPerLine + 1)] := Filter;
  1365. end;
  1366. // Compress IDAT data
  1367. CompressBuf(TotalBuffer, TotalSize, CompBuffer, CompSize, CompressLevel);
  1368. // Write IDAT data to stream
  1369. IDATStream.WriteBuffer(CompBuffer^, CompSize);
  1370. finally
  1371. FreeMem(TotalBuffer);
  1372. FreeMem(CompBuffer);
  1373. FreeMem(ZeroLine);
  1374. if Adaptive then
  1375. for I := 0 to 4 do
  1376. FreeMem(FilterLines[I]);
  1377. end;
  1378. end;
  1379. {$IFNDEF DONT_LINK_JNG}
  1380. procedure TNGFileSaver.StoreImageToJNGFrame(const JHDR: TJHDR;
  1381. const Image: TImageData; IDATStream, JDATStream,
  1382. JDAAStream: TMemoryStream);
  1383. var
  1384. ColorImage, AlphaImage: TImageData;
  1385. FmtInfo: TImageFormatInfo;
  1386. AlphaPtr: PByte;
  1387. GrayPtr: PWordRec;
  1388. ColorPtr: PColor32Rec;
  1389. I: LongInt;
  1390. FakeIHDR: TIHDR;
  1391. procedure SaveJpegToStream(Stream: TStream; const Image: TImageData);
  1392. var
  1393. JpegFormat: TCustomIOJpegFileFormat;
  1394. Handle: TImagingHandle;
  1395. DynImages: TDynImageDataArray;
  1396. begin
  1397. JpegFormat := TCustomIOJpegFileFormat.Create;
  1398. JpegFormat.SetCustomIO(StreamIO);
  1399. // Only JDAT stream can be saved progressive
  1400. if Stream = JDATStream then
  1401. JpegFormat.FProgressive := Progressive
  1402. else
  1403. JpegFormat.FProgressive := False;
  1404. JpegFormat.FQuality := Quality;
  1405. SetLength(DynImages, 1);
  1406. DynImages[0] := Image;
  1407. Handle := StreamIO.OpenWrite(Pointer(Stream));
  1408. try
  1409. JpegFormat.SaveData(Handle, DynImages, 0);
  1410. finally
  1411. StreamIO.Close(Handle);
  1412. SetLength(DynImages, 0);
  1413. JpegFormat.Free;
  1414. end;
  1415. end;
  1416. begin
  1417. GetImageFormatInfo(Image.Format, FmtInfo);
  1418. InitImage(ColorImage);
  1419. InitImage(AlphaImage);
  1420. if FmtInfo.HasAlphaChannel then
  1421. begin
  1422. // Create new image for alpha channel and color image without alpha
  1423. CloneImage(Image, ColorImage);
  1424. NewImage(Image.Width, Image.Height, ifGray8, AlphaImage);
  1425. case Image.Format of
  1426. ifA8Gray8: ConvertImage(ColorImage, ifGray8);
  1427. ifA8R8G8B8: ConvertImage(ColorImage, ifR8G8B8);
  1428. end;
  1429. // Store source image's alpha to separate image
  1430. AlphaPtr := AlphaImage.Bits;
  1431. if Image.Format = ifA8Gray8 then
  1432. begin
  1433. GrayPtr := Image.Bits;
  1434. for I := 0 to Image.Width * Image.Height - 1 do
  1435. begin
  1436. AlphaPtr^ := GrayPtr.High;
  1437. Inc(GrayPtr);
  1438. Inc(AlphaPtr);
  1439. end;
  1440. end
  1441. else
  1442. begin
  1443. ColorPtr := Image.Bits;
  1444. for I := 0 to Image.Width * Image.Height - 1 do
  1445. begin
  1446. AlphaPtr^ := ColorPtr.A;
  1447. Inc(ColorPtr);
  1448. Inc(AlphaPtr);
  1449. end;
  1450. end;
  1451. // Write color image to stream as JPEG
  1452. SaveJpegToStream(JDATStream, ColorImage);
  1453. if LossyAlpha then
  1454. begin
  1455. // Write alpha image to stream as JPEG
  1456. SaveJpegToStream(JDAAStream, AlphaImage);
  1457. end
  1458. else
  1459. begin
  1460. // Alpha channel is PNG compressed
  1461. FakeIHDR.Width := JHDR.Width;
  1462. FakeIHDR.Height := JHDR.Height;
  1463. FakeIHDR.ColorType := 0;
  1464. FakeIHDR.BitDepth := JHDR.AlphaSampleDepth;
  1465. FakeIHDR.Filter := JHDR.AlphaFilter;
  1466. FakeIHDR.Interlacing := JHDR.AlphaInterlacing;
  1467. GetImageFormatInfo(AlphaImage.Format, FmtInfo);
  1468. StoreImageToPNGFrame(FakeIHDR, AlphaImage.Bits, FmtInfo, IDATStream);
  1469. end;
  1470. FreeImage(ColorImage);
  1471. FreeImage(AlphaImage);
  1472. end
  1473. else
  1474. begin
  1475. // Simply write JPEG to stream
  1476. SaveJpegToStream(JDATStream, Image);
  1477. end;
  1478. end;
  1479. {$ENDIF}
  1480. procedure TNGFileSaver.AddFrame(const Image: TImageData; IsJpegFrame: Boolean);
  1481. var
  1482. Frame: TFrameInfo;
  1483. FmtInfo: TImageFormatInfo;
  1484. procedure StorePalette;
  1485. var
  1486. Pal: PPalette24;
  1487. Alphas: PByteArray;
  1488. I, PalBytes: LongInt;
  1489. AlphasDiffer: Boolean;
  1490. begin
  1491. // Fill and save RGB part of palette to PLTE chunk
  1492. PalBytes := FmtInfo.PaletteEntries * SizeOf(TColor24Rec);
  1493. GetMem(Pal, PalBytes);
  1494. AlphasDiffer := False;
  1495. for I := 0 to FmtInfo.PaletteEntries - 1 do
  1496. begin
  1497. Pal[I].B := Image.Palette[I].R;
  1498. Pal[I].G := Image.Palette[I].G;
  1499. Pal[I].R := Image.Palette[I].B;
  1500. if Image.Palette[I].A < 255 then
  1501. AlphasDiffer := True;
  1502. end;
  1503. Frame.Palette := Pal;
  1504. Frame.PaletteEntries := FmtInfo.PaletteEntries;
  1505. // Fill and save alpha part (if there are any alphas < 255) of palette to tRNS chunk
  1506. if AlphasDiffer then
  1507. begin
  1508. PalBytes := FmtInfo.PaletteEntries * SizeOf(Byte);
  1509. GetMem(Alphas, PalBytes);
  1510. for I := 0 to FmtInfo.PaletteEntries - 1 do
  1511. Alphas[I] := Image.Palette[I].A;
  1512. Frame.Transparency := Alphas;
  1513. Frame.TransparencySize := PalBytes;
  1514. end;
  1515. end;
  1516. begin
  1517. // Add new frame
  1518. Frame := AddFrameInfo;
  1519. Frame.IsJpegFrame := IsJpegFrame;
  1520. with Frame do
  1521. begin
  1522. GetImageFormatInfo(Image.Format, FmtInfo);
  1523. if IsJpegFrame then
  1524. begin
  1525. {$IFNDEF DONT_LINK_JNG}
  1526. // Fill JNG header
  1527. JHDR.Width := Image.Width;
  1528. JHDR.Height := Image.Height;
  1529. case Image.Format of
  1530. ifGray8: JHDR.ColorType := 8;
  1531. ifR8G8B8: JHDR.ColorType := 10;
  1532. ifA8Gray8: JHDR.ColorType := 12;
  1533. ifA8R8G8B8: JHDR.ColorType := 14;
  1534. end;
  1535. JHDR.SampleDepth := 8; // 8-bit samples and quantization tables
  1536. JHDR.Compression := 8; // Huffman coding
  1537. JHDR.Interlacing := Iff(Progressive, 8, 0);
  1538. JHDR.AlphaSampleDepth := Iff(FmtInfo.HasAlphaChannel, 8, 0);
  1539. JHDR.AlphaCompression := Iff(LossyAlpha, 8, 0);
  1540. JHDR.AlphaFilter := 0;
  1541. JHDR.AlphaInterlacing := 0;
  1542. StoreImageToJNGFrame(JHDR, Image, IDATMemory, JDATMemory, JDAAMemory);
  1543. // Finally swap endian
  1544. SwapEndianLongWord(@JHDR, 2);
  1545. {$ENDIF}
  1546. end
  1547. else
  1548. begin
  1549. // Fill PNG header
  1550. IHDR.Width := Image.Width;
  1551. IHDR.Height := Image.Height;
  1552. IHDR.Compression := 0;
  1553. IHDR.Filter := 0;
  1554. IHDR.Interlacing := 0;
  1555. IHDR.BitDepth := FmtInfo.BytesPerPixel * 8;
  1556. // Select appropiate PNG color type and modify bitdepth
  1557. if FmtInfo.HasGrayChannel then
  1558. begin
  1559. IHDR.ColorType := 0;
  1560. if FmtInfo.HasAlphaChannel then
  1561. begin
  1562. IHDR.ColorType := 4;
  1563. IHDR.BitDepth := IHDR.BitDepth div 2;
  1564. end;
  1565. end
  1566. else
  1567. begin
  1568. if FmtInfo.IsIndexed then
  1569. IHDR.ColorType := 3
  1570. else
  1571. if FmtInfo.HasAlphaChannel then
  1572. begin
  1573. IHDR.ColorType := 6;
  1574. IHDR.BitDepth := IHDR.BitDepth div 4;
  1575. end
  1576. else
  1577. begin
  1578. IHDR.ColorType := 2;
  1579. IHDR.BitDepth := IHDR.BitDepth div 3;
  1580. end;
  1581. end;
  1582. if FileType = ngAPNG then
  1583. begin
  1584. // Fill fcTL chunk of APNG file
  1585. fcTL.SeqNumber := 0; // Decided when writing to file
  1586. fcTL.Width := IHDR.Width;
  1587. fcTL.Height := IHDR.Height;
  1588. fcTL.XOffset := 0;
  1589. fcTL.YOffset := 0;
  1590. fcTL.DelayNumer := 1;
  1591. fcTL.DelayDenom := 3;
  1592. fcTL.DisposeOp := DisposeOpNone;
  1593. fcTL.BlendOp := BlendOpSource;
  1594. SwapEndianLongWord(@fcTL, 5);
  1595. fcTL.DelayNumer := SwapEndianWord(fcTL.DelayNumer);
  1596. fcTL.DelayDenom := SwapEndianWord(fcTL.DelayDenom);
  1597. end;
  1598. // Compress PNG image and store it to stream
  1599. StoreImageToPNGFrame(IHDR, Image.Bits, FmtInfo, IDATMemory);
  1600. // Store palette if necesary
  1601. if FmtInfo.IsIndexed then
  1602. StorePalette;
  1603. // Finally swap endian
  1604. SwapEndianLongWord(@IHDR, 2);
  1605. end;
  1606. end;
  1607. end;
  1608. function TNGFileSaver.SaveFile(Handle: TImagingHandle): Boolean;
  1609. var
  1610. I: LongInt;
  1611. Chunk: TChunkHeader;
  1612. SeqNo: LongWord;
  1613. function GetNextSeqNo: LongWord;
  1614. begin
  1615. // Seq numbers of fcTL and fdAT are "interleaved" as they share the counter.
  1616. // Example: first fcTL for IDAT has seq=0, next is fcTL for seond frame with
  1617. // seq=1, then first fdAT with seq=2, fcTL seq=3, fdAT=4, ...
  1618. Result := SwapEndianLongWord(SeqNo);
  1619. Inc(SeqNo);
  1620. end;
  1621. function CalcChunkCrc(const ChunkHdr: TChunkHeader; Data: Pointer;
  1622. Size: LongInt): LongWord;
  1623. begin
  1624. Result := $FFFFFFFF;
  1625. CalcCrc32(Result, @ChunkHdr.ChunkID, SizeOf(ChunkHdr.ChunkID));
  1626. CalcCrc32(Result, Data, Size);
  1627. Result := SwapEndianLongWord(Result xor $FFFFFFFF);
  1628. end;
  1629. procedure WriteChunk(var Chunk: TChunkHeader; ChunkData: Pointer);
  1630. var
  1631. ChunkCrc: LongWord;
  1632. SizeToWrite: LongInt;
  1633. begin
  1634. SizeToWrite := Chunk.DataSize;
  1635. Chunk.DataSize := SwapEndianLongWord(Chunk.DataSize);
  1636. ChunkCrc := CalcChunkCrc(Chunk, ChunkData, SizeToWrite);
  1637. GetIO.Write(Handle, @Chunk, SizeOf(Chunk));
  1638. if SizeToWrite <> 0 then
  1639. GetIO.Write(Handle, ChunkData, SizeToWrite);
  1640. GetIO.Write(Handle, @ChunkCrc, SizeOf(ChunkCrc));
  1641. end;
  1642. procedure WritefdAT(Frame: TFrameInfo);
  1643. var
  1644. ChunkCrc: LongWord;
  1645. ChunkSeqNo: LongWord;
  1646. begin
  1647. Chunk.ChunkID := fdATChunk;
  1648. ChunkSeqNo := GetNextSeqNo;
  1649. // fdAT saves seq number LongWord before compressed pixels
  1650. Chunk.DataSize := Frame.IDATMemory.Size + SizeOf(LongWord);
  1651. Chunk.DataSize := SwapEndianLongWord(Chunk.DataSize);
  1652. // Calc CRC
  1653. ChunkCrc := $FFFFFFFF;
  1654. CalcCrc32(ChunkCrc, @Chunk.ChunkID, SizeOf(Chunk.ChunkID));
  1655. CalcCrc32(ChunkCrc, @ChunkSeqNo, SizeOf(ChunkSeqNo));
  1656. CalcCrc32(ChunkCrc, Frame.IDATMemory.Memory, Frame.IDATMemory.Size);
  1657. ChunkCrc := SwapEndianLongWord(ChunkCrc xor $FFFFFFFF);
  1658. // Write out all fdAT data
  1659. GetIO.Write(Handle, @Chunk, SizeOf(Chunk));
  1660. GetIO.Write(Handle, @ChunkSeqNo, SizeOf(ChunkSeqNo));
  1661. GetIO.Write(Handle, Frame.IDATMemory.Memory, Frame.IDATMemory.Size);
  1662. GetIO.Write(Handle, @ChunkCrc, SizeOf(ChunkCrc));
  1663. end;
  1664. procedure WritePNGMainImageChunks(Frame: TFrameInfo);
  1665. begin
  1666. with Frame do
  1667. begin
  1668. // Write IHDR chunk
  1669. Chunk.DataSize := SizeOf(IHDR);
  1670. Chunk.ChunkID := IHDRChunk;
  1671. WriteChunk(Chunk, @IHDR);
  1672. // Write PLTE chunk if data is present
  1673. if Palette <> nil then
  1674. begin
  1675. Chunk.DataSize := PaletteEntries * SizeOf(TColor24Rec);
  1676. Chunk.ChunkID := PLTEChunk;
  1677. WriteChunk(Chunk, Palette);
  1678. end;
  1679. // Write tRNS chunk if data is present
  1680. if Transparency <> nil then
  1681. begin
  1682. Chunk.DataSize := TransparencySize;
  1683. Chunk.ChunkID := tRNSChunk;
  1684. WriteChunk(Chunk, Transparency);
  1685. end;
  1686. end;
  1687. end;
  1688. begin
  1689. Result := False;
  1690. SeqNo := 0;
  1691. case FileType of
  1692. ngPNG, ngAPNG: GetIO.Write(Handle, @PNGSignature, SizeOf(TChar8));
  1693. ngMNG: GetIO.Write(Handle, @MNGSignature, SizeOf(TChar8));
  1694. ngJNG: GetIO.Write(Handle, @JNGSignature, SizeOf(TChar8));
  1695. end;
  1696. if FileType = ngMNG then
  1697. begin
  1698. SwapEndianLongWord(@MHDR, SizeOf(MHDR) div SizeOf(LongWord));
  1699. Chunk.DataSize := SizeOf(MHDR);
  1700. Chunk.ChunkID := MHDRChunk;
  1701. WriteChunk(Chunk, @MHDR);
  1702. end;
  1703. for I := 0 to Length(Frames) - 1 do
  1704. with Frames[I] do
  1705. begin
  1706. if IsJpegFrame then
  1707. begin
  1708. // Write JHDR chunk
  1709. Chunk.DataSize := SizeOf(JHDR);
  1710. Chunk.ChunkID := JHDRChunk;
  1711. WriteChunk(Chunk, @JHDR);
  1712. // Write JNG image data
  1713. Chunk.DataSize := JDATMemory.Size;
  1714. Chunk.ChunkID := JDATChunk;
  1715. WriteChunk(Chunk, JDATMemory.Memory);
  1716. // Write alpha channel if present
  1717. if JHDR.AlphaSampleDepth > 0 then
  1718. begin
  1719. if JHDR.AlphaCompression = 0 then
  1720. begin
  1721. // Alpha is PNG compressed
  1722. Chunk.DataSize := IDATMemory.Size;
  1723. Chunk.ChunkID := IDATChunk;
  1724. WriteChunk(Chunk, IDATMemory.Memory);
  1725. end
  1726. else
  1727. begin
  1728. // Alpha is JNG compressed
  1729. Chunk.DataSize := JDAAMemory.Size;
  1730. Chunk.ChunkID := JDAAChunk;
  1731. WriteChunk(Chunk, JDAAMemory.Memory);
  1732. end;
  1733. end;
  1734. // Write image end
  1735. Chunk.DataSize := 0;
  1736. Chunk.ChunkID := IENDChunk;
  1737. WriteChunk(Chunk, nil);
  1738. end
  1739. else if FileType <> ngAPNG then
  1740. begin
  1741. // Regular PNG frame (single PNG image or MNG frame)
  1742. WritePNGMainImageChunks(Frames[I]);
  1743. // Write PNG image data
  1744. Chunk.DataSize := IDATMemory.Size;
  1745. Chunk.ChunkID := IDATChunk;
  1746. WriteChunk(Chunk, IDATMemory.Memory);
  1747. // Write image end
  1748. Chunk.DataSize := 0;
  1749. Chunk.ChunkID := IENDChunk;
  1750. WriteChunk(Chunk, nil);
  1751. end
  1752. else if FileType = ngAPNG then
  1753. begin
  1754. // APNG frame - first frame must have acTL and fcTL before IDAT,
  1755. // subsequent frames have fcTL and fdAT.
  1756. if I = 0 then
  1757. begin
  1758. WritePNGMainImageChunks(Frames[I]);
  1759. Chunk.DataSize := SizeOf(acTL);
  1760. Chunk.ChunkID := acTLChunk;
  1761. WriteChunk(Chunk, @acTL);
  1762. end;
  1763. // Write fcTL before frame data
  1764. Chunk.DataSize := SizeOf(fcTL);
  1765. Chunk.ChunkID := fcTLChunk;
  1766. fcTl.SeqNumber := GetNextSeqNo;
  1767. WriteChunk(Chunk, @fcTL);
  1768. // Write data - IDAT for first frame and fdAT for following ones
  1769. if I = 0 then
  1770. begin
  1771. Chunk.DataSize := IDATMemory.Size;
  1772. Chunk.ChunkID := IDATChunk;
  1773. WriteChunk(Chunk, IDATMemory.Memory);
  1774. end
  1775. else
  1776. WritefdAT(Frames[I]);
  1777. // Write image end after last frame
  1778. if I = Length(Frames) - 1 then
  1779. begin
  1780. Chunk.DataSize := 0;
  1781. Chunk.ChunkID := IENDChunk;
  1782. WriteChunk(Chunk, nil);
  1783. end;
  1784. end;
  1785. end;
  1786. if FileType = ngMNG then
  1787. begin
  1788. Chunk.DataSize := 0;
  1789. Chunk.ChunkID := MENDChunk;
  1790. WriteChunk(Chunk, nil);
  1791. end;
  1792. end;
  1793. procedure TNGFileSaver.SetFileOptions(FileFormat: TNetworkGraphicsFileFormat);
  1794. begin
  1795. PreFilter := FileFormat.FPreFilter;
  1796. CompressLevel := FileFormat.FCompressLevel;
  1797. LossyAlpha := FileFormat.FLossyAlpha;
  1798. Quality := FileFormat.FQuality;
  1799. Progressive := FileFormat.FProgressive;
  1800. end;
  1801. { TAPNGAnimator class implemnetation }
  1802. class procedure TAPNGAnimator.Animate(var Images: TDynImageDataArray;
  1803. const acTL: TacTL; const SrcFrames: array of TFrameInfo);
  1804. var
  1805. I, SrcIdx, Offset, Len: Integer;
  1806. DestFrames: TDynImageDataArray;
  1807. SrcCanvas, DestCanvas: TImagingCanvas;
  1808. PreviousCache: TImageData;
  1809. function AnimatingNeeded: Boolean;
  1810. var
  1811. I: Integer;
  1812. begin
  1813. Result := False;
  1814. for I := 0 to Len - 1 do
  1815. with SrcFrames[I] do
  1816. begin
  1817. if (FrameWidth <> IHDR.Width) or (FrameHeight <> IHDR.Height) or (Len <> acTL.NumFrames) or
  1818. (not ((fcTL.DisposeOp = DisposeOpNone) and (fcTL.BlendOp = BlendOpSource)) and
  1819. not ((fcTL.DisposeOp = DisposeOpBackground) and (fcTL.BlendOp = BlendOpSource)) and
  1820. not ((fcTL.DisposeOp = DisposeOpBackground) and (fcTL.BlendOp = BlendOpOver))) then
  1821. begin
  1822. Result := True;
  1823. Exit;
  1824. end;
  1825. end;
  1826. end;
  1827. begin
  1828. Len := Length(SrcFrames);
  1829. if (Len = 0) or not AnimatingNeeded then
  1830. Exit;
  1831. if (Len = acTL.NumFrames + 1) and (SrcFrames[0].fcTL.Width = 0) then
  1832. begin
  1833. // If default image (stored in IDAT chunk) isn't part of animation we ignore it
  1834. Offset := 1;
  1835. Len := Len - 1;
  1836. end
  1837. else
  1838. Offset := 0;
  1839. SetLength(DestFrames, Len);
  1840. DestCanvas := ImagingCanvases.FindBestCanvasForImage(Images[0]).Create;
  1841. SrcCanvas := ImagingCanvases.FindBestCanvasForImage(Images[0]).Create;
  1842. InitImage(PreviousCache);
  1843. NewImage(SrcFrames[0].IHDR.Width, SrcFrames[0].IHDR.Height, Images[0].Format, PreviousCache);
  1844. for I := 0 to Len - 1 do
  1845. begin
  1846. SrcIdx := I + Offset;
  1847. NewImage(SrcFrames[SrcIdx].IHDR.Width, SrcFrames[SrcIdx].IHDR.Height,
  1848. Images[SrcIdx].Format, DestFrames[I]);
  1849. if DestFrames[I].Format = ifIndex8 then
  1850. Move(Images[SrcIdx].Palette^, DestFrames[I].Palette^, 256 * SizeOf(TColor32));
  1851. DestCanvas.CreateForData(@DestFrames[I]);
  1852. if (SrcFrames[SrcIdx].fcTL.DisposeOp = DisposeOpPrevious) and (SrcFrames[SrcIdx - 1].fcTL.DisposeOp <> DisposeOpPrevious) then
  1853. begin
  1854. // Cache current output buffer so we may return to it later (previous dispose op)
  1855. CopyRect(DestFrames[I - 1], 0, 0, DestFrames[I - 1].Width, DestFrames[I - 1].Height,
  1856. PreviousCache, 0, 0);
  1857. end;
  1858. if (I = 0) or (SrcIdx = 0) then
  1859. begin
  1860. // Clear whole frame with transparent black color (default for first frame)
  1861. DestCanvas.FillColor32 := pcClear;
  1862. DestCanvas.Clear;
  1863. end
  1864. else if SrcFrames[SrcIdx - 1].fcTL.DisposeOp = DisposeOpBackground then
  1865. begin
  1866. // Restore background color (clear) on previous frame's area and leave previous content outside of it
  1867. CopyRect(DestFrames[I - 1], 0, 0, DestFrames[I - 1].Width, DestFrames[I - 1].Height,
  1868. DestFrames[I], 0, 0);
  1869. DestCanvas.FillColor32 := pcClear;
  1870. DestCanvas.FillRect(BoundsToRect(SrcFrames[SrcIdx - 1].fcTL.XOffset, SrcFrames[SrcIdx - 1].fcTL.YOffset,
  1871. SrcFrames[SrcIdx - 1].FrameWidth, SrcFrames[SrcIdx - 1].FrameHeight));
  1872. end
  1873. else if SrcFrames[SrcIdx - 1].fcTL.DisposeOp = DisposeOpNone then
  1874. begin
  1875. // Clone previous frame - no change to output buffer
  1876. CopyRect(DestFrames[I - 1], 0, 0, DestFrames[I - 1].Width, DestFrames[I - 1].Height,
  1877. DestFrames[I], 0, 0);
  1878. end
  1879. else if SrcFrames[SrcIdx - 1].fcTL.DisposeOp = DisposeOpPrevious then
  1880. begin
  1881. // Revert to previous frame (cached, can't just restore DestFrames[I - 2])
  1882. CopyRect(PreviousCache, 0, 0, PreviousCache.Width, PreviousCache.Height,
  1883. DestFrames[I], 0, 0);
  1884. end;
  1885. // Copy pixels or alpha blend them over
  1886. if SrcFrames[SrcIdx].fcTL.BlendOp = BlendOpSource then
  1887. begin
  1888. CopyRect(Images[SrcIdx], 0, 0, Images[SrcIdx].Width, Images[SrcIdx].Height,
  1889. DestFrames[I], SrcFrames[SrcIdx].fcTL.XOffset, SrcFrames[SrcIdx].fcTL.YOffset);
  1890. end
  1891. else if SrcFrames[SrcIdx].fcTL.BlendOp = BlendOpOver then
  1892. begin
  1893. SrcCanvas.CreateForData(@Images[SrcIdx]);
  1894. SrcCanvas.DrawAlpha(SrcCanvas.ClipRect, DestCanvas,
  1895. SrcFrames[SrcIdx].fcTL.XOffset, SrcFrames[SrcIdx].fcTL.YOffset);
  1896. end;
  1897. FreeImage(Images[SrcIdx]);
  1898. end;
  1899. DestCanvas.Free;
  1900. SrcCanvas.Free;
  1901. FreeImage(PreviousCache);
  1902. // Assign dest frames to final output images
  1903. Images := DestFrames;
  1904. end;
  1905. { TNetworkGraphicsFileFormat class implementation }
  1906. constructor TNetworkGraphicsFileFormat.Create;
  1907. begin
  1908. inherited Create;
  1909. FCanLoad := True;
  1910. FCanSave := True;
  1911. FIsMultiImageFormat := False;
  1912. FPreFilter := NGDefaultPreFilter;
  1913. FCompressLevel := NGDefaultCompressLevel;
  1914. FLossyAlpha := NGDefaultLossyAlpha;
  1915. FLossyCompression := NGDefaultLossyCompression;
  1916. FQuality := NGDefaultQuality;
  1917. FProgressive := NGDefaultProgressive;
  1918. end;
  1919. procedure TNetworkGraphicsFileFormat.CheckOptionsValidity;
  1920. begin
  1921. // Just check if save options has valid values
  1922. if not (FPreFilter in [0..6]) then
  1923. FPreFilter := NGDefaultPreFilter;
  1924. if not (FCompressLevel in [0..9]) then
  1925. FCompressLevel := NGDefaultCompressLevel;
  1926. if not (FQuality in [1..100]) then
  1927. FQuality := NGDefaultQuality;
  1928. end;
  1929. function TNetworkGraphicsFileFormat.GetSupportedFormats: TImageFormats;
  1930. begin
  1931. if FLossyCompression then
  1932. Result := NGLossyFormats
  1933. else
  1934. Result := NGLosslessFormats;
  1935. end;
  1936. procedure TNetworkGraphicsFileFormat.ConvertToSupported(var Image: TImageData;
  1937. const Info: TImageFormatInfo);
  1938. var
  1939. ConvFormat: TImageFormat;
  1940. begin
  1941. if not FLossyCompression then
  1942. begin
  1943. // Convert formats for lossless compression
  1944. if Info.HasGrayChannel then
  1945. begin
  1946. if Info.HasAlphaChannel then
  1947. begin
  1948. if Info.BytesPerPixel <= 2 then
  1949. // Convert <= 16bit grayscale images with alpha to ifA8Gray8
  1950. ConvFormat := ifA8Gray8
  1951. else
  1952. // Convert > 16bit grayscale images with alpha to ifA16Gray16
  1953. ConvFormat := ifA16Gray16
  1954. end
  1955. else
  1956. // Convert grayscale images without alpha to ifGray16
  1957. ConvFormat := ifGray16;
  1958. end
  1959. else
  1960. if Info.IsFloatingPoint then
  1961. // Convert floating point images to 64 bit ARGB (or RGB if no alpha)
  1962. ConvFormat := IffFormat(Info.HasAlphaChannel, ifA16B16G16R16, ifB16G16R16)
  1963. else if Info.HasAlphaChannel or Info.IsSpecial then
  1964. // Convert all other images with alpha or special images to A8R8G8B8
  1965. ConvFormat := ifA8R8G8B8
  1966. else
  1967. // Convert images without alpha to R8G8B8
  1968. ConvFormat := ifR8G8B8;
  1969. end
  1970. else
  1971. begin
  1972. // Convert formats for lossy compression
  1973. if Info.HasGrayChannel then
  1974. ConvFormat := IffFormat(Info.HasAlphaChannel, ifA8Gray8, ifGray8)
  1975. else
  1976. ConvFormat := IffFormat(Info.HasAlphaChannel, ifA8R8G8B8, ifR8G8B8);
  1977. end;
  1978. ConvertImage(Image, ConvFormat);
  1979. end;
  1980. function TNetworkGraphicsFileFormat.TestFormat(Handle: TImagingHandle): Boolean;
  1981. var
  1982. ReadCount: LongInt;
  1983. Sig: TChar8;
  1984. begin
  1985. Result := False;
  1986. if Handle <> nil then
  1987. with GetIO do
  1988. begin
  1989. FillChar(Sig, SizeOf(Sig), 0);
  1990. ReadCount := Read(Handle, @Sig, SizeOf(Sig));
  1991. Seek(Handle, -ReadCount, smFromCurrent);
  1992. Result := (ReadCount = SizeOf(Sig)) and (Sig = FSignature);
  1993. end;
  1994. end;
  1995. { TPNGFileFormat class implementation }
  1996. constructor TPNGFileFormat.Create;
  1997. begin
  1998. inherited Create;
  1999. FName := SPNGFormatName;
  2000. FIsMultiImageFormat := True;
  2001. FLoadAnimated := PNGDefaultLoadAnimated;
  2002. AddMasks(SPNGMasks);
  2003. FSignature := PNGSignature;
  2004. RegisterOption(ImagingPNGPreFilter, @FPreFilter);
  2005. RegisterOption(ImagingPNGCompressLevel, @FCompressLevel);
  2006. RegisterOption(ImagingPNGLoadAnimated, @FLoadAnimated);
  2007. end;
  2008. function TPNGFileFormat.LoadData(Handle: TImagingHandle;
  2009. var Images: TDynImageDataArray; OnlyFirstLevel: Boolean): Boolean;
  2010. var
  2011. I, Len: LongInt;
  2012. NGFileLoader: TNGFileLoader;
  2013. begin
  2014. Result := False;
  2015. NGFileLoader := TNGFileLoader.Create;
  2016. try
  2017. // Use NG file parser to load file
  2018. if NGFileLoader.LoadFile(Handle) and (Length(NGFileLoader.Frames) > 0) then
  2019. begin
  2020. Len := Length(NGFileLoader.Frames);
  2021. SetLength(Images, Len);
  2022. for I := 0 to Len - 1 do
  2023. with NGFileLoader.Frames[I] do
  2024. begin
  2025. // Build actual image bits
  2026. if not IsJpegFrame then
  2027. NGFileLoader.LoadImageFromPNGFrame(FrameWidth, FrameHeight, IHDR, IDATMemory, Images[I]);
  2028. // Build palette, aply color key or background
  2029. NGFileLoader.ApplyFrameSettings(NGFileLoader.Frames[I], Images[I]);
  2030. Result := True;
  2031. end;
  2032. // Animate APNG images
  2033. if (NGFileLoader.FileType = ngAPNG) and FLoadAnimated then
  2034. TAPNGAnimator.Animate(Images, NGFileLoader.acTL, NGFileLoader.Frames);
  2035. end;
  2036. finally
  2037. NGFileLoader.Free;
  2038. end;
  2039. end;
  2040. function TPNGFileFormat.SaveData(Handle: TImagingHandle;
  2041. const Images: TDynImageDataArray; Index: LongInt): Boolean;
  2042. var
  2043. I: Integer;
  2044. ImageToSave: TImageData;
  2045. MustBeFreed: Boolean;
  2046. NGFileSaver: TNGFileSaver;
  2047. DefaultFormat: TImageFormat;
  2048. Screen: TImageData;
  2049. AnimWidth, AnimHeight: Integer;
  2050. begin
  2051. Result := False;
  2052. DefaultFormat := ifDefault;
  2053. AnimWidth := 0;
  2054. AnimHeight := 0;
  2055. NGFileSaver := TNGFileSaver.Create;
  2056. // Save images with more frames as APNG format
  2057. if Length(Images) > 1 then
  2058. begin
  2059. NGFileSaver.FileType := ngAPNG;
  2060. NGFileSaver.acTL.NumFrames := FLastIdx - FFirstIdx + 1;
  2061. NGFileSaver.acTL.NumPlay := 1;
  2062. SwapEndianLongWord(@NGFileSaver.acTL, SizeOf(NGFileSaver.acTL) div SizeOf(LongWord));
  2063. // Get max dimensions of frames
  2064. AnimWidth := Images[FFirstIdx].Width;
  2065. AnimHeight := Images[FFirstIdx].Height;
  2066. for I := FFirstIdx + 1 to FLastIdx do
  2067. begin
  2068. AnimWidth := Max(AnimWidth, Images[I].Width);
  2069. AnimHeight := Max(AnimHeight, Images[I].Height);
  2070. end;
  2071. end
  2072. else
  2073. NGFileSaver.FileType := ngPNG;
  2074. NGFileSaver.SetFileOptions(Self);
  2075. with NGFileSaver do
  2076. try
  2077. // Store all frames to be saved frames file saver
  2078. for I := FFirstIdx to FLastIdx do
  2079. begin
  2080. if MakeCompatible(Images[I], ImageToSave, MustBeFreed) then
  2081. try
  2082. if FileType = ngAPNG then
  2083. begin
  2084. // IHDR chunk is shared for all frames so all frames must have the
  2085. // same data format as the first image.
  2086. if I = FFirstIdx then
  2087. begin
  2088. DefaultFormat := ImageToSave.Format;
  2089. // Subsequenet frames may be bigger than the first one.
  2090. // APNG doens't support this - max allowed size is what's written in
  2091. // IHDR - size of main/default/first image. If some frame is
  2092. // bigger than the first one we need to resize (create empty bigger
  2093. // image and copy) the first frame so all following frames could fit to
  2094. // its area.
  2095. if (ImageToSave.Width <> AnimWidth) or (ImageToSave.Height <> AnimHeight) then
  2096. begin
  2097. InitImage(Screen);
  2098. NewImage(AnimWidth, AnimHeight, ImageToSave.Format, Screen);
  2099. CopyRect(ImageToSave, 0, 0, ImageToSave.Width, ImageToSave.Height, Screen, 0, 0);
  2100. if MustBeFreed then
  2101. FreeImage(ImageToSave);
  2102. ImageToSave := Screen;
  2103. end;
  2104. end
  2105. else if ImageToSave.Format <> DefaultFormat then
  2106. begin
  2107. if MustBeFreed then
  2108. ConvertImage(ImageToSave, DefaultFormat)
  2109. else
  2110. begin
  2111. CloneImage(Images[I], ImageToSave);
  2112. ConvertImage(ImageToSave, DefaultFormat);
  2113. MustBeFreed := True;
  2114. end;
  2115. end;
  2116. end;
  2117. // Add image as PNG frame
  2118. AddFrame(ImageToSave, False);
  2119. finally
  2120. if MustBeFreed then
  2121. FreeImage(ImageToSave);
  2122. end
  2123. else
  2124. Exit;
  2125. end;
  2126. // Finally save PNG file
  2127. SaveFile(Handle);
  2128. Result := True;
  2129. finally
  2130. NGFileSaver.Free;
  2131. end;
  2132. end;
  2133. {$IFNDEF DONT_LINK_MNG}
  2134. { TMNGFileFormat class implementation }
  2135. constructor TMNGFileFormat.Create;
  2136. begin
  2137. inherited Create;
  2138. FName := SMNGFormatName;
  2139. FIsMultiImageFormat := True;
  2140. AddMasks(SMNGMasks);
  2141. FSignature := MNGSignature;
  2142. RegisterOption(ImagingMNGLossyCompression, @FLossyCompression);
  2143. RegisterOption(ImagingMNGLossyAlpha, @FLossyAlpha);
  2144. RegisterOption(ImagingMNGPreFilter, @FPreFilter);
  2145. RegisterOption(ImagingMNGCompressLevel, @FCompressLevel);
  2146. RegisterOption(ImagingMNGQuality, @FQuality);
  2147. RegisterOption(ImagingMNGProgressive, @FProgressive);
  2148. end;
  2149. function TMNGFileFormat.LoadData(Handle: TImagingHandle;
  2150. var Images: TDynImageDataArray; OnlyFirstLevel: Boolean): Boolean;
  2151. var
  2152. NGFileLoader: TNGFileLoader;
  2153. I, Len: LongInt;
  2154. begin
  2155. Result := False;
  2156. NGFileLoader := TNGFileLoader.Create;
  2157. try
  2158. // Use NG file parser to load file
  2159. if NGFileLoader.LoadFile(Handle) then
  2160. begin
  2161. Len := Length(NGFileLoader.Frames);
  2162. if Len > 0 then
  2163. begin
  2164. SetLength(Images, Len);
  2165. for I := 0 to Len - 1 do
  2166. with NGFileLoader.Frames[I] do
  2167. begin
  2168. // Build actual image bits
  2169. if IsJpegFrame then
  2170. NGFileLoader.LoadImageFromJNGFrame(FrameWidth, FrameHeight, JHDR, IDATMemory, JDATMemory, JDAAMemory, Images[I])
  2171. else
  2172. NGFileLoader.LoadImageFromPNGFrame(FrameWidth, FrameHeight, IHDR, IDATMemory, Images[I]);
  2173. // Build palette, aply color key or background
  2174. NGFileLoader.ApplyFrameSettings(NGFileLoader.Frames[I], Images[I]);
  2175. end;
  2176. end
  2177. else
  2178. begin
  2179. // Some MNG files (with BASI-IEND streams) dont have actual pixel data
  2180. SetLength(Images, 1);
  2181. NewImage(NGFileLoader.MHDR.FrameWidth, NGFileLoader.MHDR.FrameWidth, ifDefault, Images[0]);
  2182. end;
  2183. Result := True;
  2184. end;
  2185. finally
  2186. NGFileLoader.Free;
  2187. end;
  2188. end;
  2189. function TMNGFileFormat.SaveData(Handle: TImagingHandle;
  2190. const Images: TDynImageDataArray; Index: LongInt): Boolean;
  2191. var
  2192. NGFileSaver: TNGFileSaver;
  2193. I, LargestWidth, LargestHeight: LongInt;
  2194. ImageToSave: TImageData;
  2195. MustBeFreed: Boolean;
  2196. begin
  2197. Result := False;
  2198. LargestWidth := 0;
  2199. LargestHeight := 0;
  2200. NGFileSaver := TNGFileSaver.Create;
  2201. NGFileSaver.FileType := ngMNG;
  2202. NGFileSaver.SetFileOptions(Self);
  2203. with NGFileSaver do
  2204. try
  2205. // Store all frames to be saved frames file saver
  2206. for I := FFirstIdx to FLastIdx do
  2207. begin
  2208. if MakeCompatible(Images[I], ImageToSave, MustBeFreed) then
  2209. try
  2210. // Add image as PNG or JNG frame
  2211. AddFrame(ImageToSave, FLossyCompression);
  2212. // Remember largest frame width and height
  2213. LargestWidth := Iff(LargestWidth < ImageToSave.Width, ImageToSave.Width, LargestWidth);
  2214. LargestHeight := Iff(LargestHeight < ImageToSave.Height, ImageToSave.Height, LargestHeight);
  2215. finally
  2216. if MustBeFreed then
  2217. FreeImage(ImageToSave);
  2218. end
  2219. else
  2220. Exit;
  2221. end;
  2222. // Fill MNG header
  2223. MHDR.FrameWidth := LargestWidth;
  2224. MHDR.FrameHeight := LargestHeight;
  2225. MHDR.TicksPerSecond := 0;
  2226. MHDR.NominalLayerCount := 0;
  2227. MHDR.NominalFrameCount := Length(Frames);
  2228. MHDR.NominalPlayTime := 0;
  2229. MHDR.SimplicityProfile := 473; // 111011001 binary, defines MNG-VLC with transparency and JNG support
  2230. // Finally save MNG file
  2231. SaveFile(Handle);
  2232. Result := True;
  2233. finally
  2234. NGFileSaver.Free;
  2235. end;
  2236. end;
  2237. {$ENDIF}
  2238. {$IFNDEF DONT_LINK_JNG}
  2239. { TJNGFileFormat class implementation }
  2240. constructor TJNGFileFormat.Create;
  2241. begin
  2242. inherited Create;
  2243. FName := SJNGFormatName;
  2244. AddMasks(SJNGMasks);
  2245. FSignature := JNGSignature;
  2246. FLossyCompression := True;
  2247. RegisterOption(ImagingJNGLossyAlpha, @FLossyAlpha);
  2248. RegisterOption(ImagingJNGAlphaPreFilter, @FPreFilter);
  2249. RegisterOption(ImagingJNGAlphaCompressLevel, @FCompressLevel);
  2250. RegisterOption(ImagingJNGQuality, @FQuality);
  2251. RegisterOption(ImagingJNGProgressive, @FProgressive);
  2252. end;
  2253. function TJNGFileFormat.LoadData(Handle: TImagingHandle;
  2254. var Images: TDynImageDataArray; OnlyFirstLevel: Boolean): Boolean;
  2255. var
  2256. NGFileLoader: TNGFileLoader;
  2257. begin
  2258. Result := False;
  2259. NGFileLoader := TNGFileLoader.Create;
  2260. try
  2261. // Use NG file parser to load file
  2262. if NGFileLoader.LoadFile(Handle) and (Length(NGFileLoader.Frames) > 0) then
  2263. with NGFileLoader.Frames[0] do
  2264. begin
  2265. SetLength(Images, 1);
  2266. // Build actual image bits
  2267. if IsJpegFrame then
  2268. NGFileLoader.LoadImageFromJNGFrame(FrameWidth, FrameHeight, JHDR, IDATMemory, JDATMemory, JDAAMemory, Images[0]);
  2269. // Build palette, aply color key or background
  2270. NGFileLoader.ApplyFrameSettings(NGFileLoader.Frames[0], Images[0]);
  2271. Result := True;
  2272. end;
  2273. finally
  2274. NGFileLoader.Free;
  2275. end;
  2276. end;
  2277. function TJNGFileFormat.SaveData(Handle: TImagingHandle;
  2278. const Images: TDynImageDataArray; Index: LongInt): Boolean;
  2279. var
  2280. NGFileSaver: TNGFileSaver;
  2281. ImageToSave: TImageData;
  2282. MustBeFreed: Boolean;
  2283. begin
  2284. // Make image JNG compatible, store it in saver, and save it to file
  2285. Result := MakeCompatible(Images[Index], ImageToSave, MustBeFreed);
  2286. if Result then
  2287. begin
  2288. NGFileSaver := TNGFileSaver.Create;
  2289. with NGFileSaver do
  2290. try
  2291. FileType := ngJNG;
  2292. SetFileOptions(Self);
  2293. AddFrame(ImageToSave, True);
  2294. SaveFile(Handle);
  2295. finally
  2296. // Free NG saver and compatible image
  2297. NGFileSaver.Free;
  2298. if MustBeFreed then
  2299. FreeImage(ImageToSave);
  2300. end;
  2301. end;
  2302. end;
  2303. {$ENDIF}
  2304. initialization
  2305. RegisterImageFileFormat(TPNGFileFormat);
  2306. {$IFNDEF DONT_LINK_MNG}
  2307. RegisterImageFileFormat(TMNGFileFormat);
  2308. {$ENDIF}
  2309. {$IFNDEF DONT_LINK_JNG}
  2310. RegisterImageFileFormat(TJNGFileFormat);
  2311. {$ENDIF}
  2312. finalization
  2313. {
  2314. File Notes:
  2315. -- TODOS ----------------------------------------------------
  2316. - nothing now
  2317. -- 0.26.3 Changes/Bug Fixes ---------------------------------
  2318. - Added APNG saving support.
  2319. - Added APNG support to NG loader and animating to PNG loader.
  2320. -- 0.26.1 Changes/Bug Fixes ---------------------------------
  2321. - Changed file format conditional compilation to reflect changes
  2322. in LINK symbols.
  2323. -- 0.24.3 Changes/Bug Fixes ---------------------------------
  2324. - Changes for better thread safety.
  2325. -- 0.23 Changes/Bug Fixes -----------------------------------
  2326. - Added loading of global palettes and transparencies in MNG files
  2327. (and by doing so fixed crash when loading images with global PLTE or tRNS).
  2328. -- 0.21 Changes/Bug Fixes -----------------------------------
  2329. - Small changes in converting to supported formats.
  2330. - MakeCompatible method moved to base class, put ConvertToSupported here.
  2331. GetSupportedFormats removed, it is now set in constructor.
  2332. - Made public properties for options registered to SetOption/GetOption
  2333. functions.
  2334. - Changed extensions to filename masks.
  2335. - Changed SaveData, LoadData, and MakeCompatible methods according
  2336. to changes in base class in Imaging unit.
  2337. -- 0.17 Changes/Bug Fixes -----------------------------------
  2338. - MNG and JNG support added, PNG support redesigned to support NG file handlers
  2339. - added classes for working with NG file formats
  2340. - stuff from old ImagingPng unit added and that unit was deleted
  2341. - unit created and initial stuff added
  2342. -- 0.15 Changes/Bug Fixes -----------------------------------
  2343. - when saving indexed images save alpha to tRNS?
  2344. - added some defines and ifdefs to dzlib unit to allow choosing
  2345. impaszlib, fpc's paszlib, zlibex or other zlib implementation
  2346. - added colorkeying support
  2347. - fixed 16bit channel image handling - pixels were not swapped
  2348. - fixed arithmetic overflow (in paeth filter) in FPC
  2349. - data of unknown chunks are skipped and not needlesly loaded
  2350. -- 0.13 Changes/Bug Fixes -----------------------------------
  2351. - adaptive filtering added to PNG saving
  2352. - TPNGFileFormat class added
  2353. }
  2354. end.