GR32_PortableNetworkGraphic.pas 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883
  1. unit GR32_PortableNetworkGraphic;
  2. (* ***** BEGIN LICENSE BLOCK *****
  3. * Version: MPL 1.1 or LGPL 2.1 with linking exception
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. * http://www.mozilla.org/MPL/
  9. *
  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
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. *
  15. * Alternatively, the contents of this file may be used under the terms of the
  16. * Free Pascal modified version of the GNU Lesser General Public License
  17. * Version 2.1 (the "FPC modified LGPL License"), in which case the provisions
  18. * of this license are applicable instead of those above.
  19. * Please see the file LICENSE.txt for additional information concerning this
  20. * license.
  21. *
  22. * The Original Code is GR32PNG for Graphics32
  23. *
  24. * The Initial Developer of the Original Code is
  25. * Christian-W. Budde
  26. *
  27. * Portions created by the Initial Developer are Copyright (C) 2000-2009
  28. * the Initial Developer. All Rights Reserved.
  29. *
  30. * Contributor(s):
  31. *
  32. * ***** END LICENSE BLOCK ***** *)
  33. interface
  34. {$include GR32.inc}
  35. {$include GR32_PngCompilerSwitches.inc}
  36. // The following defines controls if the corresponding incomplete chunk
  37. // implementations should be enabled. They are disabled by default because
  38. // a complete implementation is required in order to pass the roundtrip unit
  39. // tests.
  40. {-$define PNG_CHUNK_SUGGESTED_PALETTE}
  41. {-$define PNG_CHUNK_INTERNATIONAL_TEXT}
  42. uses
  43. Classes, Graphics, SysUtils,
  44. {$IFDEF FPC}
  45. ZBase, ZDeflate, ZInflate;
  46. {$ELSE}
  47. {$IFDEF ZLibEx}
  48. ZLibEx, ZLibExApi;
  49. {$ELSE}
  50. {$if (CompilerVersion >= 32)} System.zlib; {$else} zlib; {$ifend}
  51. {$ENDIF}
  52. {$ENDIF}
  53. type
  54. {$A1}
  55. TColorType = (
  56. ctGrayscale = 0,
  57. ctTrueColor = 2,
  58. ctIndexedColor = 3,
  59. ctGrayscaleAlpha = 4,
  60. ctTrueColorAlpha = 6
  61. );
  62. TFilterMethod = (
  63. fmAdaptiveFilter = 0
  64. );
  65. TAdaptiveFilterMethod = (
  66. afmNone = 0,
  67. afmSub = 1,
  68. afmUp = 2,
  69. afmAverage = 3,
  70. afmPaeth = 4
  71. );
  72. TAvailableAdaptiveFilterMethod = (aafmSub, aafmUp, aafmAverage, aafmPaeth);
  73. TAvailableAdaptiveFilterMethods = set of TAvailableAdaptiveFilterMethod;
  74. TInterlaceMethod = (
  75. imNone = 0,
  76. imAdam7 = 1
  77. );
  78. TRGB24 = packed record
  79. R, G, B: Byte;
  80. end;
  81. PRGB24 = ^TRGB24;
  82. TRGB24Array = array [0..0] of TRGB24;
  83. PRGB24Array = ^TRGB24Array;
  84. TRGB24Word = packed record
  85. R, G, B : Word;
  86. end;
  87. PRGB24Word = ^TRGB24Word;
  88. TRGB32 = packed record
  89. R, G, B, A: Byte;
  90. end;
  91. PRGB32 = ^TRGB32;
  92. TRGB32Word = packed record
  93. R, G, B, A: Word;
  94. end;
  95. PRGB32Word = ^TRGB32Word;
  96. PByteArray = SysUtils.PByteArray;
  97. TByteArray = SysUtils.TByteArray;
  98. TChunkName = array [0..3] of AnsiChar;
  99. EPngError = class(Exception);
  100. {$IFDEF FPC}
  101. TZStreamRec = z_stream;
  102. {$ENDIF}
  103. {$A4}
  104. TCustomChunk = class abstract(TPersistent)
  105. protected
  106. function GetChunkNameAsString: AnsiString; virtual; abstract;
  107. function GetChunkName: TChunkName; virtual; abstract;
  108. function GetChunkSize: Cardinal; virtual; abstract;
  109. public
  110. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); virtual; abstract;
  111. procedure WriteToStream(Stream: TStream); virtual; abstract;
  112. property ChunkName: TChunkName read GetChunkName;
  113. property ChunkNameAsString: AnsiString read GetChunkNameAsString;
  114. property ChunkSize: Cardinal read GetChunkSize;
  115. end;
  116. TCustomDefinedChunk = class abstract(TCustomChunk)
  117. protected
  118. function GetChunkNameAsString: AnsiString; override;
  119. function GetChunkName: TChunkName; override;
  120. class function GetClassChunkName: TChunkName; virtual; abstract;
  121. public
  122. property ChunkName: TChunkName read GetClassChunkName;
  123. end;
  124. TCustomDefinedChunkClass = class of TCustomDefinedChunk;
  125. TChunkPngImageHeader = class(TCustomDefinedChunk)
  126. private
  127. FWidth : Integer;
  128. FHeight : Integer;
  129. FBitDepth : Byte;
  130. FColorType : TColorType;
  131. FCompressionMethod : Byte;
  132. FFilterMethod : TFilterMethod;
  133. FInterlaceMethod : TInterlaceMethod;
  134. FAdaptiveFilterMethods : TAvailableAdaptiveFilterMethods;
  135. function GetHasPalette: Boolean;
  136. function GetBytesPerRow: Integer;
  137. function GetPixelByteSize: Integer;
  138. procedure SetCompressionMethod(const Value: Byte);
  139. procedure SetFilterMethod(const Value: TFilterMethod);
  140. procedure SetAdaptiveFilterMethods(const Value: TAvailableAdaptiveFilterMethods);
  141. protected
  142. class function GetClassChunkName: TChunkName; override;
  143. function GetChunkSize: Cardinal; override;
  144. procedure AssignTo(Dest: TPersistent); override;
  145. public
  146. constructor Create; virtual;
  147. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  148. procedure WriteToStream(Stream: TStream); override;
  149. procedure ResetToDefault; virtual;
  150. property Width: Integer read FWidth write FWidth;
  151. property Height: Integer read FHeight write FHeight;
  152. property BitDepth: Byte read FBitDepth write FBitDepth;
  153. property ColorType: TColorType read FColorType write FColorType;
  154. property CompressionMethod: Byte read FCompressionMethod write SetCompressionMethod;
  155. property AdaptiveFilterMethods: TAvailableAdaptiveFilterMethods read FAdaptiveFilterMethods write SetAdaptiveFilterMethods;
  156. property FilterMethod: TFilterMethod read FFilterMethod write SetFilterMethod;
  157. property InterlaceMethod: TInterlaceMethod read FInterlaceMethod write FInterlaceMethod;
  158. property HasPalette: Boolean read GetHasPalette;
  159. property BytesPerRow: Integer read GetBytesPerRow;
  160. property PixelByteSize: Integer read GetPixelByteSize;
  161. end;
  162. TCustomDefinedChunkWithHeader = class(TCustomDefinedChunk)
  163. protected
  164. FHeader : TChunkPngImageHeader;
  165. procedure AssignTo(Dest: TPersistent); override;
  166. public
  167. constructor Create(Header: TChunkPngImageHeader); reintroduce; virtual;
  168. procedure HeaderChanged; virtual;
  169. property Header: TChunkPngImageHeader read FHeader;
  170. end;
  171. TCustomDefinedChunkWithHeaderClass = class of TCustomDefinedChunkWithHeader;
  172. TChunkPngImageData = class(TCustomDefinedChunkWithHeader)
  173. private
  174. FData : TMemoryStream;
  175. protected
  176. class function GetClassChunkName: TChunkName; override;
  177. function GetChunkSize: Cardinal; override;
  178. procedure AssignTo(Dest: TPersistent); override;
  179. public
  180. constructor Create(Header: TChunkPngImageHeader); override;
  181. destructor Destroy; override;
  182. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  183. procedure WriteToStream(Stream: TStream); override;
  184. property Data: TMemoryStream read FData;
  185. end;
  186. TChunkPngPalette = class(TCustomDefinedChunkWithHeader)
  187. private
  188. FPaletteEntries : array of TRGB24;
  189. function GetPaletteEntry(Index: Cardinal): TRGB24;
  190. function GetCount: Cardinal;
  191. procedure SetCount(const Value: Cardinal);
  192. procedure SetPaletteEntry(Index: Cardinal; const Value: TRGB24);
  193. protected
  194. procedure AssignTo(Dest: TPersistent); override;
  195. class function GetClassChunkName: TChunkName; override;
  196. function GetChunkSize: Cardinal; override;
  197. procedure PaletteEntriesChanged; virtual;
  198. public
  199. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  200. procedure WriteToStream(Stream: TStream); override;
  201. property PaletteEntry[Index: Cardinal]: TRGB24 read GetPaletteEntry write SetPaletteEntry; default;
  202. property Count: Cardinal read GetCount write SetCount;
  203. end;
  204. TChunkPngGamma = class(TCustomDefinedChunkWithHeader)
  205. private
  206. FGamma : Cardinal;
  207. function GetGammaAsSingle: Single;
  208. procedure SetGammaAsSingle(const Value: Single);
  209. protected
  210. class function GetClassChunkName: TChunkName; override;
  211. function GetChunkSize: Cardinal; override;
  212. procedure AssignTo(Dest: TPersistent); override;
  213. public
  214. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  215. procedure WriteToStream(Stream: TStream); override;
  216. property Gamma: Cardinal read FGamma write FGamma;
  217. property GammaAsSingle: Single read GetGammaAsSingle write SetGammaAsSingle;
  218. end;
  219. TChunkPngStandardColorSpaceRGB = class(TCustomDefinedChunkWithHeader)
  220. private
  221. FRenderingIntent : Byte;
  222. protected
  223. class function GetClassChunkName: TChunkName; override;
  224. function GetChunkSize: Cardinal; override;
  225. procedure AssignTo(Dest: TPersistent); override;
  226. public
  227. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  228. procedure WriteToStream(Stream: TStream); override;
  229. property RenderingIntent: Byte read FRenderingIntent write FRenderingIntent;
  230. end;
  231. TChunkPngPrimaryChromaticities = class(TCustomDefinedChunkWithHeader)
  232. private
  233. FWhiteX : Integer;
  234. FWhiteY : Integer;
  235. FRedX : Integer;
  236. FRedY : Integer;
  237. FGreenX : Integer;
  238. FGreenY : Integer;
  239. FBlueX : Integer;
  240. FBlueY : Integer;
  241. function GetBlueX: Single;
  242. function GetBlueY: Single;
  243. function GetGreenX: Single;
  244. function GetGreenY: Single;
  245. function GetRedX: Single;
  246. function GetRedY: Single;
  247. function GetWhiteX: Single;
  248. function GetWhiteY: Single;
  249. procedure SetBlueX(const Value: Single);
  250. procedure SetBlueY(const Value: Single);
  251. procedure SetGreenX(const Value: Single);
  252. procedure SetGreenY(const Value: Single);
  253. procedure SetRedX(const Value: Single);
  254. procedure SetRedY(const Value: Single);
  255. procedure SetWhiteX(const Value: Single);
  256. procedure SetWhiteY(const Value: Single);
  257. protected
  258. class function GetClassChunkName: TChunkName; override;
  259. function GetChunkSize: Cardinal; override;
  260. procedure AssignTo(Dest: TPersistent); override;
  261. public
  262. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  263. procedure WriteToStream(Stream: TStream); override;
  264. property WhiteX: Integer read FWhiteX write FWhiteX;
  265. property WhiteY: Integer read FWhiteY write FWhiteY;
  266. property RedX: Integer read FRedX write FRedX;
  267. property RedY: Integer read FRedY write FRedY;
  268. property GreenX: Integer read FGreenX write FGreenX;
  269. property GreenY: Integer read FGreenY write FGreenY;
  270. property BlueX: Integer read FBlueX write FBlueX;
  271. property BlueY: Integer read FBlueY write FBlueY;
  272. property WhiteXAsSingle: Single read GetWhiteX write SetWhiteX;
  273. property WhiteYAsSingle: Single read GetWhiteY write SetWhiteY;
  274. property RedXAsSingle: Single read GetRedX write SetRedX;
  275. property RedYAsSingle: Single read GetRedY write SetRedY;
  276. property GreenXAsSingle: Single read GetGreenX write SetGreenX;
  277. property GreenYAsSingle: Single read GetGreenY write SetGreenY;
  278. property BlueXAsSingle: Single read GetBlueX write SetBlueX;
  279. property BlueYAsSingle: Single read GetBlueY write SetBlueY;
  280. end;
  281. TChunkPngTime = class(TCustomDefinedChunkWithHeader)
  282. private
  283. FYear : Word;
  284. FMonth : Byte;
  285. FDay : Byte;
  286. FHour : Byte;
  287. FMinute : Byte;
  288. FSecond : Byte;
  289. function GetModifiedDateTime: TDateTime;
  290. procedure SetModifiedDateTime(const Value: TDateTime);
  291. protected
  292. class function GetClassChunkName: TChunkName; override;
  293. function GetChunkSize: Cardinal; override;
  294. procedure AssignTo(Dest: TPersistent); override;
  295. public
  296. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  297. procedure WriteToStream(Stream: TStream); override;
  298. property Year: Word read FYear write FYear;
  299. property Month: Byte read FMonth write FMonth;
  300. property Day: Byte read FDay write FDay;
  301. property Hour: Byte read FHour write FHour;
  302. property Minute: Byte read FMinute write FMinute;
  303. property Second: Byte read FSecond write FSecond;
  304. property ModifiedDateTime: TDateTime read GetModifiedDateTime write SetModifiedDateTime;
  305. end;
  306. TChunkPngEmbeddedIccProfile = class(TCustomDefinedChunkWithHeader)
  307. private
  308. FProfileName : AnsiString;
  309. FCompressionMethod : Byte;
  310. protected
  311. class function GetClassChunkName: TChunkName; override;
  312. function GetChunkSize: Cardinal; override;
  313. procedure AssignTo(Dest: TPersistent); override;
  314. public
  315. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  316. procedure WriteToStream(Stream: TStream); override;
  317. property ProfileName: AnsiString read FProfileName write FProfileName;
  318. property CompressionMethod: Byte read FCompressionMethod write FCompressionMethod;
  319. end;
  320. TCustomPngSignificantBits = class abstract(TPersistent)
  321. protected
  322. class function GetChunkSize: Cardinal; virtual; abstract;
  323. public
  324. constructor Create(BitDepth: Integer = 8); virtual; abstract;
  325. procedure ReadFromStream(Stream: TStream); virtual; abstract;
  326. procedure WriteToStream(Stream: TStream); virtual; abstract;
  327. property ChunkSize: Cardinal read GetChunkSize;
  328. end;
  329. TPngSignificantBitsFormat0 = class(TCustomPngSignificantBits)
  330. private
  331. FGrayBits : Byte;
  332. protected
  333. class function GetChunkSize: Cardinal; override;
  334. procedure AssignTo(Dest: TPersistent); override;
  335. public
  336. constructor Create(BitDepth: Integer = 8); override;
  337. procedure ReadFromStream(Stream: TStream); override;
  338. procedure WriteToStream(Stream: TStream); override;
  339. property GrayBits: Byte read FGrayBits write FGrayBits;
  340. end;
  341. TPngSignificantBitsFormat23 = class(TCustomPngSignificantBits)
  342. private
  343. FRedBits : Byte;
  344. FBlueBits : Byte;
  345. FGreenBits : Byte;
  346. protected
  347. class function GetChunkSize: Cardinal; override;
  348. procedure AssignTo(Dest: TPersistent); override;
  349. public
  350. constructor Create(BitDepth: Integer = 8); override;
  351. procedure ReadFromStream(Stream: TStream); override;
  352. procedure WriteToStream(Stream: TStream); override;
  353. property RedBits: Byte read FRedBits write FRedBits;
  354. property BlueBits: Byte read FBlueBits write FBlueBits;
  355. property GreenBits: Byte read FGreenBits write FGreenBits;
  356. end;
  357. TPngSignificantBitsFormat4 = class(TCustomPngSignificantBits)
  358. private
  359. FGrayBits : Byte;
  360. FAlphaBits : Byte;
  361. protected
  362. class function GetChunkSize: Cardinal; override;
  363. procedure AssignTo(Dest: TPersistent); override;
  364. public
  365. constructor Create(BitDepth: Integer = 8); override;
  366. procedure ReadFromStream(Stream: TStream); override;
  367. procedure WriteToStream(Stream: TStream); override;
  368. property GrayBits: Byte read FGrayBits write FGrayBits;
  369. property AlphaBits: Byte read FAlphaBits write FAlphaBits;
  370. end;
  371. TPngSignificantBitsFormat6 = class(TCustomPngSignificantBits)
  372. private
  373. FRedBits : Byte;
  374. FBlueBits : Byte;
  375. FGreenBits : Byte;
  376. FAlphaBits : Byte;
  377. protected
  378. class function GetChunkSize: Cardinal; override;
  379. procedure AssignTo(Dest: TPersistent); override;
  380. public
  381. constructor Create(BitDepth: Integer = 8); override;
  382. procedure ReadFromStream(Stream: TStream); override;
  383. procedure WriteToStream(Stream: TStream); override;
  384. property RedBits: Byte read FRedBits write FRedBits;
  385. property BlueBits: Byte read FBlueBits write FBlueBits;
  386. property GreenBits: Byte read FGreenBits write FGreenBits;
  387. property AlphaBits: Byte read FAlphaBits write FAlphaBits;
  388. end;
  389. TChunkPngSignificantBits = class(TCustomDefinedChunkWithHeader)
  390. private
  391. FSignificantBits : TCustomPngSignificantBits;
  392. protected
  393. class function GetClassChunkName: TChunkName; override;
  394. function GetChunkSize: Cardinal; override;
  395. procedure AssignTo(Dest: TPersistent); override;
  396. public
  397. constructor Create(Header: TChunkPngImageHeader); override;
  398. destructor Destroy; override;
  399. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  400. procedure WriteToStream(Stream: TStream); override;
  401. procedure HeaderChanged; override;
  402. property SignificantBits: TCustomPngSignificantBits read FSignificantBits;
  403. end;
  404. TCustomPngBackgroundColor = class abstract(TPersistent)
  405. protected
  406. class function GetChunkSize: Cardinal; virtual; abstract;
  407. public
  408. procedure ReadFromStream(Stream: TStream); virtual; abstract;
  409. procedure WriteToStream(Stream: TStream); virtual; abstract;
  410. property ChunkSize: Cardinal read GetChunkSize;
  411. end;
  412. TPngBackgroundColorFormat04 = class(TCustomPngBackgroundColor)
  413. private
  414. FGraySampleValue : Word;
  415. protected
  416. class function GetChunkSize: Cardinal; override;
  417. procedure AssignTo(Dest: TPersistent); override;
  418. public
  419. procedure ReadFromStream(Stream: TStream); override;
  420. procedure WriteToStream(Stream: TStream); override;
  421. property GraySampleValue: Word read FGraySampleValue write FGraySampleValue;
  422. end;
  423. TPngBackgroundColorFormat26 = class(TCustomPngBackgroundColor)
  424. private
  425. FRedSampleValue : Word;
  426. FBlueSampleValue : Word;
  427. FGreenSampleValue : Word;
  428. protected
  429. class function GetChunkSize: Cardinal; override;
  430. procedure AssignTo(Dest: TPersistent); override;
  431. public
  432. procedure ReadFromStream(Stream: TStream); override;
  433. procedure WriteToStream(Stream: TStream); override;
  434. property RedSampleValue: Word read FRedSampleValue write FRedSampleValue;
  435. property BlueSampleValue: Word read FBlueSampleValue write FBlueSampleValue;
  436. property GreenSampleValue: Word read FGreenSampleValue write FGreenSampleValue;
  437. end;
  438. TPngBackgroundColorFormat3 = class(TCustomPngBackgroundColor)
  439. private
  440. FIndex : Byte;
  441. protected
  442. class function GetChunkSize: Cardinal; override;
  443. procedure AssignTo(Dest: TPersistent); override;
  444. public
  445. procedure ReadFromStream(Stream: TStream); override;
  446. procedure WriteToStream(Stream: TStream); override;
  447. property PaletteIndex: Byte read FIndex write FIndex;
  448. end;
  449. TChunkPngBackgroundColor = class(TCustomDefinedChunkWithHeader)
  450. private
  451. FBackground : TCustomPngBackgroundColor;
  452. protected
  453. class function GetClassChunkName: TChunkName; override;
  454. function GetChunkSize: Cardinal; override;
  455. procedure AssignTo(Dest: TPersistent); override;
  456. public
  457. constructor Create(Header: TChunkPngImageHeader); override;
  458. destructor Destroy; override;
  459. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  460. procedure WriteToStream(Stream: TStream); override;
  461. procedure HeaderChanged; override;
  462. property Background: TCustomPngBackgroundColor read FBackground;
  463. end;
  464. TChunkPngImageHistogram = class(TCustomDefinedChunkWithHeader)
  465. private
  466. FHistogram : array of Word;
  467. function GetCount: Cardinal;
  468. function GetFrequency(Index: Cardinal): Word;
  469. protected
  470. class function GetClassChunkName: TChunkName; override;
  471. function GetChunkSize: Cardinal; override;
  472. public
  473. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  474. procedure WriteToStream(Stream: TStream); override;
  475. property Count: Cardinal read GetCount;
  476. property Frequency[Index: Cardinal]: Word read GetFrequency;
  477. end;
  478. TSuggestedPalette8ByteEntry = record
  479. Red : Byte;
  480. Green : Byte;
  481. Blue : Byte;
  482. Alpha : Byte;
  483. Frequency : Word;
  484. end;
  485. PSuggestedPalette8ByteEntry = ^TSuggestedPalette8ByteEntry;
  486. TSuggestedPalette8ByteArray = array [0..0] of TSuggestedPalette8ByteEntry;
  487. PSuggestedPalette8ByteArray = ^TSuggestedPalette8ByteArray;
  488. TSuggestedPalette16ByteEntry = record
  489. Red : Word;
  490. Green : Word;
  491. Blue : Word;
  492. Alpha : Word;
  493. Frequency : Word;
  494. end;
  495. PSuggestedPalette16ByteEntry = ^TSuggestedPalette16ByteEntry;
  496. TSuggestedPalette16ByteArray = array [0..0] of TSuggestedPalette16ByteEntry;
  497. PSuggestedPalette16ByteArray = ^TSuggestedPalette16ByteArray;
  498. {$ifdef PNG_CHUNK_SUGGESTED_PALETTE}
  499. TChunkPngSuggestedPalette = class(TCustomDefinedChunkWithHeader)
  500. private
  501. FPaletteName : AnsiString;
  502. FData : Pointer;
  503. FCount : Cardinal;
  504. FSampleDepth : Byte;
  505. function GetCount: Cardinal;
  506. protected
  507. class function GetClassChunkName: TChunkName; override;
  508. function GetChunkSize: Cardinal; override;
  509. public
  510. constructor Create(Header: TChunkPngImageHeader); override;
  511. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  512. procedure WriteToStream(Stream: TStream); override;
  513. property Count: Cardinal read GetCount;
  514. end;
  515. {$endif PNG_CHUNK_SUGGESTED_PALETTE}
  516. TCustomPngTransparency = class abstract(TPersistent)
  517. protected
  518. function GetChunkSize: Cardinal; virtual; abstract;
  519. public
  520. procedure ReadFromStream(Stream: TStream); virtual; abstract;
  521. procedure WriteToStream(Stream: TStream); virtual; abstract;
  522. property ChunkSize: Cardinal read GetChunkSize;
  523. end;
  524. TPngTransparencyFormat0 = class(TCustomPngTransparency)
  525. private
  526. FGraySampleValue : Word;
  527. protected
  528. procedure AssignTo(Dest: TPersistent); override;
  529. function GetChunkSize: Cardinal; override;
  530. public
  531. procedure ReadFromStream(Stream: TStream); override;
  532. procedure WriteToStream(Stream: TStream); override;
  533. property GraySampleValue: Word read FGraySampleValue write FGraySampleValue;
  534. end;
  535. TPngTransparencyFormat2 = class(TCustomPngTransparency)
  536. private
  537. FRedSampleValue : Word;
  538. FBlueSampleValue : Word;
  539. FGreenSampleValue : Word;
  540. protected
  541. procedure AssignTo(Dest: TPersistent); override;
  542. function GetChunkSize: Cardinal; override;
  543. public
  544. procedure ReadFromStream(Stream: TStream); override;
  545. procedure WriteToStream(Stream: TStream); override;
  546. property RedSampleValue: Word read FRedSampleValue write FRedSampleValue;
  547. property BlueSampleValue: Word read FBlueSampleValue write FBlueSampleValue;
  548. property GreenSampleValue: Word read FGreenSampleValue write FGreenSampleValue;
  549. end;
  550. TPngTransparencyFormat3 = class(TCustomPngTransparency)
  551. private
  552. function GetCount: Cardinal;
  553. function GetTransparency(Index: Cardinal): Byte;
  554. protected
  555. FTransparency : array of Byte;
  556. procedure AssignTo(Dest: TPersistent); override;
  557. function GetChunkSize: Cardinal; override;
  558. public
  559. procedure ReadFromStream(Stream: TStream); override;
  560. procedure WriteToStream(Stream: TStream); override;
  561. property Count: Cardinal read GetCount;
  562. property Transparency[Index: Cardinal]: Byte read GetTransparency;
  563. end;
  564. TChunkPngTransparency = class(TCustomDefinedChunkWithHeader)
  565. protected
  566. FTransparency : TCustomPngTransparency;
  567. class function GetClassChunkName: TChunkName; override;
  568. function GetChunkSize: Cardinal; override;
  569. procedure AssignTo(Dest: TPersistent); override;
  570. public
  571. constructor Create(Header: TChunkPngImageHeader); override;
  572. destructor Destroy; override;
  573. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  574. procedure WriteToStream(Stream: TStream); override;
  575. procedure HeaderChanged; override;
  576. property Transparency: TCustomPngTransparency read FTransparency;
  577. end;
  578. TChunkPngPhysicalPixelDimensions = class(TCustomDefinedChunkWithHeader)
  579. private
  580. FPixelsPerUnitX : Cardinal;
  581. FPixelsPerUnitY : Cardinal;
  582. FUnit : Byte;
  583. protected
  584. class function GetClassChunkName: TChunkName; override;
  585. function GetChunkSize: Cardinal; override;
  586. procedure AssignTo(Dest: TPersistent); override;
  587. public
  588. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  589. procedure WriteToStream(Stream: TStream); override;
  590. property PixelsPerUnitX: Cardinal read FPixelsPerUnitX write FPixelsPerUnitX;
  591. property PixelsPerUnitY: Cardinal read FPixelsPerUnitY write FPixelsPerUnitY;
  592. property PixelUnit: Byte read FUnit write FUnit;
  593. end;
  594. TChunkPngPhysicalScale = class(TCustomDefinedChunkWithHeader)
  595. private
  596. FUnitSpecifier : Byte;
  597. FUnitsPerPixelX : Single;
  598. FUnitsPerPixelY : Single;
  599. protected
  600. class function GetClassChunkName: TChunkName; override;
  601. function GetChunkSize: Cardinal; override;
  602. procedure AssignTo(Dest: TPersistent); override;
  603. public
  604. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  605. procedure WriteToStream(Stream: TStream); override;
  606. property UnitSpecifier: Byte read FUnitSpecifier write FUnitSpecifier;
  607. property UnitsPerPixelX: Single read FUnitsPerPixelX write FUnitsPerPixelX;
  608. property UnitsPerPixelY: Single read FUnitsPerPixelY write FUnitsPerPixelY;
  609. end;
  610. TChunkPngImageOffset = class(TCustomDefinedChunkWithHeader)
  611. private
  612. FImagePositionX : Integer;
  613. FImagePositionY : Integer;
  614. FUnitSpecifier : Byte;
  615. protected
  616. class function GetClassChunkName: TChunkName; override;
  617. function GetChunkSize: Cardinal; override;
  618. procedure AssignTo(Dest: TPersistent); override;
  619. public
  620. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  621. procedure WriteToStream(Stream: TStream); override;
  622. property UnitSpecifier: Byte read FUnitSpecifier write FUnitSpecifier;
  623. property ImagePositionX: Integer read FImagePositionX write FImagePositionX;
  624. property ImagePositionY: Integer read FImagePositionY write FImagePositionY;
  625. end;
  626. TChunkPngPixelCalibrator = class(TCustomDefinedChunkWithHeader)
  627. private
  628. FCalibratorName : AnsiString;
  629. FOriginalZeroes : array [0..1] of Integer;
  630. FEquationType : Byte;
  631. FNumberOfParams : Byte;
  632. FUnitName : AnsiString;
  633. protected
  634. class function GetClassChunkName: TChunkName; override;
  635. function GetChunkSize: Cardinal; override;
  636. procedure AssignTo(Dest: TPersistent); override;
  637. public
  638. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  639. procedure WriteToStream(Stream: TStream); override;
  640. property CalibratorName: AnsiString read FCalibratorName write FCalibratorName;
  641. property OriginalZeroMin: Integer read FOriginalZeroes[0] write FOriginalZeroes[0];
  642. property OriginalZeroMax: Integer read FOriginalZeroes[1] write FOriginalZeroes[1];
  643. property EquationType: Byte read FEquationType write FEquationType;
  644. property NumberOfParams: Byte read FNumberOfParams write FNumberOfParams;
  645. end;
  646. TCustomChunkPngText = class(TCustomDefinedChunkWithHeader)
  647. private
  648. procedure SetKeyword(const Value: AnsiString);
  649. procedure SetText(const Value: AnsiString);
  650. protected
  651. FKeyword : AnsiString;
  652. FText : AnsiString;
  653. procedure AssignTo(Dest: TPersistent); override;
  654. procedure KeywordChanged; virtual;
  655. procedure TextChanged; virtual;
  656. public
  657. property Keyword: AnsiString read FKeyword write SetKeyword;
  658. property Text: AnsiString read FText write SetText;
  659. end;
  660. TChunkPngText = class(TCustomChunkPngText)
  661. protected
  662. class function GetClassChunkName: TChunkName; override;
  663. function GetChunkSize: Cardinal; override;
  664. public
  665. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  666. procedure WriteToStream(Stream: TStream); override;
  667. end;
  668. TChunkPngCompressedText = class(TCustomChunkPngText)
  669. private
  670. FCompressionMethod : Byte;
  671. protected
  672. class function GetClassChunkName: TChunkName; override;
  673. function GetChunkSize: Cardinal; override;
  674. procedure SetCompressionMethod(const Value: Byte);
  675. procedure AssignTo(Dest: TPersistent); override;
  676. public
  677. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  678. procedure WriteToStream(Stream: TStream); override;
  679. property CompressionMethod: Byte read FCompressionMethod write SetCompressionMethod;
  680. end;
  681. {$ifdef PNG_CHUNK_INTERNATIONAL_TEXT}
  682. TChunkPngInternationalText = class(TCustomChunkPngText)
  683. private
  684. FCompressionMethod : Byte;
  685. FCompressionFlag : Byte;
  686. FLanguageString : AnsiString;
  687. FTranslatedKeyword : string;
  688. protected
  689. class function GetClassChunkName: TChunkName; override;
  690. function GetChunkSize: Cardinal; override;
  691. procedure AssignTo(Dest: TPersistent); override;
  692. public
  693. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  694. procedure WriteToStream(Stream: TStream); override;
  695. property CompressionMethod: Byte read FCompressionMethod write FCompressionMethod;
  696. property CompressionFlag: Byte read FCompressionFlag write FCompressionFlag;
  697. property LanguageString: AnsiString read FLanguageString write FLanguageString;
  698. property TranslatedKeyword: string read FTranslatedKeyword write FTranslatedKeyword;
  699. end;
  700. {$endif PNG_CHUNK_INTERNATIONAL_TEXT}
  701. TChunkPngUnknown = class(TCustomChunk)
  702. private
  703. function GetData(index: Integer): Byte;
  704. procedure SetData(index: Integer; const Value: Byte);
  705. protected
  706. FChunkName : TChunkName;
  707. FDataStream : TMemoryStream;
  708. function GetChunkName: TChunkName; override;
  709. function GetChunkNameAsString: AnsiString; override;
  710. function GetChunkSize: Cardinal; override;
  711. function CalculateChecksum: Integer;
  712. procedure AssignTo(Dest: TPersistent); override;
  713. public
  714. constructor Create(ChunkName: TChunkName); virtual;
  715. destructor Destroy; override;
  716. procedure ReadFromStream(Stream: TStream; ChunkSize: Cardinal); override;
  717. procedure WriteToStream(Stream: TStream); override;
  718. property Data[index : Integer]: Byte read GetData write SetData;
  719. property DataStream: TMemoryStream read FDataStream;
  720. end;
  721. TChunkList = class(TPersistent)
  722. private
  723. FChunks : array of TCustomChunk;
  724. function GetCount: Cardinal;
  725. protected
  726. function GetChunk(Index: Integer): TCustomChunk;
  727. procedure AssignTo(Dest: TPersistent); override;
  728. public
  729. destructor Destroy; override;
  730. procedure Add(Item: TCustomChunk);
  731. procedure Clear; virtual;
  732. procedure Delete(Index: Cardinal);
  733. function IndexOf(Item: TCustomChunk): Integer;
  734. procedure Remove(Item: TCustomChunk);
  735. property Count: Cardinal read GetCount;
  736. property Chunks[Index: Integer]: TCustomChunk read GetChunk; default;
  737. end;
  738. TCustomPngCoder = class abstract
  739. protected
  740. FStream : TStream;
  741. FHeader : TChunkPngImageHeader;
  742. FGamma : TChunkPngGamma;
  743. FPalette : TChunkPngPalette;
  744. FTransparency : TCustomPngTransparency;
  745. FRowBuffer : array [0..1] of PByteArray;
  746. FAlphaTable : PByteArray;
  747. FMappingTable : PByteArray;
  748. procedure BuildMappingTables; virtual;
  749. procedure EncodeFilterSub(CurrentRow, PreviousRow, OutputRow: PByteArray; BytesPerRow, PixelByteSize: Integer);
  750. procedure EncodeFilterUp(CurrentRow, PreviousRow, OutputRow: PByteArray; BytesPerRow, PixelByteSize: Integer);
  751. procedure EncodeFilterAverage(CurrentRow, PreviousRow, OutputRow: PByteArray; BytesPerRow, PixelByteSize: Integer);
  752. procedure EncodeFilterPaeth(CurrentRow, PreviousRow, OutputRow: PByteArray; BytesPerRow, PixelByteSize: Integer);
  753. procedure DecodeFilterSub(CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: NativeInt);
  754. procedure DecodeFilterUp(CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: NativeInt);
  755. procedure DecodeFilterAverage(CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: NativeInt);
  756. procedure DecodeFilterPaeth(CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: NativeInt);
  757. procedure EncodeFilterRow(CurrentRow, PreviousRow, OutputRow, TempBuffer: PByteArray; BytesPerRow, PixelByteSize: Integer); virtual; abstract;
  758. procedure DecodeFilterRow(FilterMethod: TAdaptiveFilterMethod; CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: Integer); virtual; abstract;
  759. public
  760. constructor Create(Stream: TStream; Header: TChunkPngImageHeader;
  761. Gamma: TChunkPngGamma = nil; Palette: TChunkPngPalette = nil;
  762. Transparency : TCustomPngTransparency = nil); virtual;
  763. destructor Destroy; override;
  764. end;
  765. TScanLineCallback = function(Bitmap: TObject; Y: Integer): Pointer of object;
  766. TCustomPngDecoder = class abstract(TCustomPngCoder)
  767. protected
  768. procedure EncodeFilterRow(CurrentRow, PreviousRow, OutputRow, TempBuffer: PByteArray; BytesPerRow, PixelByteSize: Integer); override;
  769. procedure DecodeFilterRow(FilterMethod: TAdaptiveFilterMethod; CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: Integer); override;
  770. public
  771. procedure DecodeToScanline(Bitmap: TObject; ScanLineCallback: TScanLineCallback); virtual; abstract;
  772. end;
  773. TCustomPngDecoderClass = class of TCustomPngDecoder;
  774. TCustomPngEncoder = class abstract(TCustomPngCoder)
  775. protected
  776. procedure EncodeFilterRow(CurrentRow, PreviousRow, OutputRow, TempBuffer: PByteArray; BytesPerRow, PixelByteSize: Integer); override;
  777. procedure DecodeFilterRow(FilterMethod: TAdaptiveFilterMethod; CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: Integer); override;
  778. public
  779. procedure EncodeFromScanline(Bitmap: TObject; ScanLineCallback: TScanLineCallback); virtual; abstract;
  780. end;
  781. TCustomPngEncoderClass = class of TCustomPngEncoder;
  782. TCustomPngTranscoder = class abstract(TCustomPngCoder)
  783. protected
  784. procedure EncodeFilterRow(CurrentRow, PreviousRow, OutputRow, TempBuffer: PByteArray; BytesPerRow, PixelByteSize: Integer); override;
  785. procedure DecodeFilterRow(FilterMethod: TAdaptiveFilterMethod; CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: Integer); override;
  786. procedure Transcode; virtual; abstract;
  787. public
  788. constructor Create(Stream: TStream; Header: TChunkPngImageHeader;
  789. Gamma: TChunkPngGamma = nil; Palette: TChunkPngPalette = nil;
  790. Transparency: TCustomPngTransparency = nil); override;
  791. destructor Destroy; override;
  792. end;
  793. TCustomPngTranscoderClass = class of TCustomPngTranscoder;
  794. TPortableNetworkGraphic = class(TInterfacedPersistent, IStreamPersist)
  795. private
  796. FCompressionLevel : Byte;
  797. function GetBitDepth: Byte;
  798. function GetColorType: TColorType;
  799. function GetCompressionMethod: Byte;
  800. function GetFilterMethod: TFilterMethod;
  801. function GetHeight: Integer;
  802. function GetInterlaceMethod: TInterlaceMethod;
  803. function GetPaletteEntry(Index: Integer): TRGB24;
  804. function GetPaletteEntryCount: Integer;
  805. function GetWidth: Integer;
  806. function GetGamma: Single;
  807. function GetModifiedTime: TDateTime;
  808. function GetPixelsPerUnitX: Cardinal;
  809. function GetPixelsPerUnitY: Cardinal;
  810. function GetPixelUnit: Byte;
  811. procedure SetPixelsPerUnitX(const Value: Cardinal);
  812. procedure SetPixelsPerUnitY(const Value: Cardinal);
  813. procedure SetPixelUnit(const Value: Byte);
  814. procedure SetBitDepth(const Value: Byte);
  815. procedure SetChromaChunk(const Value: TChunkPngPrimaryChromaticities);
  816. procedure SetColorType(const Value: TColorType);
  817. procedure SetCompressionMethod(const Value: Byte);
  818. procedure SetCompressionLevel(const Value: Byte);
  819. procedure SetFilterMethods(const Value: TAvailableAdaptiveFilterMethods);
  820. procedure SetFilterMethod(const Value: TFilterMethod);
  821. procedure SetGamma(const Value: Single);
  822. procedure SetModifiedTime(const Value: TDateTime);
  823. procedure SetHeight(const Value: Integer);
  824. procedure SetImageHeader(const Value: TChunkPngImageHeader);
  825. procedure SetInterlaceMethod(const Value: TInterlaceMethod);
  826. procedure SetGammaChunk(const Value: TChunkPngGamma);
  827. procedure SetPaletteChunk(const Value: TChunkPngPalette);
  828. procedure SetTransparencyChunk(const Value: TChunkPngTransparency);
  829. procedure SetPhysicalDimensions(const Value: TChunkPngPhysicalPixelDimensions);
  830. procedure SetSignificantBits(const Value: TChunkPngSignificantBits);
  831. procedure SetTimeChunk(const Value: TChunkPngTime);
  832. procedure SetWidth(const Value: Integer);
  833. function CalculateCRC(Buffer: PByte; Count: Cardinal): Cardinal; overload;
  834. function CalculateCRC(Stream: TStream): Cardinal; overload;
  835. {$IFDEF CheckCRC}
  836. function CheckCRC(Stream: TStream; CRC: Cardinal): Boolean;
  837. {$ENDIF}
  838. procedure ReadImageDataChunk(Stream: TStream; Size: Integer);
  839. procedure ReadUnknownChunk(Stream: TStream; ChunkName: TChunkName; ChunkSize: Integer);
  840. function GetFilterMethods: TAvailableAdaptiveFilterMethods;
  841. procedure SetBackgroundChunk(const Value: TChunkPngBackgroundColor);
  842. protected
  843. FImageHeader : TChunkPngImageHeader;
  844. FPaletteChunk : TChunkPngPalette;
  845. FGammaChunk : TChunkPngGamma;
  846. FTimeChunk : TChunkPngTime;
  847. FSignificantBits : TChunkPngSignificantBits;
  848. FPhysicalDimensions : TChunkPngPhysicalPixelDimensions;
  849. FChromaChunk : TChunkPngPrimaryChromaticities;
  850. FTransparencyChunk : TChunkPngTransparency;
  851. FBackgroundChunk : TChunkPngBackgroundColor;
  852. FDataChunkList : TChunkList;
  853. FAdditionalChunkList : TChunkList;
  854. procedure Clear; virtual;
  855. procedure AssignTo(Dest: TPersistent); override;
  856. procedure CopyImageData(Stream: TStream);
  857. procedure StoreImageData(Stream: TStream);
  858. procedure DecompressImageDataToStream(Stream: TStream);
  859. procedure CompressImageDataFromStream(Stream: TStream);
  860. procedure CompressionLevelChanged; virtual;
  861. procedure AdaptiveFilterMethodsChanged; virtual;
  862. procedure InterlaceMethodChanged; virtual;
  863. property ImageHeader: TChunkPngImageHeader read FImageHeader write SetImageHeader;
  864. property PaletteChunk: TChunkPngPalette read FPaletteChunk write SetPaletteChunk;
  865. property TransparencyChunk: TChunkPngTransparency read FTransparencyChunk write SetTransparencyChunk;
  866. property BackgroundChunk: TChunkPngBackgroundColor read FBackgroundChunk write SetBackgroundChunk;
  867. property GammaChunk: TChunkPngGamma read FGammaChunk write SetGammaChunk;
  868. property TimeChunk: TChunkPngTime read FTimeChunk write SetTimeChunk;
  869. property PhysicalPixelDimensionsChunk: TChunkPngPhysicalPixelDimensions read FPhysicalDimensions write SetPhysicalDimensions;
  870. public
  871. constructor Create; virtual;
  872. destructor Destroy; override;
  873. procedure Assign(Source: TPersistent); override;
  874. procedure LoadFromStream(Stream: TStream); virtual;
  875. procedure SaveToStream(Stream: TStream); virtual;
  876. procedure LoadFromFile(Filename: TFilename); virtual;
  877. procedure SaveToFile(Filename: TFilename); virtual;
  878. class function CanLoad(const FileName: TFileName): Boolean; overload;
  879. class function CanLoad(Stream: TStream): Boolean; overload;
  880. function HasPhysicalPixelDimensionsInformation: Boolean;
  881. function HasGammaInformation: Boolean;
  882. function HasModifiedTimeInformation: Boolean;
  883. procedure RemovePhysicalPixelDimensionsInformation;
  884. procedure RemoveGammaInformation;
  885. procedure RemoveModifiedTimeInformation;
  886. property Width: Integer read GetWidth write SetWidth;
  887. property Height: Integer read GetHeight write SetHeight;
  888. property BitDepth: Byte read GetBitDepth write SetBitDepth;
  889. property ColorType: TColorType read GetColorType write SetColorType;
  890. property CompressionMethod: Byte read GetCompressionMethod write SetCompressionMethod;
  891. property CompressionLevel: Byte read FCompressionLevel write SetCompressionLevel;
  892. property AdaptiveFilterMethods: TAvailableAdaptiveFilterMethods read GetFilterMethods write SetFilterMethods;
  893. property FilterMethod: TFilterMethod read GetFilterMethod write SetFilterMethod;
  894. property InterlaceMethod: TInterlaceMethod read GetInterlaceMethod write SetInterlaceMethod;
  895. property PaletteEntry[Index: Integer]: TRGB24 read GetPaletteEntry;
  896. property PaletteEntryCount: Integer read GetPaletteEntryCount;
  897. property Gamma: Single read GetGamma write SetGamma;
  898. property ModifiedTime: TDateTime read GetModifiedTime write SetModifiedTime;
  899. property PixelsPerUnitX: Cardinal read GetPixelsPerUnitX write SetPixelsPerUnitX;
  900. property PixelsPerUnitY: Cardinal read GetPixelsPerUnitY write SetPixelsPerUnitY;
  901. property PixelUnit: Byte read GetPixelUnit write SetPixelUnit;
  902. property SignificantBitsChunk: TChunkPngSignificantBits read FSignificantBits write SetSignificantBits;
  903. property PrimaryChromaticitiesChunk: TChunkPngPrimaryChromaticities read FChromaChunk write SetChromaChunk;
  904. end;
  905. procedure RegisterPngChunk(ChunkClass: TCustomDefinedChunkWithHeaderClass);
  906. procedure RegisterPngChunks(ChunkClasses: array of TCustomDefinedChunkWithHeaderClass);
  907. function FindPngChunkByChunkName(ChunkName: TChunkName): TCustomDefinedChunkWithHeaderClass;
  908. function ColorTypeToString(Value: TColorType): string;
  909. function InterlaceMethodToString(Value: TInterlaceMethod): string;
  910. implementation
  911. uses
  912. Math,
  913. GR32_LowLevel,
  914. GR32.BigEndian;
  915. resourcestring
  916. RCStrAncillaryUnknownChunk = 'Unknown chunk is marked as ancillary';
  917. RCStrChunkSizeTooSmall = 'Chunk size too small!';
  918. RCStrDataIncomplete = 'Data not complete';
  919. RCStrChunkInvalid = 'Invalid chunk data';
  920. RCStrDirectCompressionMethodSetError = 'Compression Method may not be specified directly yet!';
  921. RCStrDirectFilterMethodSetError = 'Filter Method may not be specified directly yet!';
  922. RCStrDirectGammaSetError = 'Gamma may not be specified directly yet!';
  923. RCStrDirectHeightSetError = 'Height may not be specified directly yet!';
  924. RCStrDirectWidthSetError = 'Width may not be specified directly yet!';
  925. RCStrEmptyChunkList = 'Chunk list is empty';
  926. RCStrHeaderInvalid = 'The provided header is not valid!';
  927. RCStrIncompletePalette = 'Palette is incomplete';
  928. RCStrIndexOutOfBounds = 'Index out of bounds (%d)';
  929. RCStrNewHeaderError = 'New header may not be nil!';
  930. RCStrNotAValidPNGFile = 'Not a valid PNG file';
  931. RCStrNotYetImplemented = 'PNG feature not implemented (%s)';
  932. RCStrChunkNotImplemented = 'Chunk type %s not implemented';
  933. RCStrPaletteLimited = 'Palette is limited to 256 entries';
  934. RCStrSeveralChromaChunks = 'Primary chromaticities chunk defined twice!';
  935. RCStrSeveralGammaChunks = 'Gamma chunk defined twice!';
  936. RCStrSeveralPaletteChunks = 'Palette chunk defined twice!';
  937. RCStrSeveralTransparencyChunks = 'Transparency chunk defined twice!';
  938. RCStrSeveralBackgroundChunks = 'Background chunk defined twice!';
  939. RCStrSeveralPhysicalPixelDimensionChunks = 'Several physical pixel dimenson chunks found';
  940. RCStrSeveralSignificantBitsChunksFound = 'Several significant bits chunks found';
  941. RCStrSeveralTimeChunks = 'Time chunk appears twice!';
  942. RCStrMissingIDATChunk = 'IDAT chunk missing';
  943. RCStrUnknownColorType = 'Unknown color type!';
  944. RCStrUnspecifiedPixelUnit = 'Unspecified unit';
  945. RCStrUnsupportedCompressionMethod = 'Compression method not supported!';
  946. RCStrUnsupportedCompressMethod = 'Unsupported compression method';
  947. RCStrUnsupportedFilter = 'Unsupported Filter';
  948. RCStrUnsupportedFilterMethod = 'Unsupported filter method';
  949. RCStrUnsupportedInterlaceMethod = 'Unsupported interlace method';
  950. RCStrUnsupportedColorType = 'Unsupported color type';
  951. RCStrWrongBitdepth = 'Wrong Bitdepth';
  952. RCStrWrongInterlaceMethod = 'Wrong interlace method';
  953. RCStrWrongPixelPerUnit = 'Pixel per unit may not be zero!';
  954. RCStrWrongTransparencyFormat = 'Wrong transparency format';
  955. RCStrInvalidCompressionLevel = 'Invalid compression level';
  956. RCStrBitDepthTranscodingError = 'Bit depth may not be specified directly yet!';
  957. RCStrColorTypeTranscodingError = 'Color Type may not be specified directly yet!';
  958. RCStrGrayscale = 'Grayscale';
  959. RCStrTrueColor = 'True Color';
  960. RCStrIndexedColor = 'Indexed Color';
  961. RCStrGrayscaleAlpha = 'Transparent Grayscale';
  962. RCStrTrueColorAlpha = 'Transparent True Color';
  963. RCStrInterlacingNone = 'None';
  964. RCStrInterlacingAdam7 = 'Adam7';
  965. {$IFDEF CheckCRC}
  966. RCStrCRCError = 'CRC Error';
  967. {$ENDIF}
  968. type
  969. TCrcTable = array [0..255] of Cardinal;
  970. PCrcTable = ^TCrcTable;
  971. var
  972. GCrcTable : PCrcTable;
  973. GPngChunkClasses: array of TCustomDefinedChunkWithHeaderClass;
  974. const
  975. PNG_SIG: array[0..7] of AnsiChar = #$89'PNG'#$0D#$0A#$1A#$0A;
  976. const
  977. CRowStart : array[0..6] of Integer = (0, 0, 4, 0, 2, 0, 1);
  978. CColumnStart : array[0..6] of Integer = (0, 4, 0, 2, 0, 1, 0);
  979. CRowIncrement : array[0..6] of Integer = (8, 8, 8, 4, 4, 2, 2);
  980. CColumnIncrement : array[0..6] of Integer = (8, 8, 4, 4, 2, 2, 1);
  981. type
  982. TPngNonInterlacedToAdam7Transcoder = class(TCustomPngTranscoder)
  983. protected
  984. procedure Transcode; override;
  985. end;
  986. TPngAdam7ToNonInterlacedTranscoder = class(TCustomPngTranscoder)
  987. protected
  988. procedure Transcode; override;
  989. end;
  990. function IsPngChunkRegistered(ChunkClass: TCustomDefinedChunkWithHeaderClass): Boolean;
  991. var
  992. ChunkClassIndex : Integer;
  993. begin
  994. Result := False;
  995. for ChunkClassIndex := 0 to Length(GPngChunkClasses) - 1 do
  996. if GPngChunkClasses[ChunkClassIndex] = ChunkClass then
  997. begin
  998. Result := True;
  999. Exit;
  1000. end;
  1001. end;
  1002. procedure RegisterPngChunk(ChunkClass: TCustomDefinedChunkWithHeaderClass);
  1003. begin
  1004. Assert(not IsPngChunkRegistered(ChunkClass), 'PNG chunk already registered');
  1005. SetLength(GPngChunkClasses, Length(GPngChunkClasses) + 1);
  1006. GPngChunkClasses[Length(GPngChunkClasses) - 1] := ChunkClass;
  1007. end;
  1008. procedure RegisterPngChunks(ChunkClasses: array of TCustomDefinedChunkWithHeaderClass);
  1009. var
  1010. ChunkClassIndex : Integer;
  1011. begin
  1012. for ChunkClassIndex := 0 to Length(ChunkClasses) - 1 do
  1013. RegisterPngChunk(ChunkClasses[ChunkClassIndex]);
  1014. end;
  1015. function FindPngChunkByChunkName(ChunkName: TChunkName): TCustomDefinedChunkWithHeaderClass;
  1016. var
  1017. ChunkClassIndex : Integer;
  1018. begin
  1019. Result := nil;
  1020. for ChunkClassIndex := 0 to Length(GPngChunkClasses) - 1 do
  1021. if GPngChunkClasses[ChunkClassIndex].GetClassChunkName = ChunkName then
  1022. begin
  1023. Result := GPngChunkClasses[ChunkClassIndex];
  1024. Exit;
  1025. end;
  1026. end;
  1027. { conversion }
  1028. function ColorTypeToString(Value: TColorType): string;
  1029. const
  1030. CColorTypeNames : array [TColorType] of string = (RCStrGrayScale,
  1031. 'undefined', RCStrTrueColor, RCStrIndexedColor, RCStrGrayscaleAlpha,
  1032. 'undefined', RCStrTrueColorAlpha);
  1033. begin
  1034. Result := CColorTypeNames[Value];
  1035. end;
  1036. function InterlaceMethodToString(Value: TInterlaceMethod): string;
  1037. const
  1038. CInterlaceMethodNames : array [TInterlaceMethod] of string = (RCStrInterlacingNone,
  1039. RCStrInterlacingAdam7);
  1040. begin
  1041. Result := CInterlaceMethodNames[Value];
  1042. end;
  1043. { zlib functions }
  1044. procedure ZCompress(Data: Pointer; Size: Integer; const Output: TStream;
  1045. Level: Byte = Z_BEST_COMPRESSION); overload;
  1046. const
  1047. CBufferSize = $8000;
  1048. var
  1049. ZStreamRecord : TZStreamRec;
  1050. ZResult : Integer;
  1051. TempBuffer : Pointer;
  1052. begin
  1053. FillChar(ZStreamRecord, SizeOf(TZStreamRec), 0);
  1054. with ZStreamRecord do
  1055. begin
  1056. next_in := Data;
  1057. avail_in := Size;
  1058. {$IFNDEF FPC}
  1059. {$IFNDEF ZLibEx}
  1060. zalloc := zlibAllocMem;
  1061. zfree := zlibFreeMem;
  1062. {$ENDIF}
  1063. {$ENDIF}
  1064. end;
  1065. {$IFDEF FPC}
  1066. if DeflateInit_(@ZStreamRecord, Level, ZLIB_VERSION, SizeOf(TZStreamRec)) < 0 then
  1067. raise EPngError.Create('Error during compression');
  1068. {$ELSE}
  1069. if DeflateInit_(ZStreamRecord, Level, ZLIB_VERSION, SizeOf(TZStreamRec)) < 0 then
  1070. raise EPngError.Create('Error during compression');
  1071. {$ENDIF}
  1072. GetMem(TempBuffer, CBufferSize);
  1073. try
  1074. while ZStreamRecord.avail_in > 0 do
  1075. begin
  1076. ZStreamRecord.next_out := TempBuffer;
  1077. ZStreamRecord.avail_out := CBufferSize;
  1078. deflate(ZStreamRecord, Z_NO_FLUSH);
  1079. Output.Write(TempBuffer^, CBufferSize - ZStreamRecord.avail_out);
  1080. end;
  1081. repeat
  1082. ZStreamRecord.next_out := TempBuffer;
  1083. ZStreamRecord.avail_out := CBufferSize;
  1084. ZResult := deflate(ZStreamRecord, Z_FINISH);
  1085. Output.Write(TempBuffer^, CBufferSize - ZStreamRecord.avail_out);
  1086. until (ZResult = Z_STREAM_END) and (ZStreamRecord.avail_out > 0);
  1087. finally
  1088. FreeMem(TempBuffer);
  1089. end;
  1090. if deflateEnd(ZStreamRecord) > 0 then
  1091. raise EPngError.Create('Error on stream validation');
  1092. end;
  1093. procedure ZCompress(const Input: TMemoryStream; const Output: TStream;
  1094. Level: Byte = Z_BEST_COMPRESSION); overload;
  1095. begin
  1096. ZCompress(Input.Memory, Input.Size, Output, Level);
  1097. end;
  1098. procedure ZDecompress(Data: Pointer; Size: Integer; const Output: TStream); overload;
  1099. const
  1100. CBufferSize = $8000;
  1101. var
  1102. ZStreamRecord : TZStreamRec;
  1103. ZResult : Integer;
  1104. TempBuffer : Pointer;
  1105. begin
  1106. FillChar(ZStreamRecord, SizeOf(TZStreamRec), 0);
  1107. with ZStreamRecord do
  1108. begin
  1109. next_in := Data;
  1110. avail_in := Size;
  1111. {$IFNDEF FPC}
  1112. {$IFNDEF ZLibEx}
  1113. zalloc := zlibAllocMem;
  1114. zfree := zlibFreeMem;
  1115. {$ENDIF}
  1116. {$ENDIF}
  1117. end;
  1118. {$IFDEF FPC}
  1119. if inflateInit_(@ZStreamRecord, ZLIB_VERSION, SizeOf(TZStreamRec)) < 0 then
  1120. raise EPngError.Create('Error during decompression');
  1121. {$ELSE}
  1122. if inflateInit_(ZStreamRecord, ZLIB_VERSION, SizeOf(TZStreamRec)) < 0 then
  1123. raise EPngError.Create('Error during decompression');
  1124. {$ENDIF}
  1125. try
  1126. GetMem(TempBuffer, CBufferSize);
  1127. try
  1128. ZResult := Z_OK;
  1129. while (ZStreamRecord.avail_in > 0) and (ZResult <> Z_STREAM_END) do
  1130. begin
  1131. ZStreamRecord.next_out := TempBuffer;
  1132. ZStreamRecord.avail_out := CBufferSize;
  1133. ZResult := inflate(ZStreamRecord, Z_NO_FLUSH);
  1134. if ZResult < 0 then
  1135. raise EPngError.CreateFmt('Error during decompression: %d', [ZResult]);
  1136. Output.Write(TempBuffer^, CBufferSize - ZStreamRecord.avail_out);
  1137. end;
  1138. finally
  1139. FreeMem(TempBuffer);
  1140. end;
  1141. finally
  1142. if inflateEnd(ZStreamRecord) > 0 then
  1143. raise EPngError.Create('Error on stream validation');
  1144. end;
  1145. end;
  1146. procedure ZDecompress(const Input: TMemoryStream; const Output: TStream); overload;
  1147. begin
  1148. ZDecompress(Input.Memory, Input.Size, Output);
  1149. end;
  1150. { TCustomDefinedChunk }
  1151. function TCustomDefinedChunk.GetChunkName: TChunkName;
  1152. begin
  1153. Result := GetClassChunkName;
  1154. end;
  1155. function TCustomDefinedChunk.GetChunkNameAsString: AnsiString;
  1156. begin
  1157. Result := AnsiString(GetClassChunkName);
  1158. end;
  1159. { TChunkPngUnknown }
  1160. constructor TChunkPngUnknown.Create(ChunkName: TChunkName);
  1161. begin
  1162. FChunkName := ChunkName;
  1163. FDataStream := TMemoryStream.Create;
  1164. end;
  1165. destructor TChunkPngUnknown.Destroy;
  1166. begin
  1167. FDataStream.Free;
  1168. inherited;
  1169. end;
  1170. function TChunkPngUnknown.CalculateChecksum: Integer;
  1171. type
  1172. PByteArray = ^TByteArray;
  1173. TByteArray = array[0..MaxInt-1] of Byte;
  1174. var
  1175. i: integer;
  1176. begin
  1177. Result := 0;
  1178. for i := 0 to FDataStream.Size-1 do
  1179. Inc(Result, PByteArray(FDataStream.Memory)[i]);
  1180. end;
  1181. procedure TChunkPngUnknown.AssignTo(Dest: TPersistent);
  1182. begin
  1183. if Dest is TChunkPngUnknown then
  1184. begin
  1185. TChunkPngUnknown(Dest).FDataStream.CopyFrom(FDataStream, FDataStream.Size);
  1186. TChunkPngUnknown(Dest).FChunkName := FChunkName;
  1187. end else
  1188. inherited AssignTo(Dest);
  1189. end;
  1190. function TChunkPngUnknown.GetData(Index: Integer): Byte;
  1191. type
  1192. PByteArray = ^TByteArray;
  1193. TByteArray = array[0..MaxInt-1] of Byte;
  1194. begin
  1195. if (Index < 0) or (Index >= FDataStream.Size) then
  1196. raise EPngError.CreateFmt(RCStrIndexOutOfBounds, [index]);
  1197. Result := PByteArray(FDataStream.Memory)[Index];
  1198. end;
  1199. function TChunkPngUnknown.GetChunkSize: Cardinal;
  1200. begin
  1201. Result := FDataStream.Size;
  1202. end;
  1203. function TChunkPngUnknown.GetChunkNameAsString: AnsiString;
  1204. begin
  1205. Result := FChunkName;
  1206. end;
  1207. function TChunkPngUnknown.GetChunkName: TChunkName;
  1208. begin
  1209. Result := FChunkName;
  1210. end;
  1211. procedure TChunkPngUnknown.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  1212. begin
  1213. Assert(Stream.Position+ChunkSize <= Stream.Size);
  1214. FDataStream.Clear;
  1215. FDataStream.Position := 0;
  1216. if ChunkSize > 0 then
  1217. FDataStream.CopyFrom(Stream, ChunkSize);
  1218. end;
  1219. procedure TChunkPngUnknown.WriteToStream(Stream: TStream);
  1220. begin
  1221. FDataStream.Position := 0;
  1222. Stream.CopyFrom(FDataStream, 0);
  1223. end;
  1224. procedure TChunkPngUnknown.SetData(Index: Integer; const Value: Byte);
  1225. type
  1226. PByteArray = ^TByteArray;
  1227. TByteArray = array[0..MaxInt-1] of Byte;
  1228. begin
  1229. if (Index < 0) or (Index >= FDataStream.Size) then
  1230. raise EPngError.CreateFmt(RCStrIndexOutOfBounds, [Index]);
  1231. PByteArray(FDataStream.Memory)[Index] := Value;
  1232. end;
  1233. { TChunkPngImageHeader }
  1234. constructor TChunkPngImageHeader.Create;
  1235. begin
  1236. inherited;
  1237. FAdaptiveFilterMethods := [aafmSub, aafmUp, aafmAverage, aafmPaeth];
  1238. ResetToDefault;
  1239. end;
  1240. procedure TChunkPngImageHeader.AssignTo(Dest: TPersistent);
  1241. begin
  1242. if Dest is TChunkPngImageHeader then
  1243. with TChunkPngImageHeader(Dest) do
  1244. begin
  1245. FWidth := Self.FWidth;
  1246. FHeight := Self.FHeight;
  1247. FBitDepth := Self.FBitDepth;
  1248. FColorType := Self.FColorType;
  1249. FCompressionMethod := Self.FCompressionMethod;
  1250. FFilterMethod := Self.FFilterMethod;
  1251. FInterlaceMethod := Self.FInterlaceMethod;
  1252. FAdaptiveFilterMethods := Self.FAdaptiveFilterMethods;
  1253. end
  1254. else
  1255. inherited;
  1256. end;
  1257. function TChunkPngImageHeader.GetBytesPerRow: Integer;
  1258. begin
  1259. case FColorType of
  1260. ctGrayscale,
  1261. ctIndexedColor:
  1262. Result := ((FWidth * FBitDepth + $7) and not $7) shr 3;
  1263. ctGrayscaleAlpha:
  1264. Result := 2 * (FBitDepth shr 3) * FWidth;
  1265. ctTrueColor:
  1266. Result := 3 * (FBitDepth shr 3) * FWidth;
  1267. ctTrueColorAlpha:
  1268. Result := 4 * (FBitDepth shr 3) * FWidth;
  1269. else
  1270. raise EPngError.Create(RCStrUnknownColorType);
  1271. end;
  1272. end;
  1273. class function TChunkPngImageHeader.GetClassChunkName: TChunkName;
  1274. begin
  1275. Result := 'IHDR';
  1276. end;
  1277. function TChunkPngImageHeader.GetChunkSize: Cardinal;
  1278. begin
  1279. Result := 13;
  1280. end;
  1281. procedure TChunkPngImageHeader.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  1282. begin
  1283. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  1284. raise EPngError.Create(RCStrChunkSizeTooSmall);
  1285. // read width
  1286. FWidth := BigEndian.ReadCardinal(Stream);
  1287. // read height
  1288. FHeight := BigEndian.ReadCardinal(Stream);
  1289. // read bit depth
  1290. Stream.Read(FBitDepth, 1);
  1291. // read Color type
  1292. Stream.Read(FColorType, 1);
  1293. // check consistency between Color type and bit depth
  1294. case FColorType of
  1295. ctGrayscale:
  1296. if not (FBitDepth in [1, 2, 4, 8, 16]) then
  1297. raise EPngError.Create(RCStrWrongBitdepth);
  1298. ctTrueColor,
  1299. ctGrayscaleAlpha,
  1300. ctTrueColorAlpha:
  1301. if not (FBitDepth in [8, 16]) then
  1302. raise EPngError.Create(RCStrWrongBitdepth);
  1303. ctIndexedColor:
  1304. if not (FBitDepth in [1, 2, 4, 8]) then
  1305. raise EPngError.Create(RCStrWrongBitdepth);
  1306. else
  1307. raise EPngError.Create(RCStrUnsupportedColorType);
  1308. end;
  1309. // read compression method
  1310. Stream.Read(FCompressionMethod, 1);
  1311. // check for compression method
  1312. if FCompressionMethod <> 0 then
  1313. raise EPngError.Create(RCStrUnsupportedCompressMethod);
  1314. // read filter method
  1315. Stream.Read(FFilterMethod, 1);
  1316. // check for filter method
  1317. if FFilterMethod <> fmAdaptiveFilter then
  1318. raise EPngError.Create(RCStrUnsupportedFilterMethod);
  1319. // read interlace method
  1320. Stream.Read(FInterlaceMethod, 1);
  1321. // check for interlace method
  1322. if not (FInterlaceMethod in [imNone, imAdam7]) then
  1323. raise EPngError.Create(RCStrUnsupportedInterlaceMethod);
  1324. end;
  1325. procedure TChunkPngImageHeader.WriteToStream(Stream: TStream);
  1326. begin
  1327. // write width
  1328. BigEndian.WriteCardinal(Stream, FWidth);
  1329. // write height
  1330. BigEndian.WriteCardinal(Stream, FHeight);
  1331. // write bit depth
  1332. Stream.Write(FBitDepth, 1);
  1333. // write Color type
  1334. Stream.Write(FColorType, 1);
  1335. // write compression method
  1336. Stream.Write(FCompressionMethod, 1);
  1337. // write filter method
  1338. Stream.Write(FFilterMethod, 1);
  1339. // write interlace method
  1340. Stream.Write(FInterlaceMethod, 1);
  1341. end;
  1342. function TChunkPngImageHeader.GetPixelByteSize: Integer;
  1343. begin
  1344. case ColorType of
  1345. ctGrayscale:
  1346. if FBitDepth = 16 then
  1347. Result := 2
  1348. else
  1349. Result := 1;
  1350. ctTrueColor:
  1351. Result := 3 * FBitDepth div 8;
  1352. ctIndexedColor:
  1353. Result := 1;
  1354. ctGrayscaleAlpha:
  1355. Result := 2 * FBitDepth div 8;
  1356. ctTrueColorAlpha:
  1357. Result := 4 * FBitDepth div 8;
  1358. else
  1359. Result := 0;
  1360. end;
  1361. end;
  1362. function TChunkPngImageHeader.GetHasPalette: Boolean;
  1363. begin
  1364. Result := FColorType in [ctIndexedColor];
  1365. end;
  1366. procedure TChunkPngImageHeader.ResetToDefault;
  1367. begin
  1368. FWidth := 0;
  1369. FHeight := 0;
  1370. FBitDepth := 8;
  1371. FColorType := ctTrueColor;
  1372. FCompressionMethod := 0;
  1373. FFilterMethod := fmAdaptiveFilter;
  1374. FInterlaceMethod := imNone;
  1375. end;
  1376. procedure TChunkPngImageHeader.SetAdaptiveFilterMethods(
  1377. const Value: TAvailableAdaptiveFilterMethods);
  1378. begin
  1379. FAdaptiveFilterMethods := Value;
  1380. end;
  1381. procedure TChunkPngImageHeader.SetCompressionMethod(const Value: Byte);
  1382. begin
  1383. // check for compression method
  1384. if Value <> 0 then
  1385. raise EPngError.Create(RCStrUnsupportedCompressMethod);
  1386. end;
  1387. procedure TChunkPngImageHeader.SetFilterMethod(const Value: TFilterMethod);
  1388. begin
  1389. // check for filter method
  1390. if Value <> fmAdaptiveFilter then
  1391. raise EPngError.Create(RCStrUnsupportedFilterMethod);
  1392. end;
  1393. { TCustomDefinedChunkWithHeader }
  1394. procedure TCustomDefinedChunkWithHeader.AssignTo(Dest: TPersistent);
  1395. begin
  1396. if Dest is TCustomDefinedChunkWithHeader then
  1397. with TCustomDefinedChunkWithHeader(Dest) do
  1398. begin
  1399. FHeader.Assign(Self.FHeader);
  1400. end
  1401. else
  1402. inherited;
  1403. end;
  1404. constructor TCustomDefinedChunkWithHeader.Create(Header: TChunkPngImageHeader);
  1405. begin
  1406. if not (Header is TChunkPngImageHeader) then
  1407. raise EPngError.Create(RCStrHeaderInvalid);
  1408. FHeader := Header;
  1409. inherited Create;
  1410. end;
  1411. procedure TCustomDefinedChunkWithHeader.HeaderChanged;
  1412. begin
  1413. // purely virtual, do nothing by default
  1414. end;
  1415. { TChunkPngPalette }
  1416. procedure TChunkPngPalette.AssignTo(Dest: TPersistent);
  1417. begin
  1418. if Dest is TChunkPngPalette then
  1419. with TChunkPngPalette(Dest) do
  1420. begin
  1421. SetLength(FPaletteEntries, Length(Self.FPaletteEntries));
  1422. Move(Self.FPaletteEntries[0], FPaletteEntries[0], Length(Self.FPaletteEntries) * SizeOf(TRGB24));
  1423. end
  1424. else
  1425. inherited;
  1426. end;
  1427. class function TChunkPngPalette.GetClassChunkName: TChunkName;
  1428. begin
  1429. Result := 'PLTE';
  1430. end;
  1431. function TChunkPngPalette.GetPaletteEntry(Index: Cardinal): TRGB24;
  1432. begin
  1433. if (Index < Count) then
  1434. Result := FPaletteEntries[Index]
  1435. else
  1436. raise EPngError.Create(RCStrIndexOutOfBounds);
  1437. end;
  1438. procedure TChunkPngPalette.SetPaletteEntry(Index: Cardinal; const Value: TRGB24);
  1439. begin
  1440. if (Index < Count) then
  1441. FPaletteEntries[Index] := Value
  1442. else
  1443. raise EPngError.Create(RCStrIndexOutOfBounds);
  1444. end;
  1445. function TChunkPngPalette.GetCount: Cardinal;
  1446. begin
  1447. Result := Length(FPaletteEntries);
  1448. end;
  1449. function TChunkPngPalette.GetChunkSize: Cardinal;
  1450. begin
  1451. Result := Length(FPaletteEntries) * SizeOf(TRGB24);
  1452. end;
  1453. procedure TChunkPngPalette.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  1454. begin
  1455. if (ChunkSize mod SizeOf(TRGB24)) <> 0 then
  1456. raise EPngError.Create(RCStrIncompletePalette);
  1457. SetLength(FPaletteEntries, ChunkSize div SizeOf(TRGB24));
  1458. Stream.Read(FPaletteEntries[0], Length(FPaletteEntries) * SizeOf(TRGB24));
  1459. end;
  1460. procedure TChunkPngPalette.WriteToStream(Stream: TStream);
  1461. begin
  1462. Stream.Write(FPaletteEntries[0], ChunkSize);
  1463. end;
  1464. procedure TChunkPngPalette.PaletteEntriesChanged;
  1465. begin
  1466. // nothing todo here yet
  1467. end;
  1468. procedure TChunkPngPalette.SetCount(const Value: Cardinal);
  1469. begin
  1470. if Value > 256 then
  1471. raise EPngError.Create(RCStrPaletteLimited);
  1472. if Value <> Cardinal(Length(FPaletteEntries)) then
  1473. begin
  1474. SetLength(FPaletteEntries, Value);
  1475. PaletteEntriesChanged;
  1476. end;
  1477. end;
  1478. { TChunkPngTransparency }
  1479. procedure TChunkPngTransparency.AssignTo(Dest: TPersistent);
  1480. begin
  1481. if Dest is TChunkPngTransparency then
  1482. with TChunkPngTransparency(Dest) do
  1483. begin
  1484. FTransparency.Assign(Self.FTransparency);
  1485. end
  1486. else
  1487. inherited;
  1488. end;
  1489. constructor TChunkPngTransparency.Create(Header: TChunkPngImageHeader);
  1490. begin
  1491. inherited;
  1492. case Header.ColorType of
  1493. ctGrayscale:
  1494. FTransparency := TPngTransparencyFormat0.Create;
  1495. ctTrueColor:
  1496. FTransparency := TPngTransparencyFormat2.Create;
  1497. ctIndexedColor:
  1498. FTransparency := TPngTransparencyFormat3.Create;
  1499. end;
  1500. end;
  1501. destructor TChunkPngTransparency.Destroy;
  1502. begin
  1503. FTransparency.Free;
  1504. inherited;
  1505. end;
  1506. class function TChunkPngTransparency.GetClassChunkName: TChunkName;
  1507. begin
  1508. Result := 'tRNS';
  1509. end;
  1510. procedure TChunkPngTransparency.HeaderChanged;
  1511. var
  1512. OldTransparency : TCustomPngTransparency;
  1513. begin
  1514. inherited;
  1515. // store old transparency object
  1516. OldTransparency := FTransparency;
  1517. // change transparency object class
  1518. case FHeader.ColorType of
  1519. ctGrayscale:
  1520. if not (FTransparency is TPngTransparencyFormat0) then
  1521. FTransparency := TPngTransparencyFormat0.Create;
  1522. ctTrueColor:
  1523. if not (FTransparency is TPngTransparencyFormat2) then
  1524. FTransparency := TPngTransparencyFormat2.Create;
  1525. ctIndexedColor:
  1526. if not (FTransparency is TPngTransparencyFormat3) then
  1527. FTransparency := TPngTransparencyFormat3.Create;
  1528. else
  1529. FTransparency := nil;
  1530. end;
  1531. if (OldTransparency <> nil) and (OldTransparency <> FTransparency) then
  1532. begin
  1533. if (FTransparency <> nil) then
  1534. FTransparency.Assign(OldTransparency);
  1535. OldTransparency.Free;
  1536. end;
  1537. end;
  1538. function TChunkPngTransparency.GetChunkSize: Cardinal;
  1539. begin
  1540. if (FTransparency <> nil) then
  1541. Result := FTransparency.ChunkSize
  1542. else
  1543. Result := 0;
  1544. end;
  1545. procedure TChunkPngTransparency.ReadFromStream(Stream: TStream;
  1546. ChunkSize: Cardinal);
  1547. begin
  1548. if (FTransparency <> nil) then
  1549. FTransparency.ReadFromStream(Stream);
  1550. end;
  1551. procedure TChunkPngTransparency.WriteToStream(Stream: TStream);
  1552. begin
  1553. // check consistency
  1554. case FHeader.ColorType of
  1555. ctGrayscale:
  1556. if not (FTransparency is TPngTransparencyFormat0) then
  1557. raise EPngError.Create(RCStrWrongTransparencyFormat);
  1558. ctTrueColor:
  1559. if not (FTransparency is TPngTransparencyFormat2) then
  1560. raise EPngError.Create(RCStrWrongTransparencyFormat);
  1561. ctIndexedColor:
  1562. if not (FTransparency is TPngTransparencyFormat3) then
  1563. raise EPngError.Create(RCStrWrongTransparencyFormat);
  1564. end;
  1565. if (FTransparency <> nil) then
  1566. FTransparency.WriteToStream(Stream);
  1567. end;
  1568. { TPngTransparencyFormat0 }
  1569. procedure TPngTransparencyFormat0.AssignTo(Dest: TPersistent);
  1570. begin
  1571. if Dest is TPngTransparencyFormat0 then
  1572. with TPngTransparencyFormat0(Dest) do
  1573. begin
  1574. FGraySampleValue := Self.FGraySampleValue;
  1575. end
  1576. else
  1577. inherited;
  1578. end;
  1579. function TPngTransparencyFormat0.GetChunkSize: Cardinal;
  1580. begin
  1581. Result := 2;
  1582. end;
  1583. procedure TPngTransparencyFormat0.ReadFromStream(Stream: TStream);
  1584. begin
  1585. inherited;
  1586. FGraySampleValue := BigEndian.ReadWord(Stream);
  1587. end;
  1588. procedure TPngTransparencyFormat0.WriteToStream(Stream: TStream);
  1589. begin
  1590. inherited;
  1591. BigEndian.WriteWord(Stream, FGraySampleValue);
  1592. end;
  1593. { TPngTransparencyFormat2 }
  1594. procedure TPngTransparencyFormat2.AssignTo(Dest: TPersistent);
  1595. begin
  1596. if Dest is TPngTransparencyFormat2 then
  1597. with TPngTransparencyFormat2(Dest) do
  1598. begin
  1599. FRedSampleValue := Self.FRedSampleValue;
  1600. FBlueSampleValue := Self.FBlueSampleValue;
  1601. FGreenSampleValue := Self.FGreenSampleValue;
  1602. end
  1603. else
  1604. inherited;
  1605. end;
  1606. function TPngTransparencyFormat2.GetChunkSize: Cardinal;
  1607. begin
  1608. Result := 6;
  1609. end;
  1610. procedure TPngTransparencyFormat2.ReadFromStream(Stream: TStream);
  1611. begin
  1612. inherited;
  1613. FRedSampleValue := BigEndian.ReadWord(Stream);
  1614. FBlueSampleValue := BigEndian.ReadWord(Stream);
  1615. FGreenSampleValue := BigEndian.ReadWord(Stream);
  1616. end;
  1617. procedure TPngTransparencyFormat2.WriteToStream(Stream: TStream);
  1618. begin
  1619. inherited;
  1620. BigEndian.WriteWord(Stream, FRedSampleValue);
  1621. BigEndian.WriteWord(Stream, FBlueSampleValue);
  1622. BigEndian.WriteWord(Stream, FGreenSampleValue);
  1623. end;
  1624. { TPngTransparencyFormat3 }
  1625. procedure TPngTransparencyFormat3.AssignTo(Dest: TPersistent);
  1626. begin
  1627. if Dest is TPngTransparencyFormat3 then
  1628. with TPngTransparencyFormat3(Dest) do
  1629. begin
  1630. SetLength(FTransparency, Length(Self.FTransparency));
  1631. Move(Self.FTransparency[0], FTransparency, Length(FTransparency));
  1632. end
  1633. else
  1634. inherited;
  1635. end;
  1636. function TPngTransparencyFormat3.GetChunkSize: Cardinal;
  1637. begin
  1638. Result := Count;
  1639. end;
  1640. function TPngTransparencyFormat3.GetCount: Cardinal;
  1641. begin
  1642. Result := Length(FTransparency);
  1643. end;
  1644. function TPngTransparencyFormat3.GetTransparency(Index: Cardinal): Byte;
  1645. begin
  1646. if Index < Count then
  1647. Result := FTransparency[Index]
  1648. else
  1649. raise EPngError.Create(RCStrIndexOutOfBounds);
  1650. end;
  1651. procedure TPngTransparencyFormat3.ReadFromStream(Stream: TStream);
  1652. begin
  1653. inherited;
  1654. SetLength(FTransparency, Stream.Size - Stream.Position);
  1655. Stream.Read(FTransparency[0], Length(FTransparency));
  1656. end;
  1657. procedure TPngTransparencyFormat3.WriteToStream(Stream: TStream);
  1658. begin
  1659. inherited;
  1660. Stream.Write(FTransparency[0], Length(FTransparency));
  1661. end;
  1662. { TChunkPngPhysicalPixelDimensions }
  1663. procedure TChunkPngPhysicalPixelDimensions.AssignTo(Dest: TPersistent);
  1664. begin
  1665. if Dest is TChunkPngPhysicalPixelDimensions then
  1666. with TChunkPngPhysicalPixelDimensions(Dest) do
  1667. begin
  1668. FPixelsPerUnitX := Self.FPixelsPerUnitX;
  1669. FPixelsPerUnitY := Self.FPixelsPerUnitY;
  1670. FUnit := Self.FUnit;
  1671. end
  1672. else
  1673. inherited;
  1674. end;
  1675. class function TChunkPngPhysicalPixelDimensions.GetClassChunkName: TChunkName;
  1676. begin
  1677. Result := 'pHYs';
  1678. end;
  1679. function TChunkPngPhysicalPixelDimensions.GetChunkSize: Cardinal;
  1680. begin
  1681. Result := 9;
  1682. end;
  1683. procedure TChunkPngPhysicalPixelDimensions.ReadFromStream(Stream: TStream;
  1684. ChunkSize: Cardinal);
  1685. begin
  1686. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  1687. raise EPngError.Create(RCStrChunkSizeTooSmall);
  1688. // read pixels per unit, X axis
  1689. FPixelsPerUnitX := BigEndian.ReadCardinal(Stream);
  1690. // read pixels per unit, Y axis
  1691. FPixelsPerUnitY := BigEndian.ReadCardinal(Stream);
  1692. // read unit
  1693. Stream.Read(FUnit, 1);
  1694. end;
  1695. procedure TChunkPngPhysicalPixelDimensions.WriteToStream(Stream: TStream);
  1696. begin
  1697. // write pixels per unit, X axis
  1698. BigEndian.WriteCardinal(Stream, FPixelsPerUnitX);
  1699. // write pixels per unit, Y axis
  1700. BigEndian.WriteCardinal(Stream, FPixelsPerUnitY);
  1701. // write unit
  1702. Stream.Write(FUnit, 1);
  1703. end;
  1704. { TChunkPngPhysicalScale }
  1705. procedure TChunkPngPhysicalScale.AssignTo(Dest: TPersistent);
  1706. begin
  1707. if Dest is TChunkPngPhysicalScale then
  1708. with TChunkPngPhysicalScale(Dest) do
  1709. begin
  1710. FUnitSpecifier := Self.FUnitSpecifier;
  1711. FUnitsPerPixelX := Self.FUnitsPerPixelX;
  1712. FUnitsPerPixelY := Self.FUnitsPerPixelY;
  1713. end
  1714. else
  1715. inherited;
  1716. end;
  1717. class function TChunkPngPhysicalScale.GetClassChunkName: TChunkName;
  1718. begin
  1719. Result := 'sCAL';
  1720. end;
  1721. function TChunkPngPhysicalScale.GetChunkSize: Cardinal;
  1722. begin
  1723. Result := 4;
  1724. end;
  1725. procedure TChunkPngPhysicalScale.ReadFromStream(Stream: TStream;
  1726. ChunkSize: Cardinal);
  1727. begin
  1728. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  1729. raise EPngError.Create(RCStrChunkSizeTooSmall);
  1730. // read unit specifier
  1731. Stream.Read(FUnitSpecifier, 1);
  1732. // yet todo, see http://www.libpng.org/pub/png/book/chapter11.html#png.ch11.div.9
  1733. end;
  1734. procedure TChunkPngPhysicalScale.WriteToStream(Stream: TStream);
  1735. begin
  1736. raise EPngError.CreateFmt(RCStrChunkNotImplemented, [ChunkNameAsString]);
  1737. // yet todo, see http://www.libpng.org/pub/png/book/chapter11.html#png.ch11.div.9
  1738. end;
  1739. { TChunkPngImageOffset }
  1740. procedure TChunkPngImageOffset.AssignTo(Dest: TPersistent);
  1741. begin
  1742. if Dest is TChunkPngImageOffset then
  1743. with TChunkPngImageOffset(Dest) do
  1744. begin
  1745. FImagePositionX := Self.FImagePositionX;
  1746. FImagePositionY := Self.FImagePositionY;
  1747. FUnitSpecifier := Self.FUnitSpecifier;
  1748. end
  1749. else
  1750. inherited;
  1751. end;
  1752. class function TChunkPngImageOffset.GetClassChunkName: TChunkName;
  1753. begin
  1754. Result := 'oFFs';
  1755. end;
  1756. function TChunkPngImageOffset.GetChunkSize: Cardinal;
  1757. begin
  1758. Result := 9;
  1759. end;
  1760. procedure TChunkPngImageOffset.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  1761. begin
  1762. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  1763. raise EPngError.Create(RCStrChunkSizeTooSmall);
  1764. // read image positions
  1765. FImagePositionX := BigEndian.ReadCardinal(Stream);
  1766. FImagePositionY := BigEndian.ReadCardinal(Stream);
  1767. // read unit specifier
  1768. Stream.Read(FUnitSpecifier, 1);
  1769. end;
  1770. procedure TChunkPngImageOffset.WriteToStream(Stream: TStream);
  1771. begin
  1772. // write image positions
  1773. BigEndian.WriteCardinal(Stream, FImagePositionX);
  1774. BigEndian.WriteCardinal(Stream, FImagePositionY);
  1775. // write unit specifier
  1776. Stream.Write(FUnitSpecifier, 1);
  1777. end;
  1778. { TChunkPngPixelCalibrator }
  1779. procedure TChunkPngPixelCalibrator.AssignTo(Dest: TPersistent);
  1780. begin
  1781. if Dest is TChunkPngPixelCalibrator then
  1782. with TChunkPngPixelCalibrator(Dest) do
  1783. begin
  1784. FCalibratorName := Self.FCalibratorName;
  1785. FOriginalZeroes[0] := Self.FOriginalZeroes[0];
  1786. FOriginalZeroes[1] := Self.FOriginalZeroes[1];
  1787. FEquationType := Self.FEquationType;
  1788. FNumberOfParams := Self.FNumberOfParams;
  1789. FUnitName := Self.FUnitName;
  1790. end
  1791. else
  1792. inherited;
  1793. end;
  1794. class function TChunkPngPixelCalibrator.GetClassChunkName: TChunkName;
  1795. begin
  1796. Result := 'pCAL';
  1797. end;
  1798. function TChunkPngPixelCalibrator.GetChunkSize: Cardinal;
  1799. begin
  1800. Result := 9;
  1801. end;
  1802. procedure TChunkPngPixelCalibrator.ReadFromStream(Stream: TStream;
  1803. ChunkSize: Cardinal);
  1804. var
  1805. Index : Integer;
  1806. ParamIndex : Integer;
  1807. begin
  1808. // read keyword
  1809. Index := 1;
  1810. SetLength(FCalibratorName, 80);
  1811. while (Stream.Position < Stream.Size) do
  1812. begin
  1813. Stream.Read(FCalibratorName[Index], SizeOf(Byte));
  1814. if FCalibratorName[Index] = #0 then
  1815. begin
  1816. SetLength(FCalibratorName, Index - 1);
  1817. Break;
  1818. end;
  1819. Inc(Index);
  1820. end;
  1821. // read original zeros
  1822. FOriginalZeroes[0] := BigEndian.ReadCardinal(Stream);
  1823. FOriginalZeroes[1] := BigEndian.ReadCardinal(Stream);
  1824. // read equation type
  1825. Stream.Read(FEquationType, 1);
  1826. // read number of parameters
  1827. Stream.Read(FNumberOfParams, 1);
  1828. // read keyword
  1829. Index := 1;
  1830. SetLength(FUnitName, 80);
  1831. while (Stream.Position < Stream.Size) do
  1832. begin
  1833. Stream.Read(FUnitName[Index], SizeOf(Byte));
  1834. if FUnitName[Index] = #0 then
  1835. begin
  1836. SetLength(FUnitName, Index - 1);
  1837. Break;
  1838. end;
  1839. Inc(Index);
  1840. end;
  1841. for ParamIndex := 0 to FNumberOfParams - 2 do
  1842. begin
  1843. // yet todo
  1844. end;
  1845. end;
  1846. procedure TChunkPngPixelCalibrator.WriteToStream(Stream: TStream);
  1847. begin
  1848. inherited;
  1849. end;
  1850. { TCustomChunkPngText }
  1851. procedure TCustomChunkPngText.AssignTo(Dest: TPersistent);
  1852. begin
  1853. if Dest is TCustomChunkPngText then
  1854. with TCustomChunkPngText(Dest) do
  1855. begin
  1856. FKeyword := Self.FKeyword;
  1857. FText := Self.FText;
  1858. end
  1859. else inherited;
  1860. end;
  1861. procedure TCustomChunkPngText.SetKeyword(const Value: AnsiString);
  1862. begin
  1863. if FKeyword <> Value then
  1864. begin
  1865. FKeyword := Value;
  1866. KeywordChanged;
  1867. end;
  1868. end;
  1869. procedure TCustomChunkPngText.SetText(const Value: AnsiString);
  1870. begin
  1871. if FText <> Value then
  1872. begin
  1873. FText := Value;
  1874. TextChanged;
  1875. end;
  1876. end;
  1877. procedure TCustomChunkPngText.KeywordChanged;
  1878. begin
  1879. // yet empty
  1880. end;
  1881. procedure TCustomChunkPngText.TextChanged;
  1882. begin
  1883. // yet empty
  1884. end;
  1885. { TChunkPngText }
  1886. class function TChunkPngText.GetClassChunkName: TChunkName;
  1887. begin
  1888. Result := 'tEXt';
  1889. end;
  1890. function TChunkPngText.GetChunkSize: Cardinal;
  1891. begin
  1892. Result := Length(FKeyword) + Length(FText) + 1;
  1893. end;
  1894. procedure TChunkPngText.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  1895. var
  1896. Index : Integer;
  1897. begin
  1898. // read keyword
  1899. Index := 1;
  1900. SetLength(FKeyword, 80);
  1901. while (Stream.Position < Stream.Size) do
  1902. begin
  1903. Stream.Read(FKeyword[Index], SizeOf(Byte));
  1904. if FKeyword[Index] = #0 then
  1905. begin
  1906. SetLength(FKeyword, Index - 1);
  1907. Break;
  1908. end;
  1909. Inc(Index);
  1910. if (Index > High(FKeyword)) then
  1911. raise EPngError.Create(RCStrChunkInvalid);
  1912. end;
  1913. // read text
  1914. SetLength(FText, Stream.Size - Stream.Position);
  1915. if (Stream.Position < Stream.Size) then
  1916. Stream.Read(FText[1], SizeOf(Byte)*(Stream.Size-Stream.Position));
  1917. end;
  1918. procedure TChunkPngText.WriteToStream(Stream: TStream);
  1919. var
  1920. Temp : Byte;
  1921. begin
  1922. // write keyword
  1923. Stream.Write(FKeyword[1], Length(FKeyword));
  1924. // write separator
  1925. Temp := 0;
  1926. Stream.Write(Temp, 1);
  1927. // write text
  1928. if (Length(FText) > 0) then
  1929. Stream.Write(FText[1], Length(FText));
  1930. end;
  1931. { TChunkPngCompressedText }
  1932. procedure TChunkPngCompressedText.AssignTo(Dest: TPersistent);
  1933. begin
  1934. if Dest is TChunkPngCompressedText then
  1935. with TChunkPngCompressedText(Dest) do
  1936. begin
  1937. FCompressionMethod := Self.FCompressionMethod;
  1938. end
  1939. else
  1940. inherited;
  1941. end;
  1942. class function TChunkPngCompressedText.GetClassChunkName: TChunkName;
  1943. begin
  1944. Result := 'zTXt';
  1945. end;
  1946. function TChunkPngCompressedText.GetChunkSize: Cardinal;
  1947. var
  1948. OutputStream: TMemoryStream;
  1949. begin
  1950. // calculate chunk size
  1951. Result := Length(FKeyword) + 1 + 1; // +1 = separator, +1 = compression method
  1952. if (Length(FText) > 0) then
  1953. begin
  1954. OutputStream := TMemoryStream.Create;
  1955. try
  1956. // compress text
  1957. ZCompress(@FText[1], Length(FText), OutputStream);
  1958. Inc(Result, OutputStream.Size);
  1959. finally
  1960. OutputStream.Free;
  1961. end;
  1962. end;
  1963. end;
  1964. procedure TChunkPngCompressedText.ReadFromStream(Stream: TStream;
  1965. ChunkSize: Cardinal);
  1966. var
  1967. DataIn : Pointer;
  1968. DataInSize : Integer;
  1969. Output : TMemoryStream;
  1970. Index : Integer;
  1971. begin
  1972. inherited;
  1973. // read keyword and null separator
  1974. Index := 1;
  1975. SetLength(FKeyword, 80);
  1976. while (Stream.Position < Stream.Size) do
  1977. begin
  1978. Stream.Read(FKeyword[Index], SizeOf(Byte));
  1979. if FKeyword[Index] = #0 then
  1980. begin
  1981. SetLength(FKeyword, Index - 1);
  1982. Break;
  1983. end;
  1984. Inc(Index);
  1985. if (Index > High(FKeyword)) then
  1986. raise EPngError.Create(RCStrChunkInvalid);
  1987. end;
  1988. // read compression method
  1989. Stream.Read(FCompressionMethod, SizeOf(Byte));
  1990. if FCompressionMethod <> 0 then
  1991. raise EPngError.Create(RCStrUnsupportedCompressMethod);
  1992. // read text
  1993. DataInSize := Stream.Size - Stream.Position;
  1994. GetMem(DataIn, DataInSize);
  1995. try
  1996. Stream.Read(DataIn^, DataInSize);
  1997. Output := TMemoryStream.Create;
  1998. try
  1999. ZDecompress(DataIn, DataInSize, Output);
  2000. SetLength(FText, Output.Size);
  2001. Move(Output.Memory^, FText[1], Output.Size);
  2002. finally
  2003. Output.Free;
  2004. end;
  2005. finally
  2006. FreeMem(DataIn);
  2007. end;
  2008. end;
  2009. procedure TChunkPngCompressedText.SetCompressionMethod(const Value: Byte);
  2010. begin
  2011. if Value <> 0 then
  2012. raise EPngError.Create(RCStrUnsupportedCompressMethod);
  2013. FCompressionMethod := Value;
  2014. end;
  2015. procedure TChunkPngCompressedText.WriteToStream(Stream: TStream);
  2016. var
  2017. OutputStream: TMemoryStream;
  2018. Temp : Byte;
  2019. begin
  2020. if (Length(FKeyword) = 0) then
  2021. raise EPngError.Create(RCStrChunkInvalid);
  2022. // write keyword
  2023. Stream.Write(FKeyword[1], Length(FKeyword));
  2024. // write separator
  2025. Temp := 0;
  2026. Stream.Write(Temp, 1);
  2027. // write compression method
  2028. Stream.Write(FCompressionMethod, SizeOf(Byte));
  2029. if (Length(FText) > 0) then
  2030. begin
  2031. OutputStream := TMemoryStream.Create;
  2032. try
  2033. // compress text
  2034. ZCompress(@FText[1], Length(FText), OutputStream);
  2035. // write text
  2036. Stream.Write(OutputStream.Memory^, OutputStream.Size);
  2037. finally
  2038. OutputStream.Free;
  2039. end;
  2040. end;
  2041. end;
  2042. { TChunkPngInternationalText }
  2043. {$ifdef PNG_CHUNK_INTERNATIONAL_TEXT}
  2044. procedure TChunkPngInternationalText.AssignTo(Dest: TPersistent);
  2045. begin
  2046. if Dest is TChunkPngInternationalText then
  2047. with TChunkPngInternationalText(Dest) do
  2048. begin
  2049. FCompressionMethod := Self.FCompressionMethod;
  2050. FCompressionFlag := Self.FCompressionFlag;
  2051. FLanguageString := Self.FLanguageString;
  2052. FTranslatedKeyword := Self.FTranslatedKeyword;
  2053. end
  2054. else
  2055. inherited;
  2056. end;
  2057. class function TChunkPngInternationalText.GetClassChunkName: TChunkName;
  2058. begin
  2059. Result := 'iTXt';
  2060. end;
  2061. function TChunkPngInternationalText.GetChunkSize: Cardinal;
  2062. begin
  2063. Result := 0;
  2064. end;
  2065. procedure TChunkPngInternationalText.ReadFromStream(Stream: TStream;
  2066. ChunkSize: Cardinal);
  2067. var
  2068. Index : Integer;
  2069. begin
  2070. inherited;
  2071. // read keyword
  2072. Index := 1;
  2073. SetLength(FKeyword, 80);
  2074. while (Stream.Position < Stream.Size) do
  2075. begin
  2076. Stream.Read(FKeyword[Index], SizeOf(Byte));
  2077. if FKeyword[Index] = #0 then
  2078. begin
  2079. SetLength(FKeyword, Index - 1);
  2080. Break;
  2081. end;
  2082. Inc(Index);
  2083. end;
  2084. // read compression flag
  2085. Stream.Read(FCompressionFlag, SizeOf(Byte));
  2086. // read compression method
  2087. Stream.Read(FCompressionMethod, SizeOf(Byte));
  2088. // read language string
  2089. Index := 1;
  2090. SetLength(FLanguageString, 10);
  2091. while (Stream.Position < Stream.Size) do
  2092. begin
  2093. Stream.Read(FLanguageString[Index], SizeOf(Byte));
  2094. if FLanguageString[Index] = #0 then
  2095. begin
  2096. SetLength(FLanguageString, Index - 1);
  2097. Break;
  2098. end;
  2099. Inc(Index);
  2100. end;
  2101. // yet todo!
  2102. Exit;
  2103. end;
  2104. procedure TChunkPngInternationalText.WriteToStream(Stream: TStream);
  2105. begin
  2106. // TODO
  2107. raise EPngError.CreateFmt(RCStrChunkNotImplemented, [ChunkNameAsString]);
  2108. end;
  2109. {$endif PNG_CHUNK_INTERNATIONAL_TEXT}
  2110. { TChunkPngImageData }
  2111. constructor TChunkPngImageData.Create;
  2112. begin
  2113. inherited;
  2114. FData := TMemoryStream.Create;
  2115. end;
  2116. destructor TChunkPngImageData.Destroy;
  2117. begin
  2118. FData.Free;
  2119. inherited;
  2120. end;
  2121. procedure TChunkPngImageData.AssignTo(Dest: TPersistent);
  2122. begin
  2123. if Dest is TChunkPngImageData then
  2124. with TChunkPngImageData(Dest) do
  2125. begin
  2126. FData.Seek(0, soFromBeginning);
  2127. Self.FData.Seek(0, soFromBeginning);
  2128. FData.CopyFrom(Self.FData, Self.FData.Size);
  2129. FData.Seek(0, soFromBeginning);
  2130. end
  2131. else
  2132. inherited;
  2133. end;
  2134. class function TChunkPngImageData.GetClassChunkName: TChunkName;
  2135. begin
  2136. Result := 'IDAT';
  2137. end;
  2138. function TChunkPngImageData.GetChunkSize: Cardinal;
  2139. begin
  2140. Result := FData.Size;
  2141. end;
  2142. procedure TChunkPngImageData.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  2143. begin
  2144. inherited;
  2145. FData.CopyFrom(Stream, ChunkSize);
  2146. end;
  2147. procedure TChunkPngImageData.WriteToStream(Stream: TStream);
  2148. begin
  2149. FData.Seek(0, soFromBeginning);
  2150. Stream.CopyFrom(FData, FData.Size);
  2151. end;
  2152. { TChunkPngTime }
  2153. procedure TChunkPngTime.AssignTo(Dest: TPersistent);
  2154. begin
  2155. if Dest is TChunkPngTime then
  2156. with TChunkPngTime(Dest) do
  2157. begin
  2158. FYear := Self.FYear;
  2159. FMonth := Self.FMonth;
  2160. FDay := Self.FDay;
  2161. FHour := Self.FHour;
  2162. FMinute := Self.FMinute;
  2163. FSecond := Self.FSecond;
  2164. end
  2165. else
  2166. inherited;
  2167. end;
  2168. class function TChunkPngTime.GetClassChunkName: TChunkName;
  2169. begin
  2170. Result := 'tIME';
  2171. end;
  2172. function TChunkPngTime.GetModifiedDateTime: TDateTime;
  2173. begin
  2174. Result := EncodeDate(Year, Month, Day) + EncodeTime(Hour, Minute, Second, 0);
  2175. end;
  2176. function TChunkPngTime.GetChunkSize: Cardinal;
  2177. begin
  2178. Result := 7;
  2179. end;
  2180. procedure TChunkPngTime.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  2181. begin
  2182. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  2183. raise EPngError.Create(RCStrChunkSizeTooSmall);
  2184. // read year
  2185. FYear := BigEndian.ReadWord(Stream);
  2186. // read month
  2187. Stream.Read(FMonth, SizeOf(Byte));
  2188. // read day
  2189. Stream.Read(FDay, SizeOf(Byte));
  2190. // read hour
  2191. Stream.Read(FHour, SizeOf(Byte));
  2192. // read minute
  2193. Stream.Read(FMinute, SizeOf(Byte));
  2194. // read second
  2195. Stream.Read(FSecond, SizeOf(Byte));
  2196. end;
  2197. procedure TChunkPngTime.WriteToStream(Stream: TStream);
  2198. begin
  2199. // write year
  2200. BigEndian.WriteWord(Stream, FYear);
  2201. // write month
  2202. Stream.Write(FMonth, SizeOf(Byte));
  2203. // write day
  2204. Stream.Write(FDay, SizeOf(Byte));
  2205. // write hour
  2206. Stream.Write(FHour, SizeOf(Byte));
  2207. // write minute
  2208. Stream.Write(FMinute, SizeOf(Byte));
  2209. // write second
  2210. Stream.Write(FSecond, SizeOf(Byte));
  2211. end;
  2212. procedure TChunkPngTime.SetModifiedDateTime(const Value: TDateTime);
  2213. var
  2214. mnth : Word;
  2215. day : Word;
  2216. hour : Word;
  2217. min : Word;
  2218. sec : Word;
  2219. msec : Word;
  2220. begin
  2221. DecodeDate(Value, FYear, mnth, day);
  2222. FMonth := mnth;
  2223. FDay := day;
  2224. DecodeTime(Value, hour, min, sec, msec);
  2225. FHour := hour;
  2226. FMinute := min;
  2227. FSecond := sec;
  2228. end;
  2229. { TChunkPngEmbeddedIccProfile }
  2230. procedure TChunkPngEmbeddedIccProfile.AssignTo(Dest: TPersistent);
  2231. begin
  2232. if Dest is TChunkPngEmbeddedIccProfile then
  2233. with TChunkPngEmbeddedIccProfile(Dest) do
  2234. begin
  2235. FProfileName := Self.FProfileName;
  2236. FCompressionMethod := Self.FCompressionMethod;
  2237. end
  2238. else
  2239. inherited;
  2240. end;
  2241. class function TChunkPngEmbeddedIccProfile.GetClassChunkName: TChunkName;
  2242. begin
  2243. Result := 'iCCP';
  2244. end;
  2245. function TChunkPngEmbeddedIccProfile.GetChunkSize: Cardinal;
  2246. begin
  2247. Result := Length(FProfileName) + 2;
  2248. end;
  2249. procedure TChunkPngEmbeddedIccProfile.ReadFromStream(Stream: TStream;
  2250. ChunkSize: Cardinal);
  2251. var
  2252. Index : Integer;
  2253. begin
  2254. // read keyword
  2255. Index := 1;
  2256. SetLength(FProfileName, 80);
  2257. while (Stream.Position < Stream.Size) do
  2258. begin
  2259. Stream.Read(FProfileName[Index], SizeOf(Byte));
  2260. if FProfileName[Index] = #0 then
  2261. begin
  2262. SetLength(FProfileName, Index - 1);
  2263. Break;
  2264. end;
  2265. Inc(Index);
  2266. end;
  2267. // read compression method
  2268. Stream.Read(FCompressionMethod, 1);
  2269. // not yet completed
  2270. end;
  2271. procedure TChunkPngEmbeddedIccProfile.WriteToStream(Stream: TStream);
  2272. var
  2273. Temp : Byte;
  2274. begin
  2275. // write keyword
  2276. Stream.Write(FProfileName[1], Length(FProfileName));
  2277. // write separator
  2278. Temp := 0;
  2279. Stream.Write(Temp, 1);
  2280. // write compression method
  2281. Stream.Write(FCompressionMethod, 1);
  2282. end;
  2283. { TChunkPngGamma }
  2284. procedure TChunkPngGamma.AssignTo(Dest: TPersistent);
  2285. begin
  2286. if Dest is TChunkPngGamma then
  2287. with TChunkPngGamma(Dest) do
  2288. begin
  2289. FGamma := Self.FGamma;
  2290. end
  2291. else
  2292. inherited;
  2293. end;
  2294. class function TChunkPngGamma.GetClassChunkName: TChunkName;
  2295. begin
  2296. Result := 'gAMA';
  2297. end;
  2298. function TChunkPngGamma.GetGammaAsSingle: Single;
  2299. begin
  2300. Result := FGamma * 1E-5;
  2301. end;
  2302. procedure TChunkPngGamma.SetGammaAsSingle(const Value: Single);
  2303. begin
  2304. FGamma := Round(Value * 1E5);
  2305. end;
  2306. function TChunkPngGamma.GetChunkSize: Cardinal;
  2307. begin
  2308. Result := 4;
  2309. end;
  2310. procedure TChunkPngGamma.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  2311. begin
  2312. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  2313. raise EPngError.Create(RCStrChunkSizeTooSmall);
  2314. // read gamma
  2315. FGamma := BigEndian.ReadCardinal(Stream);
  2316. end;
  2317. procedure TChunkPngGamma.WriteToStream(Stream: TStream);
  2318. begin
  2319. // write gamma
  2320. BigEndian.WriteCardinal(Stream, FGamma);
  2321. end;
  2322. { TChunkPngStandardColorSpaceRGB }
  2323. procedure TChunkPngStandardColorSpaceRGB.AssignTo(Dest: TPersistent);
  2324. begin
  2325. if Dest is TChunkPngStandardColorSpaceRGB then
  2326. with TChunkPngStandardColorSpaceRGB(Dest) do
  2327. begin
  2328. FRenderingIntent := Self.FRenderingIntent;
  2329. end
  2330. else
  2331. inherited;
  2332. end;
  2333. class function TChunkPngStandardColorSpaceRGB.GetClassChunkName: TChunkName;
  2334. begin
  2335. Result := 'sRGB';
  2336. end;
  2337. function TChunkPngStandardColorSpaceRGB.GetChunkSize: Cardinal;
  2338. begin
  2339. Result := 1;
  2340. end;
  2341. procedure TChunkPngStandardColorSpaceRGB.ReadFromStream(Stream: TStream;
  2342. ChunkSize: Cardinal);
  2343. begin
  2344. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  2345. raise EPngError.Create(RCStrChunkSizeTooSmall);
  2346. // read rendering intent
  2347. Stream.Read(FRenderingIntent, SizeOf(Byte));
  2348. end;
  2349. procedure TChunkPngStandardColorSpaceRGB.WriteToStream(Stream: TStream);
  2350. begin
  2351. // write rendering intent
  2352. Stream.Write(FRenderingIntent, SizeOf(Byte));
  2353. end;
  2354. { TChunkPngPrimaryChromaticities }
  2355. class function TChunkPngPrimaryChromaticities.GetClassChunkName: TChunkName;
  2356. begin
  2357. Result := 'cHRM';
  2358. end;
  2359. procedure TChunkPngPrimaryChromaticities.AssignTo(Dest: TPersistent);
  2360. begin
  2361. if Dest is TChunkPngPrimaryChromaticities then
  2362. with TChunkPngPrimaryChromaticities(Dest) do
  2363. begin
  2364. FWhiteX := Self.FWhiteX;
  2365. FWhiteY := Self.FWhiteY;
  2366. FRedX := Self.FRedX;
  2367. FRedY := Self.FRedY;
  2368. FGreenX := Self.FGreenX;
  2369. FGreenY := Self.FGreenY;
  2370. FBlueX := Self.FBlueX;
  2371. FBlueY := Self.FBlueY;
  2372. end
  2373. else
  2374. inherited;
  2375. end;
  2376. function TChunkPngPrimaryChromaticities.GetBlueX: Single;
  2377. begin
  2378. Result := FBlueX * 1E-5;
  2379. end;
  2380. function TChunkPngPrimaryChromaticities.GetBlueY: Single;
  2381. begin
  2382. Result := FBlueY * 1E-5;
  2383. end;
  2384. function TChunkPngPrimaryChromaticities.GetGreenX: Single;
  2385. begin
  2386. Result := FGreenX * 1E-5;
  2387. end;
  2388. function TChunkPngPrimaryChromaticities.GetGreenY: Single;
  2389. begin
  2390. Result := FGreenY * 1E-5;
  2391. end;
  2392. function TChunkPngPrimaryChromaticities.GetRedX: Single;
  2393. begin
  2394. Result := FRedX * 1E-5;
  2395. end;
  2396. function TChunkPngPrimaryChromaticities.GetRedY: Single;
  2397. begin
  2398. Result := FRedY * 1E-5;
  2399. end;
  2400. function TChunkPngPrimaryChromaticities.GetWhiteX: Single;
  2401. begin
  2402. Result := FWhiteX * 1E-5;
  2403. end;
  2404. function TChunkPngPrimaryChromaticities.GetWhiteY: Single;
  2405. begin
  2406. Result := FWhiteY * 1E-5;
  2407. end;
  2408. function TChunkPngPrimaryChromaticities.GetChunkSize: Cardinal;
  2409. begin
  2410. Result := 32;
  2411. end;
  2412. procedure TChunkPngPrimaryChromaticities.ReadFromStream(Stream: TStream;
  2413. ChunkSize: Cardinal);
  2414. begin
  2415. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  2416. raise EPngError.Create(RCStrChunkSizeTooSmall);
  2417. // read white point x
  2418. FWhiteX := BigEndian.ReadCardinal(Stream);
  2419. // read white point y
  2420. FWhiteY := BigEndian.ReadCardinal(Stream);
  2421. // read red x
  2422. FRedX := BigEndian.ReadCardinal(Stream);
  2423. // read red y
  2424. FRedY := BigEndian.ReadCardinal(Stream);
  2425. // read green x
  2426. FGreenX := BigEndian.ReadCardinal(Stream);
  2427. // read green y
  2428. FGreenY := BigEndian.ReadCardinal(Stream);
  2429. // read blue x
  2430. FBlueX := BigEndian.ReadCardinal(Stream);
  2431. // read blue y
  2432. FBlueY := BigEndian.ReadCardinal(Stream);
  2433. end;
  2434. procedure TChunkPngPrimaryChromaticities.WriteToStream(Stream: TStream);
  2435. begin
  2436. // write white point x
  2437. BigEndian.WriteCardinal(Stream, FWhiteX);
  2438. // write white point y
  2439. BigEndian.WriteCardinal(Stream, FWhiteY);
  2440. // write red x
  2441. BigEndian.WriteCardinal(Stream, FRedX);
  2442. // write red y
  2443. BigEndian.WriteCardinal(Stream, FRedY);
  2444. // write green x
  2445. BigEndian.WriteCardinal(Stream, FGreenX);
  2446. // write green y
  2447. BigEndian.WriteCardinal(Stream, FGreenY);
  2448. // write blue x
  2449. BigEndian.WriteCardinal(Stream, FBlueX);
  2450. // write blue y
  2451. BigEndian.WriteCardinal(Stream, FBlueY);
  2452. end;
  2453. procedure TChunkPngPrimaryChromaticities.SetBlueX(const Value: Single);
  2454. begin
  2455. FBlueX := Round(Value * 1E5);
  2456. end;
  2457. procedure TChunkPngPrimaryChromaticities.SetBlueY(const Value: Single);
  2458. begin
  2459. FBlueY := Round(Value * 1E5);
  2460. end;
  2461. procedure TChunkPngPrimaryChromaticities.SetGreenX(const Value: Single);
  2462. begin
  2463. FGreenX := Round(Value * 1E5);
  2464. end;
  2465. procedure TChunkPngPrimaryChromaticities.SetGreenY(const Value: Single);
  2466. begin
  2467. FGreenY := Round(Value * 1E5);
  2468. end;
  2469. procedure TChunkPngPrimaryChromaticities.SetRedX(const Value: Single);
  2470. begin
  2471. FRedX := Round(Value * 1E5);
  2472. end;
  2473. procedure TChunkPngPrimaryChromaticities.SetRedY(const Value: Single);
  2474. begin
  2475. FRedY := Round(Value * 1E5);
  2476. end;
  2477. procedure TChunkPngPrimaryChromaticities.SetWhiteX(const Value: Single);
  2478. begin
  2479. FWhiteX := Round(Value * 1E5);
  2480. end;
  2481. procedure TChunkPngPrimaryChromaticities.SetWhiteY(const Value: Single);
  2482. begin
  2483. FWhiteY := Round(Value * 1E5);
  2484. end;
  2485. { TPngSignificantBitsFormat0 }
  2486. constructor TPngSignificantBitsFormat0.Create(BitDepth: Integer = 8);
  2487. begin
  2488. inherited;
  2489. FGrayBits := BitDepth;
  2490. end;
  2491. procedure TPngSignificantBitsFormat0.AssignTo(Dest: TPersistent);
  2492. begin
  2493. if Dest is TPngSignificantBitsFormat0 then
  2494. with TPngSignificantBitsFormat0(Dest) do
  2495. begin
  2496. FGrayBits := Self.FGrayBits;
  2497. end
  2498. else
  2499. inherited;
  2500. end;
  2501. class function TPngSignificantBitsFormat0.GetChunkSize: Cardinal;
  2502. begin
  2503. Result := 1;
  2504. end;
  2505. procedure TPngSignificantBitsFormat0.ReadFromStream(Stream: TStream);
  2506. begin
  2507. Stream.Read(FGrayBits, 1);
  2508. end;
  2509. procedure TPngSignificantBitsFormat0.WriteToStream(Stream: TStream);
  2510. begin
  2511. Stream.Write(FGrayBits, 1);
  2512. end;
  2513. { TPngSignificantBitsFormat23 }
  2514. constructor TPngSignificantBitsFormat23.Create(BitDepth: Integer = 8);
  2515. begin
  2516. inherited;
  2517. FRedBits := BitDepth;
  2518. FGreenBits := BitDepth;
  2519. FBlueBits := BitDepth;
  2520. end;
  2521. procedure TPngSignificantBitsFormat23.AssignTo(Dest: TPersistent);
  2522. begin
  2523. if Dest is TPngSignificantBitsFormat23 then
  2524. with TPngSignificantBitsFormat23(Dest) do
  2525. begin
  2526. FRedBits := Self.FRedBits;
  2527. FBlueBits := Self.FBlueBits;
  2528. FGreenBits := Self.FGreenBits;
  2529. end
  2530. else
  2531. inherited;
  2532. end;
  2533. class function TPngSignificantBitsFormat23.GetChunkSize: Cardinal;
  2534. begin
  2535. Result := 3;
  2536. end;
  2537. procedure TPngSignificantBitsFormat23.ReadFromStream(Stream: TStream);
  2538. begin
  2539. Stream.Read(FRedBits, 1);
  2540. Stream.Read(FGreenBits, 1);
  2541. Stream.Read(FBlueBits, 1);
  2542. end;
  2543. procedure TPngSignificantBitsFormat23.WriteToStream(Stream: TStream);
  2544. begin
  2545. Stream.Write(FRedBits, 1);
  2546. Stream.Write(FGreenBits, 1);
  2547. Stream.Write(FBlueBits, 1);
  2548. end;
  2549. { TPngSignificantBitsFormat4 }
  2550. constructor TPngSignificantBitsFormat4.Create(BitDepth: Integer = 8);
  2551. begin
  2552. inherited;
  2553. FGrayBits := BitDepth;
  2554. FAlphaBits := BitDepth;
  2555. end;
  2556. procedure TPngSignificantBitsFormat4.AssignTo(Dest: TPersistent);
  2557. begin
  2558. if Dest is TPngSignificantBitsFormat4 then
  2559. with TPngSignificantBitsFormat4(Dest) do
  2560. begin
  2561. FGrayBits := Self.FGrayBits;
  2562. FAlphaBits := Self.FAlphaBits;
  2563. end
  2564. else if Dest is TPngSignificantBitsFormat0 then
  2565. with TPngSignificantBitsFormat0(Dest) do
  2566. FGrayBits := Self.FGrayBits
  2567. else
  2568. inherited;
  2569. end;
  2570. class function TPngSignificantBitsFormat4.GetChunkSize: Cardinal;
  2571. begin
  2572. Result := 2;
  2573. end;
  2574. procedure TPngSignificantBitsFormat4.ReadFromStream(Stream: TStream);
  2575. begin
  2576. Stream.Read(FGrayBits, 1);
  2577. Stream.Read(FAlphaBits, 1);
  2578. end;
  2579. procedure TPngSignificantBitsFormat4.WriteToStream(Stream: TStream);
  2580. begin
  2581. Stream.Write(FGrayBits, 1);
  2582. Stream.Write(FAlphaBits, 1);
  2583. end;
  2584. { TPngSignificantBitsFormat6 }
  2585. constructor TPngSignificantBitsFormat6.Create(BitDepth: Integer = 8);
  2586. begin
  2587. inherited;
  2588. FRedBits := BitDepth;
  2589. FGreenBits := BitDepth;
  2590. FBlueBits := BitDepth;
  2591. FAlphaBits := BitDepth;
  2592. end;
  2593. procedure TPngSignificantBitsFormat6.AssignTo(Dest: TPersistent);
  2594. begin
  2595. if Dest is TPngSignificantBitsFormat6 then
  2596. with TPngSignificantBitsFormat6(Dest) do
  2597. begin
  2598. FRedBits := Self.FRedBits;
  2599. FBlueBits := Self.FBlueBits;
  2600. FGreenBits := Self.FGreenBits;
  2601. FAlphaBits := Self.FAlphaBits;
  2602. end
  2603. else if Dest is TPngSignificantBitsFormat23 then
  2604. with TPngSignificantBitsFormat23(Dest) do
  2605. begin
  2606. FRedBits := Self.FRedBits;
  2607. FBlueBits := Self.FBlueBits;
  2608. FGreenBits := Self.FGreenBits;
  2609. end
  2610. else
  2611. inherited;
  2612. end;
  2613. class function TPngSignificantBitsFormat6.GetChunkSize: Cardinal;
  2614. begin
  2615. Result := 4;
  2616. end;
  2617. procedure TPngSignificantBitsFormat6.ReadFromStream(Stream: TStream);
  2618. begin
  2619. Stream.Read(FRedBits, 1);
  2620. Stream.Read(FGreenBits, 1);
  2621. Stream.Read(FBlueBits, 1);
  2622. Stream.Read(FAlphaBits, 1);
  2623. end;
  2624. procedure TPngSignificantBitsFormat6.WriteToStream(Stream: TStream);
  2625. begin
  2626. Stream.Write(FRedBits, 1);
  2627. Stream.Write(FGreenBits, 1);
  2628. Stream.Write(FBlueBits, 1);
  2629. Stream.Write(FAlphaBits, 1);
  2630. end;
  2631. { TChunkPngSignificantBits }
  2632. procedure TChunkPngSignificantBits.AssignTo(Dest: TPersistent);
  2633. begin
  2634. if Dest is TChunkPngSignificantBits then
  2635. with TChunkPngSignificantBits(Dest) do
  2636. begin
  2637. FSignificantBits.Assign(Self.FSignificantBits);
  2638. end
  2639. else
  2640. inherited;
  2641. end;
  2642. constructor TChunkPngSignificantBits.Create(Header: TChunkPngImageHeader);
  2643. begin
  2644. inherited;
  2645. case Header.ColorType of
  2646. ctGrayscale:
  2647. FSignificantBits := TPngSignificantBitsFormat0.Create(Header.BitDepth);
  2648. ctTrueColor,
  2649. ctIndexedColor:
  2650. FSignificantBits := TPngSignificantBitsFormat23.Create(Header.BitDepth);
  2651. ctGrayscaleAlpha:
  2652. FSignificantBits := TPngSignificantBitsFormat4.Create(Header.BitDepth);
  2653. ctTrueColorAlpha:
  2654. FSignificantBits := TPngSignificantBitsFormat6.Create(Header.BitDepth);
  2655. end;
  2656. end;
  2657. destructor TChunkPngSignificantBits.Destroy;
  2658. begin
  2659. FSignificantBits.Free;
  2660. inherited;
  2661. end;
  2662. class function TChunkPngSignificantBits.GetClassChunkName: TChunkName;
  2663. begin
  2664. Result := 'sBIT';
  2665. end;
  2666. procedure TChunkPngSignificantBits.HeaderChanged;
  2667. var
  2668. OldSignificantBits : TCustomPngSignificantBits;
  2669. begin
  2670. inherited;
  2671. // store old SignificantBits object
  2672. OldSignificantBits := FSignificantBits;
  2673. // change SignificantBits object class
  2674. case FHeader.ColorType of
  2675. ctGrayscale:
  2676. if not (FSignificantBits is TPngSignificantBitsFormat0) then
  2677. FSignificantBits := TPngSignificantBitsFormat0.Create(FHeader.BitDepth);
  2678. ctTrueColor, ctIndexedColor:
  2679. if not (FSignificantBits is TPngSignificantBitsFormat23) then
  2680. FSignificantBits := TPngSignificantBitsFormat23.Create(FHeader.BitDepth);
  2681. ctTrueColorAlpha:
  2682. if not (FSignificantBits is TPngSignificantBitsFormat4) then
  2683. FSignificantBits := TPngSignificantBitsFormat4.Create(FHeader.BitDepth);
  2684. ctGrayscaleAlpha :
  2685. if not (FSignificantBits is TPngSignificantBitsFormat6) then
  2686. FSignificantBits := TPngSignificantBitsFormat6.Create(FHeader.BitDepth);
  2687. else
  2688. FSignificantBits := nil;
  2689. end;
  2690. if (OldSignificantBits <> nil) and (OldSignificantBits <> FSignificantBits) then
  2691. begin
  2692. if (FSignificantBits <> nil) then
  2693. FSignificantBits.Assign(OldSignificantBits);
  2694. OldSignificantBits.Free;
  2695. end;
  2696. end;
  2697. function TChunkPngSignificantBits.GetChunkSize: Cardinal;
  2698. begin
  2699. if (FSignificantBits <> nil) then
  2700. Result := FSignificantBits.GetChunkSize
  2701. else
  2702. Result := 0;
  2703. end;
  2704. procedure TChunkPngSignificantBits.ReadFromStream(Stream: TStream;
  2705. ChunkSize: Cardinal);
  2706. begin
  2707. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  2708. raise EPngError.Create(RCStrChunkSizeTooSmall);
  2709. if (FSignificantBits <> nil) then
  2710. FSignificantBits.ReadFromStream(Stream);
  2711. end;
  2712. procedure TChunkPngSignificantBits.WriteToStream(Stream: TStream);
  2713. begin
  2714. if (FSignificantBits <> nil) then
  2715. FSignificantBits.WriteToStream(Stream);
  2716. end;
  2717. { TPngBackgroundColorFormat04 }
  2718. procedure TPngBackgroundColorFormat04.AssignTo(Dest: TPersistent);
  2719. begin
  2720. if Dest is TPngBackgroundColorFormat04 then
  2721. with TPngBackgroundColorFormat04(Dest) do
  2722. begin
  2723. FGraySampleValue := Self.FGraySampleValue;
  2724. end
  2725. else
  2726. inherited;
  2727. end;
  2728. class function TPngBackgroundColorFormat04.GetChunkSize: Cardinal;
  2729. begin
  2730. Result := 2;
  2731. end;
  2732. procedure TPngBackgroundColorFormat04.ReadFromStream(Stream: TStream);
  2733. begin
  2734. FGraySampleValue := BigEndian.ReadWord(Stream);
  2735. end;
  2736. procedure TPngBackgroundColorFormat04.WriteToStream(Stream: TStream);
  2737. begin
  2738. BigEndian.WriteWord(Stream, FGraySampleValue);
  2739. end;
  2740. { TPngBackgroundColorFormat26 }
  2741. procedure TPngBackgroundColorFormat26.AssignTo(Dest: TPersistent);
  2742. begin
  2743. if Dest is TPngBackgroundColorFormat26 then
  2744. with TPngBackgroundColorFormat26(Dest) do
  2745. begin
  2746. FRedSampleValue := Self.FRedSampleValue;
  2747. FBlueSampleValue := Self.FBlueSampleValue;
  2748. FGreenSampleValue := Self.FGreenSampleValue;
  2749. end
  2750. else
  2751. inherited;
  2752. end;
  2753. class function TPngBackgroundColorFormat26.GetChunkSize: Cardinal;
  2754. begin
  2755. Result := 6;
  2756. end;
  2757. procedure TPngBackgroundColorFormat26.ReadFromStream(Stream: TStream);
  2758. begin
  2759. FRedSampleValue := BigEndian.ReadWord(Stream);
  2760. FGreenSampleValue := BigEndian.ReadWord(Stream);
  2761. FBlueSampleValue := BigEndian.ReadWord(Stream);
  2762. end;
  2763. procedure TPngBackgroundColorFormat26.WriteToStream(Stream: TStream);
  2764. begin
  2765. BigEndian.WriteWord(Stream, FRedSampleValue);
  2766. BigEndian.WriteWord(Stream, FGreenSampleValue);
  2767. BigEndian.WriteWord(Stream, FBlueSampleValue);
  2768. end;
  2769. { TPngBackgroundColorFormat3 }
  2770. procedure TPngBackgroundColorFormat3.AssignTo(Dest: TPersistent);
  2771. begin
  2772. if Dest is TPngBackgroundColorFormat3 then
  2773. with TPngBackgroundColorFormat3(Dest) do
  2774. begin
  2775. FIndex := Self.FIndex;
  2776. end
  2777. else
  2778. inherited;
  2779. end;
  2780. class function TPngBackgroundColorFormat3.GetChunkSize: Cardinal;
  2781. begin
  2782. Result := 1;
  2783. end;
  2784. procedure TPngBackgroundColorFormat3.ReadFromStream(Stream: TStream);
  2785. begin
  2786. Stream.Read(FIndex, 1);
  2787. end;
  2788. procedure TPngBackgroundColorFormat3.WriteToStream(Stream: TStream);
  2789. begin
  2790. Stream.Write(FIndex, 1);
  2791. end;
  2792. { TChunkPngBackgroundColor }
  2793. procedure TChunkPngBackgroundColor.AssignTo(Dest: TPersistent);
  2794. begin
  2795. if Dest is TChunkPngBackgroundColor then
  2796. with TChunkPngBackgroundColor(Dest) do
  2797. begin
  2798. FBackground.Assign(Self.FBackground);
  2799. end
  2800. else
  2801. inherited;
  2802. end;
  2803. constructor TChunkPngBackgroundColor.Create(Header: TChunkPngImageHeader);
  2804. begin
  2805. inherited;
  2806. case Header.ColorType of
  2807. ctGrayscale, ctGrayscaleAlpha:
  2808. FBackground := TPngBackgroundColorFormat04.Create;
  2809. ctTrueColor, ctTrueColorAlpha:
  2810. FBackground := TPngBackgroundColorFormat26.Create;
  2811. ctIndexedColor:
  2812. FBackground := TPngBackgroundColorFormat3.Create;
  2813. end;
  2814. end;
  2815. destructor TChunkPngBackgroundColor.Destroy;
  2816. begin
  2817. FBackground.Free;
  2818. inherited;
  2819. end;
  2820. class function TChunkPngBackgroundColor.GetClassChunkName: TChunkName;
  2821. begin
  2822. Result := 'bKGD';
  2823. end;
  2824. procedure TChunkPngBackgroundColor.HeaderChanged;
  2825. var
  2826. OldBackground : TCustomPngBackgroundColor;
  2827. begin
  2828. inherited;
  2829. // store old background object
  2830. OldBackground := FBackground;
  2831. // change background object class
  2832. case FHeader.ColorType of
  2833. ctGrayscale, ctGrayscaleAlpha:
  2834. if not (FBackground is TPngBackgroundColorFormat04) then
  2835. FBackground := TPngBackgroundColorFormat04.Create;
  2836. ctTrueColor, ctTrueColorAlpha :
  2837. if not (FBackground is TPngBackgroundColorFormat26) then
  2838. FBackground := TPngBackgroundColorFormat26.Create;
  2839. ctIndexedColor :
  2840. if not (FBackground is TPngBackgroundColorFormat3) then
  2841. FBackground := TPngBackgroundColorFormat3.Create;
  2842. else
  2843. FBackground := nil;
  2844. end;
  2845. if (OldBackground <> nil) and (OldBackground <> FBackground) then
  2846. begin
  2847. if (FBackground <> nil) then
  2848. FBackground.Assign(OldBackground);
  2849. OldBackground.Free;
  2850. end;
  2851. end;
  2852. function TChunkPngBackgroundColor.GetChunkSize: Cardinal;
  2853. begin
  2854. if (FBackground <> nil) then
  2855. Result := FBackground.GetChunkSize
  2856. else
  2857. Result := 0;
  2858. end;
  2859. procedure TChunkPngBackgroundColor.ReadFromStream(Stream: TStream;
  2860. ChunkSize: Cardinal);
  2861. begin
  2862. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  2863. raise EPngError.Create(RCStrChunkSizeTooSmall);
  2864. if (FBackground <> nil) then
  2865. FBackground.ReadFromStream(Stream);
  2866. end;
  2867. procedure TChunkPngBackgroundColor.WriteToStream(Stream: TStream);
  2868. begin
  2869. if (FBackground <> nil) then
  2870. FBackground.WriteToStream(Stream);
  2871. end;
  2872. { TChunkPngImageHistogram }
  2873. class function TChunkPngImageHistogram.GetClassChunkName: TChunkName;
  2874. begin
  2875. Result := 'hIST';
  2876. end;
  2877. function TChunkPngImageHistogram.GetCount: Cardinal;
  2878. begin
  2879. Result := Length(FHistogram);
  2880. end;
  2881. function TChunkPngImageHistogram.GetFrequency(Index: Cardinal): Word;
  2882. begin
  2883. if Index < Count then
  2884. Result := FHistogram[Index]
  2885. else
  2886. raise Exception.CreateFmt(RCStrIndexOutOfBounds, [Index]);
  2887. end;
  2888. function TChunkPngImageHistogram.GetChunkSize: Cardinal;
  2889. begin
  2890. Result := Count * SizeOf(Word);
  2891. end;
  2892. procedure TChunkPngImageHistogram.ReadFromStream(Stream: TStream; ChunkSize: Cardinal);
  2893. var
  2894. Index : Integer;
  2895. begin
  2896. // check size
  2897. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  2898. raise EPngError.Create(RCStrChunkSizeTooSmall);
  2899. // adjust histogram array size
  2900. SetLength(FHistogram, ChunkSize div 2);
  2901. // read histogram data
  2902. for Index := 0 to Length(FHistogram) - 1 do
  2903. FHistogram[Index] := BigEndian.ReadWord(Stream);
  2904. end;
  2905. procedure TChunkPngImageHistogram.WriteToStream(Stream: TStream);
  2906. var
  2907. Index : Integer;
  2908. begin
  2909. // write histogram data
  2910. for Index := 0 to Length(FHistogram) - 1 do
  2911. BigEndian.WriteWord(Stream, FHistogram[Index]);
  2912. end;
  2913. { TChunkPngSuggestedPalette }
  2914. {$ifdef PNG_CHUNK_SUGGESTED_PALETTE}
  2915. constructor TChunkPngSuggestedPalette.Create(Header: TChunkPngImageHeader);
  2916. begin
  2917. inherited;
  2918. FData := nil;
  2919. FCount := 0;
  2920. end;
  2921. class function TChunkPngSuggestedPalette.GetClassChunkName: TChunkName;
  2922. begin
  2923. Result := 'sPLT';
  2924. end;
  2925. function TChunkPngSuggestedPalette.GetCount: Cardinal;
  2926. begin
  2927. Result := FCount;
  2928. end;
  2929. function TChunkPngSuggestedPalette.GetChunkSize: Cardinal;
  2930. begin
  2931. Result := Cardinal(Length(FPaletteName)) + 2 +
  2932. (4 * (FSampleDepth shr 3) + 2) * Count;
  2933. end;
  2934. procedure TChunkPngSuggestedPalette.ReadFromStream(Stream: TStream;
  2935. ChunkSize: Cardinal);
  2936. var
  2937. Index : Integer;
  2938. DataSize : Integer;
  2939. begin
  2940. if (Stream.Position+ChunkSize > Stream.Size) or (GetChunkSize > ChunkSize) then
  2941. raise EPngError.Create(RCStrChunkSizeTooSmall);
  2942. // read palette name
  2943. Index := 1;
  2944. SetLength(FPaletteName, 80);
  2945. while (Stream.Position < ChunkSize) do
  2946. begin
  2947. Stream.Read(FPaletteName[Index], SizeOf(Byte));
  2948. if FPaletteName[Index] = #0 then
  2949. begin
  2950. SetLength(FPaletteName, Index - 1);
  2951. Break;
  2952. end;
  2953. Inc(Index);
  2954. end;
  2955. // read sample depth
  2956. Stream.Read(FSampleDepth, 1);
  2957. DataSize := Integer(ChunkSize) - Length(FPaletteName) - 2;
  2958. Assert(DataSize >= 0);
  2959. Assert(DataSize mod 2 = 0);
  2960. Assert(DataSize mod (4 * (FSampleDepth shr 3) + 2) = 0);
  2961. FCount := DataSize div (4 * (FSampleDepth shr 3) + 2);
  2962. ReallocMem(FData, DataSize);
  2963. if FSampleDepth = 8 then
  2964. for Index := 0 to FCount - 1 do
  2965. with PSuggestedPalette8ByteArray(FData)^[Index] do
  2966. begin
  2967. Stream.Read(Red, 1);
  2968. Stream.Read(Green, 1);
  2969. Stream.Read(Blue, 1);
  2970. Stream.Read(Alpha, 1);
  2971. Frequency := BigEndian.ReadWord(Stream);
  2972. end
  2973. else if FSampleDepth = 16 then
  2974. for Index := 0 to FCount - 1 do
  2975. with PSuggestedPalette16ByteArray(FData)^[Index] do
  2976. begin
  2977. Red := BigEndian.ReadWord(Stream);
  2978. Green := BigEndian.ReadWord(Stream);
  2979. Blue := BigEndian.ReadWord(Stream);
  2980. Alpha := BigEndian.ReadWord(Stream);
  2981. Frequency := BigEndian.ReadWord(Stream);
  2982. end;
  2983. end;
  2984. procedure TChunkPngSuggestedPalette.WriteToStream(Stream: TStream);
  2985. begin
  2986. // TODO
  2987. raise EPngError.CreateFmt(RCStrChunkNotImplemented, [ChunkNameAsString]);
  2988. end;
  2989. {$endif PNG_CHUNK_SUGGESTED_PALETTE}
  2990. { TChunkList }
  2991. destructor TChunkList.Destroy;
  2992. begin
  2993. Clear;
  2994. inherited;
  2995. end;
  2996. procedure TChunkList.Add(Item: TCustomChunk);
  2997. begin
  2998. SetLength(FChunks, Length(FChunks) + 1);
  2999. FChunks[Length(FChunks) - 1] := Item;
  3000. end;
  3001. procedure TChunkList.AssignTo(Dest: TPersistent);
  3002. var
  3003. Index : Integer;
  3004. ChunkClass : TCustomDefinedChunkWithHeaderClass;
  3005. begin
  3006. if Dest is TChunkList then
  3007. with TChunkList(Dest) do
  3008. begin
  3009. Clear;
  3010. SetLength(FChunks, Self.Count);
  3011. for Index := 0 to Self.Count - 1 do
  3012. if Self.FChunks[Index] is TCustomDefinedChunkWithHeader then
  3013. begin
  3014. ChunkClass := TCustomDefinedChunkWithHeaderClass(Self.FChunks[Index].ClassType);
  3015. FChunks[Index] := ChunkClass.Create(TCustomDefinedChunkWithHeader(Self.FChunks[Index]).FHeader);
  3016. FChunks[Index].Assign(Self.FChunks[Index]);
  3017. end
  3018. else
  3019. inherited;
  3020. end
  3021. else
  3022. inherited;
  3023. end;
  3024. procedure TChunkList.Clear;
  3025. var
  3026. Index : Integer;
  3027. begin
  3028. for Index := 0 to Count - 1 do
  3029. FChunks[Index].Free;
  3030. SetLength(FChunks, 0)
  3031. end;
  3032. procedure TChunkList.Delete(Index: Cardinal);
  3033. begin
  3034. if Index >= Count then
  3035. raise EPngError.Create(RCStrEmptyChunkList);
  3036. FChunks[Index].Free;
  3037. if Index < Count then
  3038. System.Move(FChunks[Index + 1], FChunks[Index], (Count - Index) * SizeOf(Pointer));
  3039. SetLength(FChunks, Length(FChunks) - 1);
  3040. end;
  3041. function TChunkList.GetChunk(Index: Integer): TCustomChunk;
  3042. begin
  3043. if Cardinal(Index) >= Cardinal(Count) then
  3044. raise EPngError.CreateFmt(RCStrIndexOutOfBounds, [Index])
  3045. else
  3046. Result := FChunks[Index];
  3047. end;
  3048. function TChunkList.GetCount: Cardinal;
  3049. begin
  3050. Result := Length(FChunks);
  3051. end;
  3052. function TChunkList.IndexOf(Item: TCustomChunk): Integer;
  3053. begin
  3054. for Result := 0 to Count - 1 do
  3055. if FChunks[Result] = Item then
  3056. Exit;
  3057. Result := -1;
  3058. end;
  3059. procedure TChunkList.Remove(Item: TCustomChunk);
  3060. begin
  3061. Delete(IndexOf(Item));
  3062. end;
  3063. { TCustomPngCoder }
  3064. constructor TCustomPngCoder.Create(Stream: TStream;
  3065. Header: TChunkPngImageHeader; Gamma: TChunkPngGamma = nil;
  3066. Palette: TChunkPngPalette = nil; Transparency : TCustomPngTransparency = nil);
  3067. begin
  3068. FStream := Stream;
  3069. FHeader := Header;
  3070. FGamma := Gamma;
  3071. FPalette := Palette;
  3072. FTransparency := Transparency;
  3073. FMappingTable := nil;
  3074. FAlphaTable := nil;
  3075. BuildMappingTables;
  3076. inherited Create;
  3077. end;
  3078. destructor TCustomPngCoder.Destroy;
  3079. begin
  3080. Dispose(FMappingTable);
  3081. Dispose(FAlphaTable);
  3082. inherited;
  3083. end;
  3084. procedure TCustomPngCoder.BuildMappingTables;
  3085. var
  3086. Index : Integer;
  3087. Palette : PRGB24Array;
  3088. FracVal : Single;
  3089. Color : TRGB24;
  3090. MaxByte : Byte;
  3091. PreCalcGamma : Extended;
  3092. const
  3093. COne255th : Extended = 1 / 255;
  3094. begin
  3095. if FHeader.HasPalette then
  3096. begin
  3097. if (FPalette <> nil) then
  3098. begin
  3099. GetMem(FMappingTable, FPalette.Count * SizeOf(TRGB24));
  3100. Palette := PRGB24Array(FMappingTable);
  3101. if (FGamma <> nil) then
  3102. begin
  3103. PreCalcGamma := 1 / (FGamma.Gamma * 2.2E-5);
  3104. for Index := 0 to FPalette.Count - 1 do
  3105. begin
  3106. Color := FPalette.PaletteEntry[Index];
  3107. Palette[Index].R := Round(Power((Color.R * COne255th), PreCalcGamma) * 255);
  3108. Palette[Index].G := Round(Power((Color.G * COne255th), PreCalcGamma) * 255);
  3109. Palette[Index].B := Round(Power((Color.B * COne255th), PreCalcGamma) * 255);
  3110. end;
  3111. end
  3112. else
  3113. for Index := 0 to FPalette.Count - 1 do
  3114. Palette[Index] := FPalette.PaletteEntry[Index];
  3115. end
  3116. else
  3117. begin
  3118. // create gray scale palette
  3119. GetMem(FMappingTable, 256 * SizeOf(TRGB24));
  3120. Palette := PRGB24Array(FMappingTable);
  3121. MaxByte := ((1 shl FHeader.BitDepth) - 1) and $FF;
  3122. FracVal := 1 / MaxByte;
  3123. if (FGamma <> nil) then
  3124. begin
  3125. PreCalcGamma := 1 / (FGamma.Gamma * 2.2E-5);
  3126. for Index := 0 to FPalette.Count - 1 do
  3127. begin
  3128. Palette[Index].R := Round(Power(Index * FracVal, PreCalcGamma) * 255);
  3129. Palette[Index].G := Palette[Index].R;
  3130. Palette[Index].B := Palette[Index].B;
  3131. end;
  3132. end
  3133. else
  3134. begin
  3135. for Index := 0 to MaxByte do
  3136. begin
  3137. Palette[Index].R := Round(255 * (Index * FracVal));
  3138. Palette[Index].G := Palette[Index].R;
  3139. Palette[Index].B := Palette[Index].R;
  3140. end;
  3141. end;
  3142. end;
  3143. // build alpha table
  3144. GetMem(FAlphaTable, 256);
  3145. FillChar(FAlphaTable^, 256, $FF);
  3146. // eventually fill alpha table
  3147. if FTransparency is TPngTransparencyFormat3 then
  3148. with TPngTransparencyFormat3(FTransparency) do
  3149. for Index := 0 to Count - 1 do
  3150. FAlphaTable[Index] := Transparency[Index];
  3151. end
  3152. else
  3153. begin
  3154. GetMem(FMappingTable, 256);
  3155. if (FGamma <> nil) and (FGamma.Gamma <> 0) then
  3156. begin
  3157. PreCalcGamma := 1 / (FGamma.Gamma * 2.2E-5);
  3158. for Index := 0 to $FF do
  3159. FMappingTable[Index] := Round(Power((Index * COne255th), PreCalcGamma) * 255);
  3160. end
  3161. else
  3162. for Index := 0 to $FF do
  3163. FMappingTable[Index] := Index;
  3164. end;
  3165. end;
  3166. procedure TCustomPngCoder.DecodeFilterSub(CurrentRow, PreviousRow: PByteArray;
  3167. BytesPerRow, PixelByteSize: NativeInt);
  3168. {$IFDEF PUREPASCAL}
  3169. var
  3170. Index : Integer;
  3171. begin
  3172. for Index := PixelByteSize + 1 to BytesPerRow do
  3173. CurrentRow[Index] := (CurrentRow[Index] + CurrentRow[Index - PixelByteSize]) and $FF;
  3174. {$ELSE}
  3175. asm
  3176. {$IFDEF Target_x64}
  3177. // RCX = Self
  3178. // RDX = CurrentRow
  3179. // R9 = BytesPerRow
  3180. ADD RDX, 1
  3181. MOV RAX, RDX
  3182. MOV RCX, BytesPerRow
  3183. ADD RAX, PixelByteSize
  3184. SUB RCX, PixelByteSize
  3185. LEA RAX, [RAX + RCX]
  3186. LEA RDX, [RDX + RCX]
  3187. NEG RCX
  3188. JNL @Done
  3189. @Start:
  3190. MOV R8B, [RAX + RCX].Byte
  3191. ADD R8B, [RDX + RCX].Byte
  3192. MOV [RAX + RCX].Byte, R8B
  3193. ADD RCX, 1
  3194. JS @Start
  3195. @Done:
  3196. {$ENDIF}
  3197. {$IFDEF Target_x86}
  3198. ADD EDX, 1
  3199. MOV EAX, EDX
  3200. MOV ECX, BytesPerRow.DWORD
  3201. ADD EAX, PixelByteSize.DWORD
  3202. SUB ECX, PixelByteSize.DWORD
  3203. LEA EAX, [EAX + ECX]
  3204. LEA EDX, [EDX + ECX]
  3205. NEG ECX
  3206. JNL @Done
  3207. PUSH EBX
  3208. @Start:
  3209. MOV BL, [EAX + ECX].Byte
  3210. ADD BL, [EDX + ECX].Byte
  3211. MOV [EAX + ECX].Byte, BL
  3212. ADD ECX, 1
  3213. JS @Start
  3214. POP EBX
  3215. @Done:
  3216. {$ENDIF}
  3217. {$ENDIF}
  3218. end;
  3219. procedure TCustomPngCoder.DecodeFilterUp(CurrentRow, PreviousRow: PByteArray;
  3220. BytesPerRow, PixelByteSize: NativeInt);
  3221. {$IFDEF PUREPASCAL}
  3222. var
  3223. Index : Integer;
  3224. begin
  3225. for Index := 1 to BytesPerRow do
  3226. CurrentRow[Index] := (CurrentRow[Index] + PreviousRow[Index]) and $FF;
  3227. {$ELSE}
  3228. asm
  3229. {$IFDEF Target_x64}
  3230. // RCX = Self
  3231. // RDX = CurrentRow
  3232. // R8 = PreviousRow
  3233. // R9 = BytesPerRow
  3234. MOV RAX, RDX
  3235. MOV RDX, R8
  3236. MOV RCX, BytesPerRow
  3237. LEA RAX, [RAX + RCX + 1]
  3238. LEA RDX, [RDX + RCX + 1]
  3239. NEG RCX
  3240. JNL @Done
  3241. @Start:
  3242. MOV R8B, [RAX + RCX].Byte
  3243. ADD R8B, [RDX + RCX].Byte
  3244. MOV [RAX + RCX].Byte, R8B
  3245. ADD RCX, 1
  3246. JS @Start
  3247. @Done:
  3248. {$ENDIF}
  3249. {$IFDEF Target_x86}
  3250. MOV EAX, EDX
  3251. MOV EDX, ECX
  3252. MOV ECX, BytesPerRow.DWORD
  3253. LEA EAX, [EAX + ECX + 1]
  3254. LEA EDX, [EDX + ECX + 1]
  3255. NEG ECX
  3256. JNL @Done
  3257. PUSH EBX
  3258. @Start:
  3259. MOV BL, [EAX + ECX].Byte
  3260. ADD BL, [EDX + ECX].Byte
  3261. MOV [EAX + ECX].Byte, BL
  3262. ADD ECX, 1
  3263. JS @Start
  3264. POP EBX
  3265. @Done:
  3266. {$ENDIF}
  3267. {$ENDIF}
  3268. end;
  3269. procedure TCustomPngCoder.DecodeFilterAverage(CurrentRow, PreviousRow: PByteArray;
  3270. BytesPerRow, PixelByteSize: NativeInt);
  3271. var
  3272. Index : Integer;
  3273. begin
  3274. for Index := 1 to PixelByteSize do
  3275. CurrentRow[Index] := (CurrentRow[Index] + PreviousRow[Index] shr 1) and $FF;
  3276. for Index := PixelByteSize + 1 to BytesPerRow do
  3277. CurrentRow[Index] := (CurrentRow[Index] +
  3278. (CurrentRow[Index - PixelByteSize] + PreviousRow[Index]) shr 1) and $FF;
  3279. end;
  3280. function PaethPredictor(a, b, c: Byte): Integer; {$IFNDEF TARGET_x64} pascal; {$ENDIF}
  3281. {$IFDEF PUREPASCAL}
  3282. var
  3283. DistA, DistB, DistC: Integer;
  3284. begin
  3285. DistA := Abs(b - c);
  3286. DistB := Abs(a - c);
  3287. DistC := Abs(a + b - c * 2);
  3288. if (DistA <= DistB) and (DistA <= DistC) then Result := a else
  3289. if DistB <= DistC then
  3290. Result := b
  3291. else
  3292. Result := c;
  3293. {$ELSE}
  3294. asm
  3295. {$IFDEF TARGET_x64}
  3296. // RCX = a
  3297. // RDX = b
  3298. // R8 = c
  3299. // calculate DistA = Abs(b - c)
  3300. MOVZX RAX, DL // RAX = b
  3301. SUB RAX, R8 // RAX = b - c
  3302. MOV R10, RAX // R10 = b - c
  3303. JAE @PositiveDistA // if R10 >= 0 then
  3304. NOT RAX // ...
  3305. INC RAX // RAX = Abs(b - c) = DistA
  3306. @PositiveDistA:
  3307. // calculate DistB = Abs(a - c)
  3308. MOVZX R11, CL // R11 = a
  3309. SUB R11, R8 // R11 = a - c
  3310. MOV R9, R11 // R9 = a - c
  3311. JAE @PositiveDistB // if R9 >= 0 then
  3312. NOT R11 // ...
  3313. INC R11 // R11 = Abs(a - c) = DistB
  3314. @PositiveDistB:
  3315. // calculate DistC = Abs(a + b - c * 2)
  3316. ADD R10, R9 // R10 = b - c + a - c = a + b - 2 * c
  3317. JNL @PositiveDistC // if R10 >= 0 then
  3318. NOT R10 // ...
  3319. INC R10 // R10 = Abs(a + b - c * 2) = DistC
  3320. @PositiveDistC:
  3321. MOV R9, RAX // R9 = DistA
  3322. SUB R9, R11 // R9 = DistA - DistB
  3323. JA @NextCheck // if (DistA <= DistB) then
  3324. MOV R9, RAX // R9 = DistA
  3325. SUB R9, R10 // R9 = DistA - DistC
  3326. JA @NextCheck // if (DistA <= DistC) then
  3327. MOV RAX, RCX // RAX = a
  3328. JMP @Done // Exit
  3329. @NextCheck:
  3330. MOV R9, R11 // R9 = DistB
  3331. SUB R9, R10 // R9 = DistB - DistC
  3332. JA @ResultC // if (DistB <= DistC) then
  3333. MOV RAX, RDX // RAX = b
  3334. JMP @Done
  3335. @ResultC:
  3336. MOV RAX, R8 // RAX = c
  3337. @Done:
  3338. {$ELSE}
  3339. MOVZX EDX, c
  3340. PUSH EBX
  3341. MOVZX EAX, b
  3342. SUB EAX, EDX
  3343. JAE @PositiveDistA
  3344. NOT EAX
  3345. INC EAX
  3346. @PositiveDistA:
  3347. MOVZX EBX, a
  3348. SUB EBX, EDX
  3349. JAE @PositiveDistB
  3350. NOT EBX
  3351. INC EBX
  3352. @PositiveDistB:
  3353. MOVZX ECX, a
  3354. SUB ECX, EDX
  3355. MOVZX EDX, b
  3356. ADD ECX, EDX
  3357. MOVZX EDX, c
  3358. SUB ECX, EDX
  3359. JAE @PositiveDistC
  3360. NOT ECX
  3361. INC ECX
  3362. @PositiveDistC:
  3363. MOV EDX, EAX
  3364. SUB EDX, EBX
  3365. JA @NextCheck
  3366. MOV EDX, EAX
  3367. SUB EDX, ECX
  3368. JA @NextCheck
  3369. MOVZX EDX, a
  3370. MOV Result, EDX
  3371. JMP @Done
  3372. @NextCheck:
  3373. MOV EDX, EBX
  3374. SUB EDX, ECX
  3375. JA @ResultC
  3376. MOVZX EDX, b
  3377. MOV Result, EDX
  3378. JMP @Done
  3379. @ResultC:
  3380. MOVZX EDX, c
  3381. MOV Result, EDX
  3382. @Done:
  3383. POP EBX
  3384. {$ENDIF}
  3385. {$ENDIF}
  3386. end;
  3387. procedure TCustomPngCoder.DecodeFilterPaeth(CurrentRow, PreviousRow: PByteArray;
  3388. BytesPerRow, PixelByteSize: NativeInt);
  3389. var
  3390. Index : Integer;
  3391. begin
  3392. DecodeFilterUp(CurrentRow, PreviousRow, PixelByteSize, PixelByteSize);
  3393. for Index := PixelByteSize + 1 to BytesPerRow do
  3394. CurrentRow[Index] := (CurrentRow[Index] +
  3395. PaethPredictor(CurrentRow[Index - PixelByteSize], PreviousRow[Index],
  3396. PreviousRow[Index - PixelByteSize])) and $FF;
  3397. end;
  3398. procedure TCustomPngCoder.EncodeFilterSub(CurrentRow, PreviousRow, OutputRow: PByteArray;
  3399. BytesPerRow, PixelByteSize: Integer);
  3400. var
  3401. Index : Integer;
  3402. begin
  3403. // copy first pixel
  3404. Move(CurrentRow[1], OutputRow[1], PixelByteSize);
  3405. for Index := PixelByteSize + 1 to BytesPerRow do
  3406. OutputRow[Index] := (CurrentRow[Index] - CurrentRow[Index - PixelByteSize]) and $FF;
  3407. end;
  3408. procedure TCustomPngCoder.EncodeFilterUp(CurrentRow, PreviousRow, OutputRow: PByteArray;
  3409. BytesPerRow, PixelByteSize: Integer);
  3410. var
  3411. Index : Integer;
  3412. begin
  3413. for Index := 1 to BytesPerRow do
  3414. OutputRow[Index] := (CurrentRow[Index] - PreviousRow[Index]) and $FF;
  3415. end;
  3416. procedure TCustomPngCoder.EncodeFilterAverage(CurrentRow, PreviousRow, OutputRow: PByteArray;
  3417. BytesPerRow, PixelByteSize: Integer);
  3418. var
  3419. Index : Integer;
  3420. begin
  3421. for Index := 1 to PixelByteSize do
  3422. OutputRow[Index] := (CurrentRow[Index] - PreviousRow[Index] shr 1) and $FF;
  3423. for Index := PixelByteSize + 1 to BytesPerRow do
  3424. OutputRow[Index] := (CurrentRow[Index] - (CurrentRow[Index - PixelByteSize] + PreviousRow[Index]) shr 1) and $FF;
  3425. end;
  3426. procedure TCustomPngCoder.EncodeFilterPaeth(CurrentRow, PreviousRow, OutputRow: PByteArray;
  3427. BytesPerRow, PixelByteSize: Integer);
  3428. var
  3429. Index : Integer;
  3430. begin
  3431. EncodeFilterUp(CurrentRow, PreviousRow, OutputRow, PixelByteSize, PixelByteSize);
  3432. for Index := PixelByteSize + 1 to BytesPerRow do
  3433. OutputRow[Index] := (CurrentRow[Index] -
  3434. PaethPredictor(CurrentRow[Index - PixelByteSize], PreviousRow[Index],
  3435. PreviousRow[Index - PixelByteSize])) and $FF;
  3436. end;
  3437. { TCustomPngDecoder }
  3438. procedure TCustomPngDecoder.DecodeFilterRow(FilterMethod: TAdaptiveFilterMethod;
  3439. CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: Integer);
  3440. begin
  3441. case FilterMethod of
  3442. afmNone : ;
  3443. afmSub : DecodeFilterSub(CurrentRow, PreviousRow, BytesPerRow, PixelByteSize);
  3444. afmUp : DecodeFilterUp(CurrentRow, PreviousRow, BytesPerRow, PixelByteSize);
  3445. afmAverage : DecodeFilterAverage(CurrentRow, PreviousRow, BytesPerRow, PixelByteSize);
  3446. afmPaeth : DecodeFilterPaeth(CurrentRow, PreviousRow, BytesPerRow, PixelByteSize);
  3447. else
  3448. raise EPngError.Create(RCStrUnsupportedFilter);
  3449. end;
  3450. end;
  3451. procedure TCustomPngDecoder.EncodeFilterRow(CurrentRow, PreviousRow, OutputRow,
  3452. TempBuffer: PByteArray; BytesPerRow, PixelByteSize: Integer);
  3453. begin
  3454. raise Exception.Create('Class is only meant for decoding');
  3455. end;
  3456. { TCustomPngEncoder }
  3457. function CalculateRowSum(CurrentRow: PByteArray; BytesPerRow: Integer): Cardinal;
  3458. var
  3459. Index : Integer;
  3460. begin
  3461. Result := 0;
  3462. for Index := 1 to BytesPerRow do
  3463. Result := Result + Cardinal(Abs(SmallInt(CurrentRow[Index])));
  3464. end;
  3465. procedure TCustomPngEncoder.EncodeFilterRow(CurrentRow, PreviousRow,
  3466. OutputRow, TempBuffer: PByteArray; BytesPerRow, PixelByteSize: Integer);
  3467. var
  3468. PixelIndex : Integer;
  3469. CurrentSum : Cardinal;
  3470. BestSum : Cardinal;
  3471. begin
  3472. BestSum := 0;
  3473. OutputRow^[0] := 0;
  3474. for PixelIndex := 1 to BytesPerRow do
  3475. BestSum := BestSum + CurrentRow[PixelIndex];
  3476. Move(CurrentRow^[1], OutputRow^[1], BytesPerRow);
  3477. // check whether sub pre filter shall be used
  3478. if aafmSub in FHeader.AdaptiveFilterMethods then
  3479. begin
  3480. // calculate sub filter
  3481. EncodeFilterSub(CurrentRow, PreviousRow, TempBuffer, BytesPerRow, PixelByteSize);
  3482. CurrentSum := CalculateRowSum(TempBuffer, BytesPerRow);
  3483. // check if sub filter is the current best filter
  3484. if CurrentSum < BestSum then
  3485. begin
  3486. BestSum := CurrentSum;
  3487. Move(TempBuffer^[1], OutputRow^[1], BytesPerRow);
  3488. OutputRow^[0] := 1;
  3489. end;
  3490. end;
  3491. // check whether up pre filter shall be used
  3492. if aafmUp in FHeader.AdaptiveFilterMethods then
  3493. begin
  3494. // calculate up filter
  3495. EncodeFilterUp(CurrentRow, PreviousRow, TempBuffer, BytesPerRow, PixelByteSize);
  3496. CurrentSum := CalculateRowSum(TempBuffer, BytesPerRow);
  3497. // check if up filter is the current best filter
  3498. if CurrentSum < BestSum then
  3499. begin
  3500. BestSum := CurrentSum;
  3501. Move(TempBuffer^[1], OutputRow^[1], BytesPerRow);
  3502. OutputRow^[0] := 2;
  3503. end;
  3504. end;
  3505. // check whether average pre filter shall be used
  3506. if aafmAverage in FHeader.AdaptiveFilterMethods then
  3507. begin
  3508. // calculate average filter
  3509. EncodeFilterAverage(CurrentRow, PreviousRow, TempBuffer, BytesPerRow, PixelByteSize);
  3510. CurrentSum := CalculateRowSum(TempBuffer, BytesPerRow);
  3511. // check if average filter is the current best filter
  3512. if CurrentSum < BestSum then
  3513. begin
  3514. BestSum := CurrentSum;
  3515. Move(TempBuffer^[1], OutputRow^[1], BytesPerRow);
  3516. OutputRow^[0] := 3;
  3517. end;
  3518. end;
  3519. // check whether paeth pre filter shall be used
  3520. if aafmPaeth in FHeader.AdaptiveFilterMethods then
  3521. begin
  3522. // calculate paeth filter
  3523. EncodeFilterPaeth(CurrentRow, PreviousRow, TempBuffer, BytesPerRow, PixelByteSize);
  3524. CurrentSum := CalculateRowSum(TempBuffer, BytesPerRow);
  3525. // check if paeth filter is the current best filter
  3526. if CurrentSum < BestSum then
  3527. begin
  3528. Move(TempBuffer^[1], OutputRow^[1], BytesPerRow);
  3529. OutputRow^[0] := 4;
  3530. end;
  3531. end;
  3532. end;
  3533. procedure TCustomPngEncoder.DecodeFilterRow(FilterMethod: TAdaptiveFilterMethod;
  3534. CurrentRow, PreviousRow: PByteArray; BytesPerRow, PixelByteSize: Integer);
  3535. begin
  3536. raise Exception.Create('Class is only meant for encoding');
  3537. end;
  3538. { TCustomPngTranscoder }
  3539. constructor TCustomPngTranscoder.Create(Stream: TStream;
  3540. Header: TChunkPngImageHeader; Gamma: TChunkPngGamma = nil;
  3541. Palette: TChunkPngPalette = nil; Transparency: TCustomPngTransparency = nil);
  3542. begin
  3543. inherited;
  3544. GetMem(FRowBuffer[0], FHeader.BytesPerRow + 1);
  3545. GetMem(FRowBuffer[1], FHeader.BytesPerRow + 1);
  3546. end;
  3547. destructor TCustomPngTranscoder.Destroy;
  3548. begin
  3549. Dispose(FRowBuffer[0]);
  3550. Dispose(FRowBuffer[1]);
  3551. inherited;
  3552. end;
  3553. procedure TCustomPngTranscoder.DecodeFilterRow(
  3554. FilterMethod: TAdaptiveFilterMethod; CurrentRow, PreviousRow: PByteArray;
  3555. BytesPerRow, PixelByteSize: Integer);
  3556. begin
  3557. case FilterMethod of
  3558. afmNone : ;
  3559. afmSub : DecodeFilterSub(CurrentRow, PreviousRow, BytesPerRow, PixelByteSize);
  3560. afmUp : DecodeFilterUp(CurrentRow, PreviousRow, BytesPerRow, PixelByteSize);
  3561. afmAverage : DecodeFilterAverage(CurrentRow, PreviousRow, BytesPerRow, PixelByteSize);
  3562. afmPaeth : DecodeFilterPaeth(CurrentRow, PreviousRow, BytesPerRow, PixelByteSize);
  3563. else
  3564. raise EPngError.Create(RCStrUnsupportedFilter);
  3565. end;
  3566. end;
  3567. procedure TCustomPngTranscoder.EncodeFilterRow(CurrentRow, PreviousRow,
  3568. OutputRow, TempBuffer: PByteArray; BytesPerRow, PixelByteSize: Integer);
  3569. var
  3570. PixelIndex : Integer;
  3571. CurrentSum : Cardinal;
  3572. BestSum : Cardinal;
  3573. begin
  3574. BestSum := 0;
  3575. OutputRow^[0] := 0;
  3576. for PixelIndex := 1 to BytesPerRow do
  3577. BestSum := BestSum + CurrentRow[PixelIndex];
  3578. Move(CurrentRow^[1], OutputRow^[1], BytesPerRow);
  3579. // check whether sub pre filter shall be used
  3580. if aafmSub in FHeader.AdaptiveFilterMethods then
  3581. begin
  3582. // calculate sub filter
  3583. EncodeFilterSub(CurrentRow, PreviousRow, TempBuffer, BytesPerRow, PixelByteSize);
  3584. CurrentSum := CalculateRowSum(TempBuffer, BytesPerRow);
  3585. // check if sub filter is the current best filter
  3586. if CurrentSum < BestSum then
  3587. begin
  3588. BestSum := CurrentSum;
  3589. Move(TempBuffer^[1], OutputRow^[1], BytesPerRow);
  3590. OutputRow^[0] := 1;
  3591. end;
  3592. end;
  3593. // check whether up pre filter shall be used
  3594. if aafmUp in FHeader.AdaptiveFilterMethods then
  3595. begin
  3596. // calculate up filter
  3597. EncodeFilterUp(CurrentRow, PreviousRow, TempBuffer, BytesPerRow, PixelByteSize);
  3598. CurrentSum := CalculateRowSum(TempBuffer, BytesPerRow);
  3599. // check if up filter is the current best filter
  3600. if CurrentSum < BestSum then
  3601. begin
  3602. BestSum := CurrentSum;
  3603. Move(TempBuffer^[1], OutputRow^[1], BytesPerRow);
  3604. OutputRow^[0] := 2;
  3605. end;
  3606. end;
  3607. // check whether average pre filter shall be used
  3608. if aafmAverage in FHeader.AdaptiveFilterMethods then
  3609. begin
  3610. // calculate average filter
  3611. EncodeFilterAverage(CurrentRow, PreviousRow, TempBuffer, BytesPerRow, PixelByteSize);
  3612. CurrentSum := CalculateRowSum(TempBuffer, BytesPerRow);
  3613. // check if average filter is the current best filter
  3614. if CurrentSum < BestSum then
  3615. begin
  3616. BestSum := CurrentSum;
  3617. Move(TempBuffer^[1], OutputRow^[1], BytesPerRow);
  3618. OutputRow^[0] := 3;
  3619. end;
  3620. end;
  3621. // check whether paeth pre filter shall be used
  3622. if aafmPaeth in FHeader.AdaptiveFilterMethods then
  3623. begin
  3624. // calculate paeth filter
  3625. EncodeFilterPaeth(CurrentRow, PreviousRow, TempBuffer, BytesPerRow, PixelByteSize);
  3626. CurrentSum := CalculateRowSum(TempBuffer, BytesPerRow);
  3627. // check if paeth filter is the current best filter
  3628. if CurrentSum < BestSum then
  3629. begin
  3630. Move(TempBuffer^[1], OutputRow^[1], BytesPerRow);
  3631. OutputRow^[0] := 4;
  3632. end;
  3633. end;
  3634. end;
  3635. { TPortableNetworkGraphic }
  3636. constructor TPortableNetworkGraphic.Create;
  3637. begin
  3638. FImageHeader := TChunkPngImageHeader.Create;
  3639. FDataChunkList := TChunkList.Create;
  3640. FAdditionalChunkList := TChunkList.Create;
  3641. FCompressionLevel := Z_BEST_COMPRESSION;
  3642. inherited;
  3643. end;
  3644. destructor TPortableNetworkGraphic.Destroy;
  3645. begin
  3646. FAdditionalChunkList.Clear;
  3647. FAdditionalChunkList.Free;
  3648. FDataChunkList.Free;
  3649. FImageHeader.Free;
  3650. FPaletteChunk.Free;
  3651. FGammaChunk.Free;
  3652. FTimeChunk.Free;
  3653. FSignificantBits.Free;
  3654. FPhysicalDimensions.Free;
  3655. FChromaChunk.Free;
  3656. FTransparencyChunk.Free;
  3657. FBackgroundChunk.Free;
  3658. inherited;
  3659. end;
  3660. procedure TPortableNetworkGraphic.SetPaletteChunk(
  3661. const Value: TChunkPngPalette);
  3662. begin
  3663. if (FPaletteChunk <> nil) then
  3664. if (Value <> nil) then
  3665. FPaletteChunk.Assign(Value)
  3666. else
  3667. FreeAndNil(FPaletteChunk)
  3668. else
  3669. if (Value <> nil) then
  3670. begin
  3671. FPaletteChunk := TChunkPngPalette.Create(FImageHeader);
  3672. FPaletteChunk.Assign(Value);
  3673. end;
  3674. end;
  3675. procedure TPortableNetworkGraphic.SetPhysicalDimensions(
  3676. const Value: TChunkPngPhysicalPixelDimensions);
  3677. begin
  3678. if (FPhysicalDimensions <> nil) then
  3679. if (Value <> nil) then
  3680. FPhysicalDimensions.Assign(Value)
  3681. else
  3682. FreeAndNil(FPhysicalDimensions)
  3683. else
  3684. if (Value <> nil) then
  3685. begin
  3686. FPhysicalDimensions := TChunkPngPhysicalPixelDimensions.Create(FImageHeader);
  3687. FPhysicalDimensions.Assign(Value);
  3688. end;
  3689. end;
  3690. procedure TPortableNetworkGraphic.SetSignificantBits(
  3691. const Value: TChunkPngSignificantBits);
  3692. begin
  3693. if (FSignificantBits <> nil) then
  3694. if (Value <> nil) then
  3695. FSignificantBits.Assign(Value)
  3696. else
  3697. FreeAndNil(FSignificantBits)
  3698. else
  3699. if (Value <> nil) then
  3700. begin
  3701. FSignificantBits := TChunkPngSignificantBits.Create(FImageHeader);
  3702. FSignificantBits.Assign(Value);
  3703. end;
  3704. end;
  3705. procedure TPortableNetworkGraphic.SetTimeChunk(const Value: TChunkPngTime);
  3706. begin
  3707. if (FTimeChunk <> nil) then
  3708. if (Value <> nil) then
  3709. FTimeChunk.Assign(Value)
  3710. else
  3711. FreeAndNil(FTimeChunk)
  3712. else
  3713. if (Value <> nil) then
  3714. begin
  3715. FTimeChunk := TChunkPngTime.Create(FImageHeader);
  3716. FTimeChunk.Assign(Value);
  3717. end;
  3718. end;
  3719. procedure TPortableNetworkGraphic.SetTransparencyChunk(
  3720. const Value: TChunkPngTransparency);
  3721. begin
  3722. if (FTransparencyChunk <> nil) then
  3723. if (Value <> nil) then
  3724. FTransparencyChunk.Assign(Value)
  3725. else
  3726. FreeAndNil(FTransparencyChunk)
  3727. else
  3728. if (Value <> nil) then
  3729. begin
  3730. FTransparencyChunk := TChunkPngTransparency.Create(FImageHeader);
  3731. FTransparencyChunk.Assign(Value);
  3732. end;
  3733. end;
  3734. procedure TPortableNetworkGraphic.SetPixelsPerUnitX(const Value: Cardinal);
  3735. begin
  3736. if Value = 0 then
  3737. raise EPngError.Create(RCStrWrongPixelPerUnit);
  3738. if not (FPhysicalDimensions <> nil) then
  3739. FPhysicalDimensions := TChunkPngPhysicalPixelDimensions.Create(FImageHeader);
  3740. FPhysicalDimensions.PixelsPerUnitX := Value;
  3741. end;
  3742. procedure TPortableNetworkGraphic.SetPixelsPerUnitY(const Value: Cardinal);
  3743. begin
  3744. if Value = 0 then
  3745. raise EPngError.Create(RCStrWrongPixelPerUnit);
  3746. if not (FPhysicalDimensions <> nil) then
  3747. FPhysicalDimensions := TChunkPngPhysicalPixelDimensions.Create(FImageHeader);
  3748. FPhysicalDimensions.PixelsPerUnitY := Value;
  3749. end;
  3750. procedure TPortableNetworkGraphic.SetPixelUnit(const Value: Byte);
  3751. begin
  3752. if Value > 1 then
  3753. raise EPngError.Create(RCStrUnspecifiedPixelUnit);
  3754. if not (FPhysicalDimensions <> nil) then
  3755. FPhysicalDimensions := TChunkPngPhysicalPixelDimensions.Create(FImageHeader);
  3756. FPhysicalDimensions.PixelUnit := Value;
  3757. end;
  3758. procedure TPortableNetworkGraphic.SetChromaChunk(
  3759. const Value: TChunkPngPrimaryChromaticities);
  3760. begin
  3761. if (FChromaChunk <> nil) then
  3762. if (Value <> nil) then
  3763. FChromaChunk.Assign(Value)
  3764. else
  3765. FreeAndNil(FChromaChunk)
  3766. else
  3767. if (Value <> nil) then
  3768. begin
  3769. FChromaChunk := TChunkPngPrimaryChromaticities.Create(FImageHeader);
  3770. FChromaChunk.Assign(Value);
  3771. end;
  3772. end;
  3773. procedure TPortableNetworkGraphic.SetGammaChunk(const Value: TChunkPngGamma);
  3774. begin
  3775. if (FGammaChunk <> nil) then
  3776. if (Value <> nil) then
  3777. FGammaChunk.Assign(Value)
  3778. else
  3779. FreeAndNil(FGammaChunk)
  3780. else
  3781. if (Value <> nil) then
  3782. begin
  3783. FGammaChunk := TChunkPngGamma.Create(FImageHeader);
  3784. FGammaChunk.Assign(Value);
  3785. end;
  3786. end;
  3787. procedure TPortableNetworkGraphic.SetBackgroundChunk(
  3788. const Value: TChunkPngBackgroundColor);
  3789. begin
  3790. if (FGammaChunk <> nil) then
  3791. if (Value <> nil) then
  3792. FBackgroundChunk.Assign(Value)
  3793. else
  3794. FreeAndNil(FBackgroundChunk)
  3795. else
  3796. if (Value <> nil) then
  3797. begin
  3798. FBackgroundChunk := TChunkPngBackgroundColor.Create(FImageHeader);
  3799. FBackgroundChunk.Assign(Value);
  3800. end;
  3801. end;
  3802. procedure TPortableNetworkGraphic.SetImageHeader(
  3803. const Value: TChunkPngImageHeader);
  3804. begin
  3805. if not (Value <> nil) then
  3806. raise EPngError.Create(RCStrNewHeaderError)
  3807. else
  3808. FImageHeader.Assign(Value);
  3809. end;
  3810. procedure TPortableNetworkGraphic.SetBitDepth(const Value: Byte);
  3811. begin
  3812. raise EPngError.CreateFmt(RCStrBitDepthTranscodingError, [Value]);
  3813. end;
  3814. procedure TPortableNetworkGraphic.SetColorType(const Value: TColorType);
  3815. begin
  3816. raise EPngError.CreateFmt(RCStrColorTypeTranscodingError, [Integer(Value)]);
  3817. end;
  3818. procedure TPortableNetworkGraphic.SetFilterMethods(
  3819. const Value: TAvailableAdaptiveFilterMethods);
  3820. begin
  3821. if (FImageHeader <> nil) then
  3822. if FImageHeader.FAdaptiveFilterMethods <> Value then
  3823. begin
  3824. FImageHeader.FAdaptiveFilterMethods := Value;
  3825. AdaptiveFilterMethodsChanged;
  3826. end;
  3827. end;
  3828. procedure TPortableNetworkGraphic.SetCompressionLevel(const Value: Byte);
  3829. begin
  3830. if not (Value in [1..9]) then
  3831. raise EPngError.Create(RCStrInvalidCompressionLevel);
  3832. if FCompressionLevel <> Value then
  3833. begin
  3834. FCompressionLevel := Value;
  3835. CompressionLevelChanged;
  3836. end;
  3837. end;
  3838. procedure TPortableNetworkGraphic.SetCompressionMethod(const Value: Byte);
  3839. begin
  3840. raise EPngError.CreateFmt(RCStrDirectCompressionMethodSetError, [Value]);
  3841. end;
  3842. procedure TPortableNetworkGraphic.SetFilterMethod(const Value: TFilterMethod);
  3843. begin
  3844. raise EPngError.CreateFmt(RCStrDirectFilterMethodSetError, [Integer(Value)]);
  3845. end;
  3846. procedure TPortableNetworkGraphic.SetWidth(const Value: Integer);
  3847. begin
  3848. raise EPngError.CreateFmt(RCStrDirectWidthSetError, [Value]);
  3849. end;
  3850. procedure TPortableNetworkGraphic.SetInterlaceMethod(
  3851. const Value: TInterlaceMethod);
  3852. begin
  3853. if Value <> FImageHeader.InterlaceMethod then
  3854. begin
  3855. InterlaceMethodChanged;
  3856. FImageHeader.InterlaceMethod := Value;
  3857. end;
  3858. end;
  3859. procedure TPortableNetworkGraphic.SetModifiedTime(const Value: TDateTime);
  3860. begin
  3861. if (FTimeChunk <> nil) then
  3862. FTimeChunk.ModifiedDateTime := Value;
  3863. end;
  3864. procedure TPortableNetworkGraphic.SetGamma(const Value: Single);
  3865. begin
  3866. raise EPngError.CreateFmt(RCStrDirectGammaSetError, [Value]);
  3867. end;
  3868. procedure TPortableNetworkGraphic.SetHeight(const Value: Integer);
  3869. begin
  3870. raise EPngError.CreateFmt(RCStrDirectHeightSetError, [Value]);
  3871. end;
  3872. procedure TPortableNetworkGraphic.CopyImageData(Stream: TStream);
  3873. var
  3874. DataIndex : Integer;
  3875. begin
  3876. // combine all data chunks first
  3877. for DataIndex := 0 to FDataChunkList.Count - 1 do
  3878. begin
  3879. // make sure the chunk is inded an image data chunk
  3880. Assert(FDataChunkList[DataIndex] is TChunkPngImageData);
  3881. // concat current chunk to data stream
  3882. with TChunkPngImageData(FDataChunkList[DataIndex]) do
  3883. begin
  3884. Data.Seek(0, soFromBeginning);
  3885. Stream.CopyFrom(Data, Data.Size);
  3886. end;
  3887. end;
  3888. end;
  3889. procedure TPortableNetworkGraphic.StoreImageData(Stream: TStream);
  3890. var
  3891. DataChunk : TChunkPngImageData;
  3892. ChunkSize : Integer;
  3893. begin
  3894. // delete old image data
  3895. FDataChunkList.Clear;
  3896. ChunkSize := Stream.Size;
  3897. while Stream.Position < Stream.Size do
  3898. begin
  3899. DataChunk := TChunkPngImageData.Create(ImageHeader);
  3900. if (Stream.Size - Stream.Position) < ChunkSize then
  3901. ChunkSize := (Stream.Size - Stream.Position);
  3902. // copy data to IDAT chunk
  3903. DataChunk.Data.CopyFrom(Stream, ChunkSize);
  3904. // add data chunk to data chunk list
  3905. FDataChunkList.Add(DataChunk);
  3906. end;
  3907. end;
  3908. procedure TPortableNetworkGraphic.DecompressImageDataToStream(Stream: TStream);
  3909. var
  3910. DataStream: TMemoryStream;
  3911. begin
  3912. DataStream := TMemoryStream.Create;
  3913. try
  3914. // copy image data from all data chunks to one continous data stream
  3915. CopyImageData(DataStream);
  3916. // check whether compression method is supported
  3917. if FImageHeader.CompressionMethod <> 0 then
  3918. raise EPngError.Create(RCStrUnsupportedCompressionMethod);
  3919. // reset data stream position to zero
  3920. DataStream.Seek(0, soFromBeginning);
  3921. // decompress z-stream
  3922. ZDecompress(DataStream, Stream);
  3923. finally
  3924. DataStream.Free;
  3925. end;
  3926. end;
  3927. procedure TPortableNetworkGraphic.CompressImageDataFromStream(Stream: TStream);
  3928. var
  3929. DataStream: TMemoryStream;
  3930. begin
  3931. DataStream := TMemoryStream.Create;
  3932. try
  3933. // set compression method
  3934. FImageHeader.CompressionMethod := 0;
  3935. // compress Stream to DataStream
  3936. if Stream is TMemoryStream then
  3937. ZCompress(TMemoryStream(Stream), DataStream, FCompressionLevel)
  3938. else
  3939. raise EPngError.CreateFmt(RCStrNotYetImplemented, ['source stream must be TMemoryStream']);
  3940. // reset data stream position to zero
  3941. DataStream.Seek(0, soFromBeginning);
  3942. // copy image data from all data chunks to one continous data stream
  3943. StoreImageData(DataStream);
  3944. finally
  3945. DataStream.Free;
  3946. end;
  3947. end;
  3948. class function TPortableNetworkGraphic.CanLoad(const FileName: TFileName): Boolean;
  3949. var
  3950. FileStream: TFileStream;
  3951. begin
  3952. FileStream := TFileStream.Create(FileName, fmOpenRead);
  3953. try
  3954. Result := CanLoad(FileStream);
  3955. finally
  3956. FileStream.Free;
  3957. end;
  3958. end;
  3959. class function TPortableNetworkGraphic.CanLoad(Stream: TStream): Boolean;
  3960. var
  3961. Signature: array[0..SizeOf(PNG_SIG)-1] of AnsiChar;
  3962. begin
  3963. Result := (Stream.Size >= SizeOf(Signature));
  3964. if Result then
  3965. begin
  3966. Stream.Read(Signature, SizeOf(Signature));
  3967. Stream.Seek(-SizeOf(Signature), soFromCurrent);
  3968. Result := CompareMem(@Signature, @PNG_SIG, SizeOf(Signature));
  3969. end;
  3970. end;
  3971. procedure TPortableNetworkGraphic.LoadFromFile(Filename: TFilename);
  3972. var
  3973. FileStream: TFileStream;
  3974. begin
  3975. FileStream := TFileStream.Create(FileName, fmOpenRead);
  3976. try
  3977. LoadFromStream(FileStream);
  3978. finally
  3979. FileStream.Free;
  3980. end;
  3981. end;
  3982. procedure TPortableNetworkGraphic.LoadFromStream(Stream: TStream);
  3983. var
  3984. ChunkName : TChunkName;
  3985. ChunkSize : Integer;
  3986. ChunkCRC : Cardinal;
  3987. ChunkClass : TCustomDefinedChunkWithHeaderClass;
  3988. Chunk : TCustomDefinedChunkWithHeader;
  3989. MemoryStream : TMemoryStream;
  3990. GotIDAT : boolean;
  3991. SavePos : UInt64;
  3992. begin
  3993. GotIDAT := False;
  3994. Clear;
  3995. // Check for minimum file size and signature
  3996. if (not CanLoad(Stream)) then
  3997. raise EPngError.Create(RCStrNotAValidPNGFile);
  3998. // Skip chunk ID and magic - We already checked them in CanLoad above
  3999. Stream.Seek(SizeOf(PNG_SIG), soFromCurrent);
  4000. MemoryStream := TMemoryStream.Create;
  4001. try
  4002. // read image header chunk size
  4003. ChunkSize := BigEndian.ReadCardinal(Stream);
  4004. if ChunkSize > Stream.Size - 12 then
  4005. raise EPngError.Create(RCStrNotAValidPNGFile);
  4006. // read image header chunk ID
  4007. SavePos := Stream.Position;
  4008. Stream.Read(ChunkName, 4);
  4009. if ChunkName <> 'IHDR' then
  4010. raise EPngError.Create(RCStrNotAValidPNGFile);
  4011. // reset position to the chunk start and copy stream to memory
  4012. Stream.Position := SavePos;
  4013. MemoryStream.CopyFrom(Stream, ChunkSize + 4);
  4014. MemoryStream.Position := 4;
  4015. // load image header
  4016. FImageHeader.ReadFromStream(MemoryStream, ChunkSize);
  4017. // read image header chunk size
  4018. ChunkCRC := 0;
  4019. Stream.Read(ChunkCRC, 4);
  4020. {$IFDEF CheckCRC}
  4021. if not CheckCRC(MemoryStream, Swap32(ChunkCRC)) then
  4022. raise EPngError.Create(RCStrCRCError);
  4023. {$ENDIF}
  4024. while Stream.Position < Stream.Size do
  4025. begin
  4026. // read image header chunk size
  4027. ChunkSize := BigEndian.ReadCardinal(Stream);
  4028. if Stream.Position+ChunkSize+4 > Stream.Size then
  4029. raise EPngError.Create(RCStrNotAValidPNGFile);
  4030. // read chunk ID
  4031. SavePos := Stream.Position;
  4032. Stream.Read(ChunkName, 4);
  4033. // check for stream end
  4034. if ChunkName = 'IEND' then
  4035. begin
  4036. // read image header chunk size
  4037. Stream.Read(ChunkCRC, 4);
  4038. {$IFDEF CheckCRC}
  4039. if ChunkCRC <> 2187346606 then
  4040. raise EPngError.Create(RCStrCRCError);
  4041. {$ENDIF}
  4042. Break;
  4043. end;
  4044. // reset position to the chunk start and copy stream to memory
  4045. Stream.Position := SavePos;
  4046. MemoryStream.Clear;
  4047. MemoryStream.CopyFrom(Stream, ChunkSize + 4);
  4048. // reset memory stream to beginning of the chunk
  4049. MemoryStream.Seek(4, soFromBeginning);
  4050. if ChunkName = 'IHDR' then
  4051. raise EPngError.Create(RCStrNotAValidPNGFile);
  4052. if ChunkName = 'IDAT' then
  4053. begin
  4054. ReadImageDataChunk(MemoryStream, ChunkSize);
  4055. GotIDAT := True;
  4056. end else
  4057. if ChunkName = 'gAMA' then
  4058. begin
  4059. if (FGammaChunk <> nil) then
  4060. raise EPngError.Create(RCStrSeveralGammaChunks);
  4061. FGammaChunk := TChunkPngGamma.Create(FImageHeader);
  4062. FGammaChunk.ReadFromStream(MemoryStream, ChunkSize);
  4063. end else
  4064. if ChunkName = 'cHRM' then
  4065. begin
  4066. if (FChromaChunk <> nil) then
  4067. raise EPngError.Create(RCStrSeveralChromaChunks);
  4068. FChromaChunk := TChunkPngPrimaryChromaticities.Create(FImageHeader);
  4069. FChromaChunk.ReadFromStream(MemoryStream, ChunkSize);
  4070. end else
  4071. if ChunkName = 'tIME' then
  4072. begin
  4073. if (FTimeChunk <> nil) then
  4074. raise EPngError.Create(RCStrSeveralTimeChunks);
  4075. FTimeChunk := TChunkPngTime.Create(FImageHeader);
  4076. FTimeChunk.ReadFromStream(MemoryStream, ChunkSize);
  4077. end else
  4078. if ChunkName = 'sBIT' then
  4079. begin
  4080. if (FSignificantBits <> nil) then
  4081. raise EPngError.Create(RCStrSeveralSignificantBitsChunksFound);
  4082. FSignificantBits := TChunkPngSignificantBits.Create(FImageHeader);
  4083. FSignificantBits.ReadFromStream(MemoryStream, ChunkSize);
  4084. end else
  4085. if ChunkName = 'pHYs' then
  4086. begin
  4087. if (FPhysicalDimensions <> nil) then
  4088. raise EPngError.Create(RCStrSeveralPhysicalPixelDimensionChunks);
  4089. FPhysicalDimensions := TChunkPngPhysicalPixelDimensions.Create(FImageHeader);
  4090. FPhysicalDimensions.ReadFromStream(MemoryStream, ChunkSize);
  4091. end else
  4092. if ChunkName = 'PLTE' then
  4093. begin
  4094. if (FPaletteChunk <> nil) then
  4095. raise EPngError.Create(RCStrSeveralPaletteChunks);
  4096. FPaletteChunk := TChunkPngPalette.Create(FImageHeader);
  4097. FPaletteChunk.ReadFromStream(MemoryStream, ChunkSize);
  4098. end else
  4099. if ChunkName = 'tRNS' then
  4100. begin
  4101. if (FTransparencyChunk <> nil) then
  4102. raise EPngError.Create(RCStrSeveralTransparencyChunks);
  4103. FTransparencyChunk := TChunkPngTransparency.Create(FImageHeader);
  4104. FTransparencyChunk.ReadFromStream(MemoryStream, ChunkSize);
  4105. end else
  4106. if ChunkName = 'bKGD' then
  4107. begin
  4108. if (FBackgroundChunk <> nil) then
  4109. raise EPngError.Create(RCStrSeveralBackgroundChunks);
  4110. FBackgroundChunk := TChunkPngBackgroundColor.Create(FImageHeader);
  4111. FBackgroundChunk.ReadFromStream(MemoryStream, ChunkSize);
  4112. end else
  4113. begin
  4114. ChunkClass := FindPngChunkByChunkName(ChunkName);
  4115. if ChunkClass <> nil then
  4116. begin
  4117. Chunk := ChunkClass.Create(FImageHeader);
  4118. Chunk.ReadFromStream(MemoryStream, ChunkSize);
  4119. FAdditionalChunkList.Add(Chunk);
  4120. end
  4121. else
  4122. begin
  4123. // check if chunk is ancillary
  4124. if (Byte(ChunkName[0]) and $80) <> 0 then
  4125. raise EPngError.Create(RCStrAncillaryUnknownChunk);
  4126. ReadUnknownChunk(MemoryStream, ChunkName, ChunkSize);
  4127. end;
  4128. end;
  4129. // read & check CRC
  4130. Stream.Read(ChunkCRC, 4);
  4131. {$IFDEF CheckCRC}
  4132. if not CheckCRC(MemoryStream, Swap32(ChunkCRC)) then
  4133. raise EPngError.Create(RCStrCRCError);
  4134. {$ENDIF}
  4135. end;
  4136. finally
  4137. MemoryStream.Free;
  4138. end;
  4139. if (not GotIDAT) then
  4140. raise EPngError.Create(RCStrMissingIDATChunk);
  4141. end;
  4142. procedure TPortableNetworkGraphic.SaveToFile(Filename: TFilename);
  4143. var
  4144. FileStream: TFileStream;
  4145. begin
  4146. FileStream := TFileStream.Create(FileName, fmCreate);
  4147. try
  4148. SaveToStream(FileStream);
  4149. finally
  4150. FileStream.Free;
  4151. end;
  4152. end;
  4153. procedure TPortableNetworkGraphic.SaveToStream(Stream: TStream);
  4154. var
  4155. ChunkName : TChunkName;
  4156. ChunkSize : Cardinal;
  4157. CRC : Cardinal;
  4158. MemoryStream : TMemoryStream;
  4159. Index : Integer;
  4160. procedure SaveChunkToStream(Chunk: TCustomChunk);
  4161. begin
  4162. MemoryStream.Clear;
  4163. // store chunk size directly to stream
  4164. ChunkSize := Chunk.ChunkSize;
  4165. BigEndian.WriteCardinal(Stream, ChunkSize);
  4166. // store chunk name to memory stream
  4167. ChunkName := Chunk.ChunkName;
  4168. MemoryStream.Write(ChunkName, 4);
  4169. // save chunk to memory stream
  4170. Chunk.WriteToStream(MemoryStream);
  4171. // copy memory stream to stream
  4172. MemoryStream.Position := 0;
  4173. Stream.CopyFrom(MemoryStream, 0);
  4174. // calculate and write CRC
  4175. CRC := Swap32(CalculateCRC(MemoryStream));
  4176. Stream.Write(CRC, SizeOf(Cardinal));
  4177. end;
  4178. begin
  4179. // Write chunk ID and PNG magic
  4180. Stream.Write(PNG_SIG, SizeOf(PNG_SIG));
  4181. MemoryStream := TMemoryStream.Create;
  4182. try
  4183. // store chunk size directly to stream
  4184. ChunkSize := FImageHeader.ChunkSize;
  4185. BigEndian.WriteCardinal(Stream, ChunkSize);
  4186. // store chunk name to memory stream
  4187. ChunkName := FImageHeader.ChunkName;
  4188. MemoryStream.Write(ChunkName, 4);
  4189. // save image header to memory stream
  4190. FImageHeader.WriteToStream(MemoryStream);
  4191. // copy memory stream to stream
  4192. MemoryStream.Position := 0;;
  4193. Stream.CopyFrom(MemoryStream, 0);
  4194. // calculate and write CRC
  4195. CRC := Swap32(CalculateCRC(MemoryStream));
  4196. Stream.Write(CRC, SizeOf(Cardinal));
  4197. // eventually save physical pixel dimensions chunk
  4198. if (FPhysicalDimensions <> nil) then
  4199. SaveChunkToStream(FPhysicalDimensions);
  4200. // eventually save significant bits chunk
  4201. if (FSignificantBits <> nil) then
  4202. SaveChunkToStream(FSignificantBits);
  4203. // eventually save gamma chunk
  4204. if (FGammaChunk <> nil) then
  4205. SaveChunkToStream(FGammaChunk);
  4206. // eventually save chroma chunk
  4207. if (FChromaChunk <> nil) then
  4208. SaveChunkToStream(FChromaChunk);
  4209. // eventually save palette chunk
  4210. if (FPaletteChunk <> nil) then
  4211. SaveChunkToStream(FPaletteChunk);
  4212. // eventually save transparency chunk
  4213. if (FTransparencyChunk <> nil) then
  4214. SaveChunkToStream(FTransparencyChunk);
  4215. // eventually save background chunk
  4216. if (FBackgroundChunk <> nil) then
  4217. SaveChunkToStream(FBackgroundChunk);
  4218. // store additional chunks
  4219. for Index := 0 to FAdditionalChunkList.Count - 1 do
  4220. SaveChunkToStream(TCustomChunk(FAdditionalChunkList[Index]));
  4221. // save data streams
  4222. for Index := 0 to FDataChunkList.Count - 1 do
  4223. SaveChunkToStream(TCustomChunk(FDataChunkList[Index]));
  4224. finally
  4225. MemoryStream.Free;
  4226. end;
  4227. // write chunk size
  4228. BigEndian.WriteCardinal(Stream, 0);
  4229. // write chunk ID
  4230. ChunkName := 'IEND';
  4231. Stream.Write(ChunkName, 4);
  4232. // write CRC
  4233. CRC := 2187346606;
  4234. Stream.Write(CRC, 4);
  4235. end;
  4236. procedure TPortableNetworkGraphic.ReadUnknownChunk(Stream: TStream;
  4237. ChunkName: TChunkName; ChunkSize: Integer);
  4238. var
  4239. UnknownChunk : TChunkPngUnknown;
  4240. begin
  4241. UnknownChunk := TChunkPngUnknown.Create(ChunkName);
  4242. UnknownChunk.ReadFromStream(Stream, ChunkSize);
  4243. FAdditionalChunkList.Add(UnknownChunk);
  4244. end;
  4245. procedure TPortableNetworkGraphic.RemoveGammaInformation;
  4246. begin
  4247. FreeAndNil(FGammaChunk);
  4248. end;
  4249. procedure TPortableNetworkGraphic.RemoveModifiedTimeInformation;
  4250. begin
  4251. FreeAndNil(FTimeChunk);
  4252. end;
  4253. procedure TPortableNetworkGraphic.RemovePhysicalPixelDimensionsInformation;
  4254. begin
  4255. FreeAndNil(FPhysicalDimensions);
  4256. end;
  4257. procedure TPortableNetworkGraphic.CompressionLevelChanged;
  4258. var
  4259. TempStream : TMemoryStream;
  4260. begin
  4261. TempStream := TMemoryStream.Create;
  4262. try
  4263. DecompressImageDataToStream(TempStream);
  4264. TempStream.Seek(0, soFromBeginning);
  4265. CompressImageDataFromStream(TempStream);
  4266. finally
  4267. TempStream.Free;
  4268. end;
  4269. end;
  4270. procedure TPortableNetworkGraphic.AdaptiveFilterMethodsChanged;
  4271. begin
  4272. if FDataChunkList.Count > 0 then
  4273. begin
  4274. // transcoding!
  4275. raise EPngError.CreateFmt(RCStrNotYetImplemented, ['AdaptiveFilterMethods transcoding']);
  4276. end;
  4277. end;
  4278. procedure TPortableNetworkGraphic.InterlaceMethodChanged;
  4279. var
  4280. TempStream : TMemoryStream;
  4281. TranscoderClass : TCustomPngTranscoderClass;
  4282. begin
  4283. TempStream := TMemoryStream.Create;
  4284. try
  4285. DecompressImageDataToStream(TempStream);
  4286. TempStream.Seek(0, soFromBeginning);
  4287. case FImageHeader.InterlaceMethod of
  4288. imNone : TranscoderClass := TPngNonInterlacedToAdam7Transcoder;
  4289. imAdam7 : TranscoderClass := TPngAdam7ToNonInterlacedTranscoder;
  4290. else
  4291. raise EPngError.Create(RCStrWrongInterlaceMethod);
  4292. end;
  4293. with TranscoderClass.Create(TempStream, FImageHeader) do
  4294. try
  4295. Transcode;
  4296. finally
  4297. Free;
  4298. end;
  4299. TempStream.Seek(0, soFromBeginning);
  4300. CompressImageDataFromStream(TempStream);
  4301. finally
  4302. TempStream.Free;
  4303. end;
  4304. end;
  4305. procedure TPortableNetworkGraphic.ReadImageDataChunk(Stream: TStream; Size: Integer);
  4306. var
  4307. ImageDataChunk : TChunkPngImageData;
  4308. begin
  4309. ImageDataChunk := TChunkPngImageData.Create(FImageHeader);
  4310. ImageDataChunk.ReadFromStream(Stream, Size);
  4311. FDataChunkList.Add(ImageDataChunk);
  4312. end;
  4313. procedure TPortableNetworkGraphic.Assign(Source: TPersistent);
  4314. begin
  4315. if Source is TPortableNetworkGraphic then
  4316. with TPortableNetworkGraphic(Source) do
  4317. begin
  4318. if (Self.FImageHeader <> nil) then
  4319. Self.FImageHeader.Assign(FImageHeader);
  4320. // assign palette chunk
  4321. if (Self.FPaletteChunk <> nil) then
  4322. if (FPaletteChunk <> nil) then
  4323. Self.FPaletteChunk.Assign(FPaletteChunk)
  4324. else
  4325. FreeAndNil(Self.FPaletteChunk)
  4326. else if (FPaletteChunk <> nil) then
  4327. begin
  4328. Self.FPaletteChunk := TChunkPngPalette.Create(FImageHeader);
  4329. Self.FPaletteChunk.Assign(FPaletteChunk);
  4330. end;
  4331. // assign gamma chunk
  4332. if (Self.FGammaChunk <> nil) then
  4333. if (FGammaChunk <> nil) then
  4334. Self.FGammaChunk.Assign(FGammaChunk)
  4335. else
  4336. FreeAndNil(Self.FGammaChunk)
  4337. else if (FGammaChunk <> nil) then
  4338. begin
  4339. Self.FGammaChunk := TChunkPngGamma.Create(FImageHeader);
  4340. Self.FGammaChunk.Assign(FGammaChunk);
  4341. end;
  4342. // assign time chunk
  4343. if (Self.FTimeChunk <> nil) then
  4344. if (FTimeChunk <> nil) then
  4345. Self.FTimeChunk.Assign(FTimeChunk)
  4346. else
  4347. FreeAndNil(Self.FTimeChunk)
  4348. else if (FTimeChunk <> nil) then
  4349. begin
  4350. Self.FTimeChunk := TChunkPngTime.Create(FImageHeader);
  4351. Self.FTimeChunk.Assign(FTimeChunk);
  4352. end;
  4353. // assign significant bits
  4354. if (Self.FSignificantBits <> nil) then
  4355. if (FSignificantBits <> nil) then
  4356. Self.FSignificantBits.Assign(FSignificantBits)
  4357. else
  4358. FreeAndNil(Self.FSignificantBits)
  4359. else if (FSignificantBits <> nil) then
  4360. begin
  4361. Self.FSignificantBits := TChunkPngSignificantBits.Create(FImageHeader);
  4362. Self.FSignificantBits.Assign(FSignificantBits);
  4363. end;
  4364. // assign physical dimensions
  4365. if (Self.FPhysicalDimensions <> nil) then
  4366. if (FPhysicalDimensions <> nil) then
  4367. Self.FPhysicalDimensions.Assign(FPhysicalDimensions)
  4368. else
  4369. FreeAndNil(Self.FPhysicalDimensions)
  4370. else if (FPhysicalDimensions <> nil) then
  4371. begin
  4372. Self.FPhysicalDimensions := TChunkPngPhysicalPixelDimensions.Create(FImageHeader);
  4373. Self.FPhysicalDimensions.Assign(FPhysicalDimensions);
  4374. end;
  4375. // assign primary chromaticities
  4376. if (Self.FChromaChunk <> nil) then
  4377. if (FChromaChunk <> nil) then
  4378. Self.FChromaChunk.Assign(FChromaChunk)
  4379. else
  4380. FreeAndNil(Self.FChromaChunk)
  4381. else if (FChromaChunk <> nil) then
  4382. begin
  4383. Self.FChromaChunk := TChunkPngPrimaryChromaticities.Create(FImageHeader);
  4384. Self.FChromaChunk.Assign(FChromaChunk);
  4385. end;
  4386. // assign transparency
  4387. if (Self.FTransparencyChunk <> nil) then
  4388. if (FTransparencyChunk <> nil) then
  4389. Self.FTransparencyChunk.Assign(FTransparencyChunk)
  4390. else
  4391. FreeAndNil(Self.FTransparencyChunk)
  4392. else if (FTransparencyChunk <> nil) then
  4393. begin
  4394. Self.FTransparencyChunk := TChunkPngTransparency.Create(FImageHeader);
  4395. Self.FTransparencyChunk.Assign(FTransparencyChunk);
  4396. end;
  4397. // assign background
  4398. if (Self.FBackgroundChunk <> nil) then
  4399. if (FBackgroundChunk <> nil) then
  4400. Self.FBackgroundChunk.Assign(FBackgroundChunk)
  4401. else
  4402. FreeAndNil(Self.FBackgroundChunk)
  4403. else if (FBackgroundChunk <> nil) then
  4404. begin
  4405. Self.FBackgroundChunk := TChunkPngBackgroundColor.Create(FImageHeader);
  4406. Self.FBackgroundChunk.Assign(FBackgroundChunk);
  4407. end;
  4408. if (Self.FDataChunkList <> nil) then
  4409. Self.FDataChunkList.Assign(FDataChunkList);
  4410. if (Self.FAdditionalChunkList <> nil) then
  4411. Self.FAdditionalChunkList.Assign(FAdditionalChunkList);
  4412. end
  4413. else
  4414. inherited;
  4415. end;
  4416. procedure TPortableNetworkGraphic.AssignTo(Dest: TPersistent);
  4417. begin
  4418. if Dest is TPortableNetworkGraphic then
  4419. with TPortableNetworkGraphic(Dest) do
  4420. begin
  4421. FImageHeader.Assign(Self.FImageHeader);
  4422. FPaletteChunk.Assign(Self.FPaletteChunk);
  4423. FGammaChunk.Assign(Self.FGammaChunk);
  4424. FTimeChunk.Assign(Self.FTimeChunk);
  4425. FSignificantBits.Assign(Self.FSignificantBits);
  4426. FPhysicalDimensions.Assign(Self.FPhysicalDimensions);
  4427. FChromaChunk.Assign(Self.FChromaChunk);
  4428. FTransparencyChunk.Assign(Self.FTransparencyChunk);
  4429. FBackgroundChunk.Assign(Self.FBackgroundChunk);
  4430. FDataChunkList.Assign(Self.FDataChunkList);
  4431. FAdditionalChunkList.Assign(Self.FAdditionalChunkList);
  4432. end
  4433. else
  4434. inherited;
  4435. end;
  4436. function TPortableNetworkGraphic.CalculateCRC(Stream: TStream): Cardinal;
  4437. var
  4438. CrcValue : Cardinal;
  4439. Value : Byte;
  4440. begin
  4441. if Stream is TMemoryStream then
  4442. Result := CalculateCRC(TMemoryStream(Stream).Memory, Stream.Size)
  4443. else
  4444. begin
  4445. Stream.Position := 0;
  4446. // initialize CRC
  4447. CrcValue := $FFFFFFFF;
  4448. {$IFDEF FPC}
  4449. Value := 0;
  4450. {$ENDIF}
  4451. while Stream.Position < Stream.Size do
  4452. begin
  4453. Stream.Read(Value, 1);
  4454. CrcValue := GCrcTable^[(CrcValue xor Value) and $FF] xor (CrcValue shr 8);
  4455. end;
  4456. Result := (CrcValue xor $FFFFFFFF);
  4457. Stream.Position := 0;
  4458. end;
  4459. end;
  4460. function TPortableNetworkGraphic.CalculateCRC(Buffer: PByte; Count: Cardinal): Cardinal;
  4461. {$if defined(PUREPASCAL)}
  4462. var
  4463. CrcValue : Cardinal;
  4464. Pos : Cardinal;
  4465. begin
  4466. // ignore size (offset by 4 bytes)
  4467. Pos := 0;
  4468. // initialize CRC
  4469. CrcValue := $FFFFFFFF;
  4470. while Pos < Count do
  4471. begin
  4472. CrcValue := GCrcTable^[(CrcValue xor Buffer^) and $FF] xor (CrcValue shr 8);
  4473. Inc(Buffer);
  4474. Inc(Pos);
  4475. end;
  4476. Result := (CrcValue xor $FFFFFFFF);
  4477. {$else}
  4478. asm
  4479. {$IFDEF Target_x64}
  4480. PUSH RBX
  4481. PUSH RDI
  4482. MOV RCX, R8
  4483. JS @Done
  4484. NEG RCX
  4485. MOV RBX, $FFFFFFFF
  4486. {$IFNDEF FPC}
  4487. MOV RDI, [GCrcTable]
  4488. {$ELSE}
  4489. MOV RDI, [RIP + GCrcTable]
  4490. {$ENDIF}
  4491. @Start:
  4492. MOVZX EAX, [RDX].BYTE
  4493. XOR EAX, EBX
  4494. AND EAX, $FF
  4495. MOV EAX, [RDI + 4 * RAX]
  4496. SHR EBX, 8
  4497. XOR EAX, EBX
  4498. MOV EBX, EAX
  4499. INC RDX
  4500. INC RCX
  4501. JS @Start
  4502. XOR EBX, $FFFFFFFF
  4503. MOV RAX, RBX
  4504. @Done:
  4505. POP RDI
  4506. POP RBX
  4507. {$ELSE}
  4508. PUSH EBX
  4509. PUSH EDI
  4510. JS @Done
  4511. NEG ECX
  4512. MOV EBX, $FFFFFFFF
  4513. MOV EDI, [GCrcTable]
  4514. @Start:
  4515. MOVZX EAX, [EDX].BYTE
  4516. XOR EAX, EBX
  4517. AND EAX, $FF
  4518. MOV EAX, [EDI + 4 * EAX]
  4519. SHR EBX, 8
  4520. XOR EAX, EBX
  4521. MOV EBX, EAX
  4522. INC EDX
  4523. INC ECX
  4524. JS @Start
  4525. XOR EAX, $FFFFFFFF
  4526. @Done:
  4527. POP EDI
  4528. POP EBX
  4529. {$ENDIF}
  4530. {$ifend}
  4531. end;
  4532. {$IFDEF CheckCRC}
  4533. function TPortableNetworkGraphic.CheckCRC(Stream: TStream; CRC: Cardinal): Boolean;
  4534. begin
  4535. Result := CalculateCRC(Stream) = CRC;
  4536. end;
  4537. {$ENDIF}
  4538. function TPortableNetworkGraphic.GetBitDepth: Byte;
  4539. begin
  4540. Result := FImageHeader.BitDepth;
  4541. end;
  4542. function TPortableNetworkGraphic.GetColorType: TColorType;
  4543. begin
  4544. Result := FImageHeader.ColorType;
  4545. end;
  4546. function TPortableNetworkGraphic.GetCompressionMethod: Byte;
  4547. begin
  4548. Result := FImageHeader.CompressionMethod;
  4549. end;
  4550. function TPortableNetworkGraphic.GetFilterMethod: TFilterMethod;
  4551. begin
  4552. Result := FImageHeader.FilterMethod;
  4553. end;
  4554. function TPortableNetworkGraphic.GetFilterMethods: TAvailableAdaptiveFilterMethods;
  4555. begin
  4556. Result := FImageHeader.FAdaptiveFilterMethods;
  4557. end;
  4558. function TPortableNetworkGraphic.GetGamma: Single;
  4559. begin
  4560. if (FGammaChunk <> nil) then
  4561. Result := FGammaChunk.GammaAsSingle
  4562. else
  4563. Result := 1;
  4564. end;
  4565. function TPortableNetworkGraphic.GetHeight: Integer;
  4566. begin
  4567. Result := FImageHeader.Height;
  4568. end;
  4569. function TPortableNetworkGraphic.GetInterlaceMethod: TInterlaceMethod;
  4570. begin
  4571. Result := FImageHeader.InterlaceMethod;
  4572. end;
  4573. function TPortableNetworkGraphic.GetModifiedTime: TDateTime;
  4574. begin
  4575. if (FTimeChunk <> nil) then
  4576. Result := EncodeDate(FTimeChunk.Year, FTimeChunk.Month, FTimeChunk.Day) +
  4577. EncodeTime(FTimeChunk.Hour, FTimeChunk.Minute, FTimeChunk.Second, 0)
  4578. else
  4579. Result := 0;
  4580. end;
  4581. function TPortableNetworkGraphic.GetPaletteEntry(Index: Integer): TRGB24;
  4582. begin
  4583. if (FPaletteChunk <> nil) then
  4584. Result := FPaletteChunk.PaletteEntry[Index]
  4585. else
  4586. raise EPngError.CreateFmt(RCStrIndexOutOfBounds, [Index]);
  4587. end;
  4588. function TPortableNetworkGraphic.GetPaletteEntryCount: Integer;
  4589. begin
  4590. if (FPaletteChunk <> nil) then
  4591. Result := FPaletteChunk.Count
  4592. else
  4593. Result := 0;
  4594. end;
  4595. function TPortableNetworkGraphic.GetPixelsPerUnitX: Cardinal;
  4596. begin
  4597. if (FPhysicalDimensions <> nil) then
  4598. Result := FPhysicalDimensions.PixelsPerUnitX
  4599. else
  4600. Result := 1;
  4601. end;
  4602. function TPortableNetworkGraphic.GetPixelsPerUnitY: Cardinal;
  4603. begin
  4604. if (FPhysicalDimensions <> nil) then
  4605. Result := FPhysicalDimensions.PixelsPerUnitY
  4606. else
  4607. Result := 1;
  4608. end;
  4609. function TPortableNetworkGraphic.GetPixelUnit: Byte;
  4610. begin
  4611. if (FPhysicalDimensions <> nil) then
  4612. Result := FPhysicalDimensions.PixelUnit
  4613. else
  4614. Result := 0;
  4615. end;
  4616. function TPortableNetworkGraphic.GetWidth: Integer;
  4617. begin
  4618. Result := FImageHeader.Width;
  4619. end;
  4620. function TPortableNetworkGraphic.HasGammaInformation: Boolean;
  4621. begin
  4622. Result := (FGammaChunk <> nil);
  4623. end;
  4624. function TPortableNetworkGraphic.HasModifiedTimeInformation: Boolean;
  4625. begin
  4626. Result := (FTimeChunk <> nil);
  4627. end;
  4628. function TPortableNetworkGraphic.HasPhysicalPixelDimensionsInformation: Boolean;
  4629. begin
  4630. Result := (FPhysicalDimensions <> nil);
  4631. end;
  4632. procedure TPortableNetworkGraphic.Clear;
  4633. begin
  4634. // clear chunk lists
  4635. FDataChunkList.Clear;
  4636. FAdditionalChunkList.Clear;
  4637. // reset image header to default
  4638. FImageHeader.ResetToDefault;
  4639. FreeAndNil(FPaletteChunk);
  4640. FreeAndNil(FGammaChunk);
  4641. FreeAndNil(FChromaChunk);
  4642. FreeAndNil(FTransparencyChunk);
  4643. FreeAndNil(FBackgroundChunk);
  4644. FreeAndNil(FTimeChunk);
  4645. FreeAndNil(FSignificantBits);
  4646. FreeAndNil(FPhysicalDimensions);
  4647. end;
  4648. { TPngNonInterlacedToAdam7Transcoder }
  4649. procedure TPngNonInterlacedToAdam7Transcoder.Transcode;
  4650. var
  4651. CurrentRow : Integer;
  4652. RowByteSize : Integer;
  4653. PixelPerRow : Integer;
  4654. PixelByteSize : Integer;
  4655. CurrentPass : Integer;
  4656. Index : Integer;
  4657. PassRow : Integer;
  4658. Source : PByte;
  4659. Destination : PByte;
  4660. TempData : PByteArray;
  4661. OutputRow : PByteArray;
  4662. TempBuffer : PByteArray;
  4663. begin
  4664. // initialize variables
  4665. CurrentRow := 0;
  4666. PixelByteSize := FHeader.PixelByteSize;
  4667. GetMem(TempData, FHeader.Height * FHeader.BytesPerRow);
  4668. Destination := PByte(TempData);
  4669. try
  4670. ///////////////////////////////////
  4671. // decode image (non-interlaced) //
  4672. ///////////////////////////////////
  4673. // clear previous row
  4674. FillChar(FRowBuffer[1 - CurrentRow]^[0], FHeader.BytesPerRow + 1, 0);
  4675. for Index := 0 to FHeader.Height - 1 do
  4676. begin
  4677. // read data from stream
  4678. if FStream.Read(FRowBuffer[CurrentRow][0], FHeader.BytesPerRow + 1) <> FHeader.BytesPerRow + 1 then
  4679. raise EPngError.Create(RCStrDataIncomplete);
  4680. // filter current row
  4681. DecodeFilterRow(TAdaptiveFilterMethod(FRowBuffer[CurrentRow]^[0]),
  4682. FRowBuffer[CurrentRow], FRowBuffer[1 - CurrentRow], FHeader.BytesPerRow,
  4683. PixelByteSize);
  4684. // transfer data from row to temp data
  4685. Move(FRowBuffer[CurrentRow][1], Destination^, PixelByteSize * FHeader.Width);
  4686. Inc(Destination, FHeader.Width * PixelByteSize);
  4687. // flip current row
  4688. CurrentRow := 1 - CurrentRow;
  4689. end;
  4690. // reset position to zero
  4691. FStream.Seek(0, soFromBeginning);
  4692. // The Adam7 interlacer uses 7 passes to create the complete image
  4693. for CurrentPass := 0 to 6 do
  4694. begin
  4695. // calculate some intermediate variables
  4696. PixelPerRow := (FHeader.Width - CColumnStart[CurrentPass] +
  4697. CColumnIncrement[CurrentPass] - 1) div CColumnIncrement[CurrentPass];
  4698. case FHeader.ColorType of
  4699. ctGrayscale : RowByteSize := (PixelPerRow * FHeader.BitDepth + 7) div 8;
  4700. ctIndexedColor : RowByteSize := (PixelPerRow * FHeader.BitDepth + 7) div 8;
  4701. ctTrueColor : RowByteSize := (PixelPerRow * FHeader.BitDepth * 3) div 8;
  4702. ctGrayscaleAlpha : RowByteSize := (PixelPerRow * FHeader.BitDepth * 2) div 8;
  4703. ctTrueColorAlpha : RowByteSize := (PixelPerRow * FHeader.BitDepth * 4) div 8;
  4704. else
  4705. Continue;
  4706. end;
  4707. PassRow := CRowStart[CurrentPass];
  4708. // clear previous row
  4709. FillChar(FRowBuffer[1 - CurrentRow]^[0], RowByteSize + 1, 0);
  4710. // check if pre filter is used and eventually calculate pre filter
  4711. if (FHeader.ColorType <> ctIndexedColor) and
  4712. not (FHeader.AdaptiveFilterMethods = []) then
  4713. begin
  4714. GetMem(OutputRow, RowByteSize + 1);
  4715. GetMem(TempBuffer, RowByteSize + 1);
  4716. try
  4717. while PassRow < FHeader.Height do
  4718. begin
  4719. Index := CColumnStart[CurrentPass];
  4720. Source := @TempData[PassRow * FHeader.BytesPerRow + Index * PixelByteSize];
  4721. Destination := @FRowBuffer[CurrentRow][1];
  4722. repeat
  4723. // copy bytes per pixels
  4724. Move(Source^, Destination^, PixelByteSize);
  4725. Inc(Source, CColumnIncrement[CurrentPass] * PixelByteSize);
  4726. Inc(Destination, PixelByteSize);
  4727. Inc(Index, CColumnIncrement[CurrentPass]);
  4728. until Index >= FHeader.Width;
  4729. // filter current row
  4730. EncodeFilterRow(FRowBuffer[CurrentRow], FRowBuffer[1 - CurrentRow],
  4731. OutputRow, TempBuffer, RowByteSize, FHeader.PixelByteSize);
  4732. Assert(OutputRow[0] in [0..4]);
  4733. // write data to data stream
  4734. FStream.Write(OutputRow[0], RowByteSize + 1);
  4735. // prepare for the next pass
  4736. Inc(PassRow, CRowIncrement[CurrentPass]);
  4737. CurrentRow := 1 - CurrentRow;
  4738. end;
  4739. finally
  4740. Dispose(OutputRow);
  4741. Dispose(TempBuffer);
  4742. end;
  4743. end
  4744. else
  4745. while PassRow < FHeader.Height do
  4746. begin
  4747. Index := CColumnStart[CurrentPass];
  4748. Source := @TempData[PassRow * FHeader.BytesPerRow + Index * PixelByteSize];
  4749. Destination := @FRowBuffer[CurrentRow][1];
  4750. repeat
  4751. // copy bytes per pixels
  4752. Move(Source^, Destination^, PixelByteSize);
  4753. Inc(Source, CColumnIncrement[CurrentPass] * PixelByteSize);
  4754. Inc(Destination, PixelByteSize);
  4755. Inc(Index, CColumnIncrement[CurrentPass]);
  4756. until Index >= FHeader.Width;
  4757. // set filter method 0
  4758. FRowBuffer[CurrentRow][0] := 0;
  4759. // write data to data stream
  4760. FStream.Write(FRowBuffer[CurrentRow][0], RowByteSize + 1);
  4761. // prepare for the next pass
  4762. Inc(PassRow, CRowIncrement[CurrentPass]);
  4763. CurrentRow := 1 - CurrentRow;
  4764. end;
  4765. end;
  4766. finally
  4767. Dispose(TempData);
  4768. end;
  4769. end;
  4770. { TPngAdam7ToNonInterlacedTranscoder }
  4771. procedure TPngAdam7ToNonInterlacedTranscoder.Transcode;
  4772. var
  4773. CurrentRow : Integer;
  4774. RowByteSize : Integer;
  4775. PixelPerRow : Integer;
  4776. PixelByteSize : Integer;
  4777. CurrentPass : Integer;
  4778. Index : Integer;
  4779. PassRow : Integer;
  4780. Source : PByte;
  4781. Destination : PByte;
  4782. TempData : PByteArray;
  4783. OutputRow : PByteArray;
  4784. TempBuffer : PByteArray;
  4785. begin
  4786. // initialize variables
  4787. CurrentRow := 0;
  4788. PixelByteSize := FHeader.PixelByteSize;
  4789. GetMem(TempData, FHeader.Height * FHeader.BytesPerRow);
  4790. try
  4791. /////////////////////////////////////
  4792. // decode image (Adam7-interlaced) //
  4793. /////////////////////////////////////
  4794. // The Adam7 deinterlacer uses 7 passes to create the complete image
  4795. for CurrentPass := 0 to 6 do
  4796. begin
  4797. // calculate some intermediate variables
  4798. PixelPerRow := (FHeader.Width - CColumnStart[CurrentPass] +
  4799. CColumnIncrement[CurrentPass] - 1) div CColumnIncrement[CurrentPass];
  4800. case FHeader.ColorType of
  4801. ctGrayscale : RowByteSize := (PixelPerRow * FHeader.BitDepth + 7) div 8;
  4802. ctIndexedColor : RowByteSize := (PixelPerRow * FHeader.BitDepth + 7) div 8;
  4803. ctTrueColor : RowByteSize := (PixelPerRow * FHeader.BitDepth * 3) div 8;
  4804. ctGrayscaleAlpha : RowByteSize := (PixelPerRow * FHeader.BitDepth * 2) div 8;
  4805. ctTrueColorAlpha : RowByteSize := (PixelPerRow * FHeader.BitDepth * 4) div 8;
  4806. else
  4807. Continue;
  4808. end;
  4809. PassRow := CRowStart[CurrentPass];
  4810. // clear previous row
  4811. FillChar(FRowBuffer[1 - CurrentRow]^[0], RowByteSize, 0);
  4812. // process pixels
  4813. while PassRow < FHeader.Height do
  4814. begin
  4815. // get interlaced row data
  4816. if FStream.Read(FRowBuffer[CurrentRow][0], RowByteSize + 1) <> (RowByteSize + 1) then
  4817. raise EPngError.Create(RCStrDataIncomplete);
  4818. DecodeFilterRow(TAdaptiveFilterMethod(FRowBuffer[CurrentRow]^[0]),
  4819. FRowBuffer[CurrentRow], FRowBuffer[1 - CurrentRow], RowByteSize, PixelByteSize);
  4820. Index := CColumnStart[CurrentPass];
  4821. Source := @FRowBuffer[CurrentRow][1];
  4822. Destination := @TempData[PassRow * FHeader.BytesPerRow + Index * PixelByteSize];
  4823. repeat
  4824. // copy bytes per pixels
  4825. Move(Source^, Destination^, PixelByteSize);
  4826. Inc(Source, PixelByteSize);
  4827. Inc(Destination, CColumnIncrement[CurrentPass] * PixelByteSize);
  4828. Inc(Index, CColumnIncrement[CurrentPass]);
  4829. until Index >= FHeader.Width;
  4830. // prepare for the next pass
  4831. Inc(PassRow, CRowIncrement[CurrentPass]);
  4832. CurrentRow := 1 - CurrentRow;
  4833. end;
  4834. end;
  4835. // reset position to zero
  4836. FStream.Seek(0, soFromBeginning);
  4837. /////////////////////////////////
  4838. // encode image non-interlaced //
  4839. /////////////////////////////////
  4840. // clear previous row buffer
  4841. FillChar(FRowBuffer[1 - CurrentRow]^[0], FHeader.BytesPerRow, 0);
  4842. Source := PByte(TempData);
  4843. // check if pre filter is used and eventually calculate pre filter
  4844. if (FHeader.ColorType <> ctIndexedColor) and
  4845. not (FHeader.AdaptiveFilterMethods = []) then
  4846. begin
  4847. GetMem(OutputRow, FHeader.BytesPerRow + 1);
  4848. GetMem(TempBuffer, FHeader.BytesPerRow + 1);
  4849. try
  4850. for Index := 0 to FHeader.Height - 1 do
  4851. begin
  4852. // copy bytes per pixels
  4853. Move(Source^, FRowBuffer[CurrentRow][1], FHeader.Width * PixelByteSize);
  4854. Inc(Source, FHeader.Width * PixelByteSize);
  4855. // filter current row
  4856. EncodeFilterRow(FRowBuffer[CurrentRow], FRowBuffer[1 - CurrentRow],
  4857. OutputRow, TempBuffer, FHeader.BytesPerRow, FHeader.PixelByteSize);
  4858. // write data to data stream
  4859. FStream.Write(OutputRow[0], FHeader.BytesPerRow + 1);
  4860. // flip current row used
  4861. CurrentRow := 1 - CurrentRow;
  4862. end;
  4863. finally
  4864. Dispose(OutputRow);
  4865. Dispose(TempBuffer);
  4866. end;
  4867. end
  4868. else
  4869. for Index := 0 to FHeader.Height - 1 do
  4870. begin
  4871. // copy bytes per pixels
  4872. Move(Source^, FRowBuffer[CurrentRow][1], FHeader.Width * PixelByteSize);
  4873. Inc(Source, FHeader.Width * PixelByteSize);
  4874. // set filter method to none
  4875. FRowBuffer[CurrentRow][0] := 0;
  4876. // write data to data stream
  4877. FStream.Write(FRowBuffer[CurrentRow][0], FHeader.BytesPerRow + 1);
  4878. // flip current row used
  4879. CurrentRow := 1 - CurrentRow;
  4880. end;
  4881. finally
  4882. Dispose(TempData);
  4883. end;
  4884. end;
  4885. procedure BuildCrcTable(Polynomial: Cardinal);
  4886. var
  4887. c : Cardinal;
  4888. n, k : Integer;
  4889. begin
  4890. // allocate CRC table memory
  4891. GetMem(GCrcTable, 256 * SizeOf(Cardinal));
  4892. // fill CRC table
  4893. for n := 0 to 255 do
  4894. begin
  4895. c := n;
  4896. for k := 0 to 7 do
  4897. begin
  4898. if (c and 1) <> 0 then
  4899. c := Polynomial xor (c shr 1)
  4900. else
  4901. c := c shr 1;
  4902. end;
  4903. GCrcTable^[n] := c;
  4904. end;
  4905. end;
  4906. initialization
  4907. BuildCrcTable($EDB88320);
  4908. RegisterPngChunks([TChunkPngImageData, TChunkPngPalette, TChunkPngGamma,
  4909. TChunkPngStandardColorSpaceRGB, TChunkPngPrimaryChromaticities,
  4910. TChunkPngTime, TChunkPngTransparency, TChunkPngEmbeddedIccProfile,
  4911. TChunkPngPhysicalPixelDimensions,
  4912. TChunkPngText, TChunkPngCompressedText,
  4913. TChunkPngImageHistogram, TChunkPngBackgroundColor,
  4914. TChunkPngSignificantBits, TChunkPngImageOffset, TChunkPngPixelCalibrator]);
  4915. {$ifdef PNG_CHUNK_SUGGESTED_PALETTE}
  4916. RegisterPngChunks([TChunkPngSuggestedPalette]);
  4917. {$endif PNG_CHUNK_SUGGESTED_PALETTE}
  4918. {$ifdef PNG_CHUNK_INTERNATIONAL_TEXT}
  4919. RegisterPngChunks([TChunkPngInternationalText]);
  4920. {$endif PNG_CHUNK_INTERNATIONAL_TEXT}
  4921. finalization
  4922. if (GCrcTable <> nil) then
  4923. Dispose(GCrcTable);
  4924. end.