GR32_PortableNetworkGraphic.pas 166 KB

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