c# free pdf viewer component : Add pages to pdf in preview application Library tool html .net winforms online REC-png3-part864

7. CHUNKORDERINGRULES
31
preventsuchproblemsbyrequiringPNGeditorstodiscardallunknownchunks,butthatisaveryunattractive
solution.Instead,PNGrequiresancillarychunksnottohaveorderingrestrictionslikethis.
Topreventthistypeofproblemwhileallowingforfutureextension,weputsomeconstraintsonboththe
behaviorofPNGeditorsandtheallowedorderingrequirementsforchunks.
7.1 BehaviorofPNGeditors
TherulesforPNGeditorsare:
Whencopyinganunknownunsafe-to-copyancillarychunk,aPNGeditormustnotmovethechunk
relativetoanycriticalchunk. Itcanrelocatethechunkfreelyrelativetootherancillarychunksthat
occurbetweenthesamepairofcriticalchunks. (Thisiswelldefinedsincetheeditormustnotadd,
delete,modify,orreordercriticalchunksifitispreservingunknownunsafe-to-copychunks.)
Whencopyinganunknownsafe-to-copyancillarychunk,aPNGeditormustnotmovethechunkfrom
beforeIDATtoafterIDATorviceversa.(ThisiswelldefinedbecauseIDATisalwayspresent.)Any
otherreorderingispermitted.
Whencopyingaknownancillarychunktype,aneditorneedonlyhonorthespecificchunkordering
rulesthatexistforthatchunktype. However,itcanalwayschoosetoapplytheabovegeneralrules
instead.
PNGeditorsmustgiveuponencounteringanunknowncriticalchunktype,becausethereisnoway
tobecertainthatavalidfilewillresultfrommodifyingafilecontainingsuchachunk. (Notethat
simplydiscardingthechunkisnotgoodenough,becauseitmighthaveunknownimplicationsforthe
interpretationofotherchunks.)
Theserulesareexpressedintermsofcopyingchunksfromaninputfiletoanoutputfile,buttheyapplyin
theobviouswayifaPNGfileismodifiedinplace.
SeealsoChunknamingconventions(Section3.3).
7.2 Orderingofancillarychunks
Theorderingrulesforanancillarychunktypecannotbeanystricterthanthis:
Unsafe-to-copychunkscanhaveorderingrequirementsrelativetocriticalchunks.
Safe-to-copychunkscanhaveorderingrequirementsrelativetoIDAT.
Theactualorderingrulesforanyparticularancillarychunktypemaybeweaker.Seeforexampletheordering
rulesforthestandardancillarychunktypes(Summaryofstandardchunks,Section4.3).
Decodersmustnotassumemoreaboutthepositioningofanyancillarychunkthanisspecifiedbythe
chunkorderingrules. Inparticular,itisnevervalidtoassumethataspecificancillarychunktypeoccurs
withanyparticularpositioningrelativetootherancillarychunks. (Forexample,itisunsafetoassumethat
Add pages to pdf in preview - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
add and delete pages in pdf online; add page number to pdf file
Add pages to pdf in preview - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
adding page numbers to pdf files; add page to pdf acrobat
32
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
yourprivateancillarychunkoccursimmediatelybeforeIEND. Evenifyourapplicationalwayswritesit
there,aPNGeditormighthaveinsertedsomeotherancillarychunkafterit.Butyoucansafelyassumethat
yourchunkwillremainsomewherebetweenIDATandIEND.)
7.3 Orderingofcriticalchunks
Criticalchunkscanhavearbitraryorderingrequirements,becausePNGeditorsarerequiredtogiveupifthey
encounterunknowncriticalchunks. Forexample,IHDRhasthespecialorderingrulethatitmustalways
appearfirst. APNGeditor,orindeedanyPNG-writingprogram,mustknowandfollowtheorderingrules
foranycriticalchunktypethatitcanemit.
8 MiscellaneousTopics
8.1 Filenameextension
Onsystemswherefilenamescustomarilyincludeanextensionsignifyingfiletype,theextension“.png”is
recommendedforPNGfiles.Lowercase“.png”ispreferrediffilenamesarecase-sensitive.
8.2 Internetmediatype
ThePNGauthorsintendtoregister“image/png”astheInternetMediaTypeforPNG[RFC-1521,RFC-
1590].Atthedateofthisdocument,themediatyperegistrationprocesshadnotbeencompleted. Itisrec-
ommendedthatimplementationsalsorecognizetheinterimmediatype“image/x-png”.
8.3 Macintoshfilelayout
IntheAppleMacintoshsystem,thefollowingconventionsarerecommended:
Thefour-bytefiletypecodeforPNGfilesis“PNGf”.(ThiscodehasbeenregisteredwithApplefor
PNGfiles.)Thecreatorcodewillvarydependingonthecreatingapplication.
ThecontentsofthedataforkmustbeaPNGfileexactlyasdescribedintherestofthisspecification.
Thecontents oftheresourceforkare unspecified. . Itmaybeemptyormaycontainapplication-
dependentresources.
WhentransferringaMacintoshPNGfiletoanon-Macintoshsystem,onlythedataforkshouldbetrans-
ferred.
C# WinForms Viewer: Load, View, Convert, Annotate and Edit PDF
Add text to PDF document in preview. • Add text box to PDF file in preview. Erase PDF pages. Miscellaneous. Search PDF text in preview.
add pages to an existing pdf; add a page to a pdf document
C# WPF Viewer: Load, View, Convert, Annotate and Edit PDF
PDF Protection. • Add signatures to PDF document. Erase PDF pages. Miscellaneous. • Select PDF text on viewer. • Search PDF text in preview.
add page numbers to pdf; add and remove pages from a pdf
9. RECOMMENDATIONSFORENCODERS
33
8.4 Multiple-imageextension
PNGitselfisstrictlyasingle-imageformat. However,itmaybenecessarytostoremultipleimageswithin
onefile;forexample,thisisneededtoconvertsomeGIFfiles.Inthefuture,amultiple-imageformatbased
onPNGmaybedefined. Suchaformatwillbeconsideredaseparatefileformatandwillhaveadifferent
signature.PNG-supportingapplicationsmayormaynotchoosetosupportthemultiple-imageformat.
SeeRationale:Whynotthesefeatures?(Section12.3).
8.5 Securityconsiderations
APNGfileordatastreamiscomposedofacollectionofexplicitlytyped“chunks”.Chunkswhosecontents
aredefinedbythespecificationcouldactuallycontainanything,includingmaliciouscode. Butthereisno
knownriskthatsuchmaliciouscodecouldbeexecutedontherecipient’scomputerasaresultofdecoding
thePNGimage.
Thepossiblesecurityrisksassociatedwithfuturechunktypescannotbespecifiedatthistime.Securityissues
willbeconsideredwhenevaluatingchunksproposedforregistrationaspublicchunks.Thereisnoadditional
securityriskassociatedwithunknownorunimplementedchunktypes,becausesuchchunkswillbeignored,
oratmostbecopiedintoanotherPNGfile.
ThetEXtandzTXtchunkscontaindatathatismeanttobedisplayedasplaintext. Itispossiblethatif
thedecoderdisplayssuchtextwithoutfilteringoutcontrolcharacters,especiallytheESC(escape)character,
certainsystemsorterminalscouldbehaveinundesirableandinsecureways. Werecommendthatdecoders
filteroutcontrolcharacterstoavoidthisrisk;seeRecommendationsforDecoders: Textchunkprocessing
(Section10.11).
Becauseeverychunk’slengthisavailableatitsbeginning,andbecauseeverychunkhasaCRCtrailer,there
isaveryrobustdefenseagainstcorrupteddataandagainstfraudulentchunksthatattempttooverflowthe
decoder’sbuffers.Also,thePNGsignaturebytesprovideearlydetectionofcommonfiletransmissionerrors.
AdecoderthatfailstocheckCRCscouldbesubjecttodatacorruption.Theonlylikelyconsequenceofsuch
corruptionisincorrectlydisplayedpixelswithintheimage. WorsethingsmighthappeniftheCRCofthe
IHDRchunkisnotcheckedandthewidthorheightfieldsarecorrupted.SeeRecommendationsforDecoders:
Errorchecking(Section10.1).
Apoorlywrittendecodermightbesubjecttobufferoverflow,becausechunkscanbeextremelylarge,upto
(2ˆ31)-1byteslong.Butproperlywrittendecoderswillhandlelargechunkswithoutdifficulty.
9 RecommendationsforEncoders
Thischaptergivessomerecommendationsforencoderbehavior. TheonlyabsoluterequirementonaPNG
encoderisthatitproducefilesthatconformtotheformatspecifiedintheprecedingchapters.However,best
resultswillusuallybeachievedbyfollowingtheserecommendations.
How to C#: Preview Document Content Using XDoc.Word
With the SDK, you can preview the document content according to the preview thumbnail by the ways as following. C# DLLs for Word File Preview. Add references:
add page number to pdf in preview; add page numbers to a pdf
How to C#: Preview Document Content Using XDoc.PowerPoint
C# DLLs: Preview PowerPoint Document. Add necessary XDoc.PowerPoint DLL libraries into your created C# application as references. RasterEdge.Imaging.Basic.dll.
add pages to pdf reader; add page numbers to pdf document
34
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
9.1 Sampledepthscaling
WhenencodinginputsamplesthathaveasampledepththatcannotbedirectlyrepresentedinPNG,theen-
codermustscalethesamplesuptoasampledepththatisallowedbyPNG.Themostaccuratescalingmethod
isthelinearequation
output = = ROUND(input t * * MAXOUTSAMPLE E / MAXINSAMPLE)
wheretheinputsamplesrangefrom0toMAXINSAMPLEandtheoutputsrangefrom0toMAXOUTSAM-
PLE(whichis(2ˆsampledepth)-1).
Acloseapproximationtothelinearscalingmethodcanbeachievedby“leftbitreplication”,whichisshifting
thevalidbitstobegininthemostsignificantbitandrepeatingthemostsignificantbitsintotheopenbits.This
methodisoftenfastertocomputethanlinearscaling. Asanexample,assumethat5-bitsamplesarebeing
scaledupto8bits.Ifthesourcesamplevalueis27(intherangefrom0-31),thentheoriginalbitsare:
4 3 3 2 2 1 1 0
------
1 1 1 0 0 1 1 1
Leftbitreplicationgivesavalueof222:
7 6 6 5 5 4 4 3
2 1 1 0
-----------
1 1 1 0 0 1 1 1
1 1 1 0
|=======| |===|
|
Leftmost Bits Repeated to Fill Open n Bits
|
Original Bits
whichmatchesthevaluecomputedbythelinearequation.Leftbitreplicationusuallygivesthesamevalue
aslinearscaling,andisneveroffbymorethanone.
Adistinctlylessaccurateapproximationisobtainedbysimplyleft-shiftingtheinputvalueandfillingthe
loworderbitswithzeroes. Thisschemecannotreproducewhiteexactly,sinceitdoesnotgenerateanall-
onesmaximumvalue;theneteffectistodarkentheimageslightly. Thismethodisnotrecommendedin
general,butitdoeshavetheeffectofimprovingcompression,particularlywhendealingwithgreater-than-
eight-bitsampledepths.Sincetherelativeerrorintroducedbyzero-fillscalingissmallathighsampledepths,
someencodersmaychoosetouseit.Zero-fillmustnotbeusedforalphachanneldata,however,sincemany
decoderswillspecial-casealphavaluesofallzeroesandallones.Itisimportanttorepresentboththosevalues
exactlyinthescaleddata.
WhentheencoderwritesansBITchunk,itisrequiredtodothescalinginsuchawaythatthehigh-order
bitsofthestoredsamplesmatchtheoriginaldata.Thatis,ifthesBITchunkspecifiesasampledepthofS,
thehigh-orderSbitsofthestoreddatamustagreewiththeoriginalS-bitdatavalues.Thisallowsdecoders
torecovertheoriginaldatabyshiftingright.Theaddedlow-orderbitsarenotconstrained.Notethatallthe
abovescalingmethodsmeetthisrestriction.
C# PDF insert image Library: insert images into PDF in C#.net, ASP
viewer component supports inserting image to PDF in preview without adobe Insert images into PDF form field. How to insert and add image, picture, digital photo
add page numbers to pdf document in preview; adding page numbers in pdf file
VB.NET PDF File Compress Library: Compress reduce PDF size in vb.
Remove bookmarks, annotations, watermark, page labels and article threads from PDF while compressing. Also a preview component enables compressing and
add page to pdf without acrobat; adding page numbers pdf
9. RECOMMENDATIONSFORENCODERS
35
Whenscalingupsourcedata,itisrecommendedthatthelow-orderbitsbefilledconsistentlyforallsamples;
thatis,thesamesourcevalueshouldgeneratethesamesamplevalueatanypixelposition. Thisimproves
compressionbyreducingthenumberofdistinctsamplevalues.However,thisisnotarequirement,andsome
encodersmaychoosenottofollowit.Forexample,anencodermightinsteadditherthelow-orderbits,im-
provingdisplayedimagequalityatthepriceofincreasingfilesize.
Insomeapplicationstheoriginalsourcedatamayhavearangethatisnotapowerof2.Thelinearscaling
equationstillworksforthiscase,althoughtheshiftingmethodsdonot. ItisrecommendedthatansBIT
chunknotbewrittenforsuchimages,sincesBITsuggeststhattheoriginaldatarangewasexactly0..2ˆS-1.
9.2 Encodergammahandling
SeeGammaTutorial(Chapter13)ifyouaren’talreadyfamiliarwithgammaissues.
ProperhandlingofgammaencodingandthegAMAchunkinanencoderdependsonthepriorhistoryofthe
samplevaluesandonwhetherthesevalueshavealreadybeenquantizedtointegers.
Iftheencoderhasaccesstosampleintensityvaluesinfloating-pointorhigh-precisionintegerform(perhaps
fromacomputerimagerenderer),thenitisrecommendedthattheencoderperformitsowngammaencoding
beforequantizingthedatatointegervaluesforstorageinthefile. Applyinggammaencodingatthisstage
resultsinimageswithfewerbandingartifactsatagivensampledepth,orallowssmallersampleswhilere-
tainingthesamevisualquality.
Alinearintensitylevel,expressedasafloating-pointvalueintherange0to1,canbeconvertedtoagamma-
encodedsamplevalueby
sample = = ROUND((intensity y ˆ ˆ encoder_gamma) ) * MAXSAMPLE)
Thefile_gammavaluetobewritteninthePNGgAMAchunkisthesameasencoder_gammainthisequation,
sinceweareassumingtheinitialintensityvalueislinear(ineffect,camera_gammais1.0).
Iftheimageisbeingwrittentoafileonly,theencoder_gammavaluecanbeselectedsomewhatarbitrarily.
Valuesof0.45or0.5aregenerallygoodchoicesbecausetheyarecommoninvideosystems,andsomost
PNGdecodersshoulddoagoodjobdisplayingsuchimages.
SomeimagerenderersmaysimultaneouslywritetheimagetoaPNGfileanddisplayiton-screen. Thedis-
playedpixelsshouldbegammacorrectedforthedisplaysystemandviewingconditionsinuse,sothatthe
userseesaproperrepresentationoftheintendedscene.Anappropriategammacorrectionvalueis
screen_gc = = viewing_gamma a / / display_gamma
Iftherendererwantstowritethesamegamma-correctedsamplevaluestothePNGfile,avoidingaseparate
gamma-encodingstepforfileoutput,thenthisscreen_gcvalueshouldbewritteninthegAMAchunk. This
willallowaPNGdecodertoreproducewhatthefile’soriginatorsawonscreenduringrendering(provided
thedecoderproperlysupportsarbitraryvaluesinagAMAchunk).
However,itisequallyreasonableforarenderertoapplygammacorrectionforscreendisplayusingagamma
appropriatetotheviewingconditions,andtoseparatelygamma-encodethesamplevaluesforfilestorage
VB.NET PDF insert image library: insert images into PDF in vb.net
inserting image to PDF in preview without adobe provide users the most individualized PDF page image inserting function, allowing developers to add and insert
adding page numbers pdf file; add a page to pdf file
How to C#: Preview Document Content Using XDoc.excel
following. C# DLLs: Preview Excel Document without Microsoft Office Installed. Add necessary references: RasterEdge.Imaging.Basic.dll.
add pages to pdf preview; adding page numbers to pdf document
36
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
usingastandardvalueofgammasuchas0.5.Infact,thisispreferable,sincesomePNGdecodersmaynot
accuratelydisplayimageswithunusualgAMAvalues.
Computergraphicsrenderersoftendonotperformgammaencoding,insteadmakingsamplevaluesdirectly
proportionaltoscenelightintensity.IfthePNGencoderreceivessamplevaluesthathavealreadybeenquan-
tizedintolinear-lightintegervalues,thereisnopointindoinggammaencodingonthem;thatwouldjustresult
infurtherlossofinformation.TheencodershouldjustwritethesamplevaluestothePNGfile.This“linear”
sampleencodingisequivalenttogammaencodingwithagammaof1.0,sographicsprogramsthatproduce
linearsamplesshouldalwaysemitagAMAchunkspecifyingagammaof1.0.
Whenthesamplevaluescomedirectlyfromapieceofhardware,thecorrectgAMAvalueisdeterminedby
thegammacharacteristicofthehardware.Inthecaseofvideodigitizers(“framegrabbers”),gAMAshould
be0.45or0.5forNTSC(possiblylessforPALorSECAM)sincevideocameratransferfunctionsarestan-
dardized.Imagescannersarelesspredictable. Theiroutputsamplesmaybelinear(gamma1.0)sinceCCD
sensorsthemselvesarelinear,orthescannerhardwaremayhavealreadyappliedgammacorrectiondesigned
tocompensatefordotgaininsubsequentprinting(gammaofabout0.57),orthescannermayhavecorrected
thesamplesfordisplayonaCRT(gammaof0.4-0.5).Youwillneedtorefertothescanner’smanual,oreven
scanacalibratedgraywedge,todeterminewhataparticularscannerdoes.
Fileformatconvertersgenerallyshouldnotattempttoconvertsuppliedimagestoadifferentgamma.Store
thedatainthePNGfilewithoutconversion,andrecordthesourcegammaifitisknown.Gammaalteration
atfileconversiontimecausesre-quantizationofthesetofintensitylevelsthatarerepresented,introducing
furtherroundofferrorwithlittlebenefit.It’salmostalwaysbettertojustcopythesamplevaluesintactfrom
theinputtotheoutputfile.
Insomecases,thesuppliedimagemaybeinanimageformat(e.g.,TIFF)thatcandescribethegammachar-
acteristicoftheimage. Insuchcases,afileformatconverterisstronglyencouragedtowriteaPNGgAMA
chunkthatcorrespondstotheknowngammaofthesourceimage. Notethatsomefileformatsspecifythe
gammaofthedisplaysystem,notthecamera.Iftheinputfile’sgammavalueisgreaterthan1.0,itisalmost
certainlyadisplaysystemgamma,andyoushoulduseitsreciprocalforthePNGgAMA.
Iftheencoderorfileformatconverterdoesnotknowhowanimagewasoriginallycreated,butdoesknow
thattheimagehasbeendisplayedsatisfactorilyonadisplaywithgammadisplay_gammaunderlighting
conditionswhereaparticularviewing_gammaisappropriate,thentheimagecanbemarkedashavingthe
file_gamma:
file_gamma = = viewing_gamma a / display_gamma
ThiswillallowviewersofthePNGfiletoseethesameimagethatthepersonrunningthefileformatcon-
vertersaw.Althoughthismaynotbepreciselythecorrectvalueoftheimagegamma,it’sbettertowritea
gAMAchunkwithanapproximatelyrightvaluethantoomitthechunkandforcePNGdecoderstoguessat
anappropriategamma.
Ontheotherhand,iftheimagefileisbeingconvertedaspartofa“bulk”conversion,withnoonelookingat
eachimage,thenitisbettertoomitthegAMAchunkentirely.Iftheimagegammahastobeguessedat,leave
ittothedecodertodotheguessing.
Gammadoesnotapplytoalphasamples;alphaisalwaysrepresentedlinearly.
C# HTML5 Viewer: Load, View, Convert, Annotate and Edit Raster
zoom in or zoom out images while in preview. to Tiff (.tif, .tiff) online, create PDF document from Supported annotation features includes add text comments to
add page pdf; adding page numbers to pdf in preview
9. RECOMMENDATIONSFORENCODERS
37
SeealsoRecommendationsforDecoders:Decodergammahandling(Section10.5).
9.3 Encodercolorhandling
SeeColorTutorial(Chapter14)ifyouaren’talreadyfamiliarwithcolorissues.
Ifitispossiblefortheencodertodeterminethechromaticitiesofthesourcedisplayprimaries,ortomake
astrongguessbasedontheoriginoftheimageorthehardwarerunningit,thentheencoderisstronglyen-
couragedtooutputthecHRMchunk.Ifitdoesso,thegAMAchunkshouldalsobewritten;decoderscando
littlewithcHRMifgAMAismissing.
VideocreatedwithrecentvideoequipmentprobablyusestheCCIR709primariesandD65whitepoint[ITU-
BT709],whichare:
R
G
B
White
x
0.640
0.300
0.150
0.3127
y
0.330
0.600
0.060
0.3290
AnolderbutstillverypopularvideostandardisSMPTE-C[SMPTE-170M]:
R
G
B
White
x
0.630
0.310
0.155
0.3127
y
0.340
0.595
0.070
0.3290
TheoriginalNTSCcolorprimarieshavenotbeenusedindecades. AlthoughyoumaystillfindtheNTSC
numberslistedinstandardsdocuments,youwon’tfindanyimagesthatactuallyusethem.
ScannersthatproducePNGfilesasoutputshouldinsertthefilterchromaticitiesintoacHRMchunkandthe
camera_gammaintoagAMAchunk.
Inthecaseofhand-drawnordigitallyeditedimages,youhavetodeterminewhatmonitortheywereviewed
onwhenbeingproduced.Manyimageeditingprogramsallowyoutospecifywhattypeofmonitoryouare
using.Thisisoftenbecausetheyareworkinginsomedevice-independentspaceinternally. Suchprograms
haveenoughinformationtowritevalidcHRMandgAMAchunks,andshoulddosoautomatically.
Iftheencoderiscompiledasaportionofacomputerimagerendererthatperformsfull-spectralrendering,
themonitorvaluesthatwereusedtoconvertfromtheinternaldevice-independentcolorspacetoRGBshould
bewrittenintothecHRMchunk.AnycolorsthatareoutsidethegamutofthechosenRGBdeviceshouldbe
clippedorotherwiseconstrainedtobewithinthegamut;PNGdoesnotstoreoutofgamutcolors.
Ifthecomputerimagerendererperformscalculationsdirectlyindevice-dependentRGBspace,acHRMchunk
shouldnotbewrittenunlessthescenedescriptionandrenderingparametershavebeenadjustedtolookgood
onaparticularmonitor.Inthatcase,thedataforthatmonitor(ifknown)shouldbeusedtoconstructacHRM
chunk.
Thereareoftencaseswhereanimage’sexactoriginsareunknown,particularlyifitbeganlifeinsomeother
format.Afewimageformatsstorecalibrationinformation,whichcanbeusedtofillinthecHRMchunk.For
example,allPhotoCDimagesusetheCCIR709primariesandD65whitepoint,sothesevaluescanbewritten
38
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
intothecHRMchunkwhenconvertingaPhotoCDfile.PhotoCDalsousestheSMPTE-170Mtransferfunc-
tion,whichiscloselyapproximatedbyagAMAof0.5. (PhotoCDcanstorecolorsoutsidetheRGBgamut,
sotheimagedatawillrequiregamutmappingbeforewritingtoPNGformat.)TIFF6.0filescanoptionally
storecalibrationinformation,whichifpresentshouldbeusedtoconstructthecHRMchunk. GIFandmost
otherformatsdonotstoreanycalibrationinformation.
ItisnotrecommendedthatfileformatconvertersattempttoconvertsuppliedimagestoadifferentRGBcolor
space.StorethedatainthePNGfilewithoutconversion,andrecordthesourceprimarychromaticitiesifthey
areknown. Colorspacetransformationatfileconversiontimeisabadideabecauseofgamutmismatches
androundingerrors.Aswithgammaconversions,it’sbettertostorethedatalosslesslyandincuratmostone
conversionwhentheimageisfinallydisplayed.
SeealsoRecommendationsforDecoders:Decodercolorhandling(Section10.6).
9.4 Alphachannelcreation
Thealphachannelcanberegardedeitherasamaskthattemporarilyhidestransparentpartsoftheimage,or
asameansforconstructinganon-rectangularimage. Inthefirstcase,thecolorvaluesoffullytransparent
pixelsshouldbepreservedforfutureuse.Inthesecondcase,thetransparentpixelscarrynousefuldataand
aresimplytheretofillouttherectangularimagearearequiredbyPNG.Inthiscase,fullytransparentpixels
shouldallbeassignedthesamecolorvalueforbestcompression.
Imageauthorsshouldkeepinmindthepossibilitythatadecoderwillignoretransparencycontrol. Hence,
thecolorsassignedtotransparentpixelsshouldbereasonablebackgroundcolorswheneverfeasible.
Forapplicationsthatdonotrequireafullalphachannel,orcannotaffordthepriceincompressionefficiency,
thetRNStransparencychunkisalsoavailable.
Iftheimagehasaknownbackgroundcolor,thiscolorshouldbewritteninthebKGDchunk.Evendecoders
thatignoretransparencymayusethebKGDcolortofillunusedscreenarea.
Iftheoriginal image haspremultiplied(also called“associated”) alpha data, , convertitto PNG’snon-
premultipliedformatbydividingeachsamplevaluebythecorrespondingalphavalue,thenmultiplyingby
themaximumvaluefortheimagebitdepth,androundingtothenearestinteger.Invalidpremultiplieddata,
thesamplevaluesneverexceedtheircorrespondingalphavalues,sotheresultofthedivisionshouldalways
beintherange0to1.Ifthealphavalueiszero,outputblack(zeroes).
9.5 Suggestedpalettes
APLTEchunkcanappearintruecolorPNGfiles.Insuchfiles,thechunkisnotanessentialpartoftheimage
data,butsimplyrepresentsasuggestedpalettethatviewersmayusetopresenttheimageonindexed-color
displayhardware.Asuggestedpaletteisofnointeresttoviewersrunningontruecolorhardware.
Ifanencoderchoosestoprovideasuggestedpalette,itisrecommendedthatahISTchunkalsobewritten
toindicatetherelativeimportanceofthepaletteentries. Thehistogramvaluesaremosteasilycomputed
9. RECOMMENDATIONSFORENCODERS
39
as“nearestneighbor”counts,thatis,theapproximateusageofeachpaletteentryifnoditheringisapplied.
(Thesecountswilloftenbeavailableforfreeasaconsequenceofdevelopingthesuggestedpalette.)
Forimagesofcolortype2(truecolorwithoutalphachannel),itisrecommendedthatthepaletteandhistogram
becomputedwithreferencetotheRGBdataonly,ignoringanytransparent-colorspecification.Ifthefileuses
transparency(hasatRNSchunk),viewerscaneasilyadapttheresultingpaletteforusewiththeirintended
backgroundcolor.TheyneedonlyreplacethepaletteentryclosesttothetRNScolorwiththeirbackground
color(whichmayormaynotmatchthefile’sbKGDcolor,ifany).
Forimagesofcolortype6(truecolorwithalphachannel),itisrecommendedthatabKGDchunkappearand
thatthepaletteandhistogrambecomputedwithreferencetotheimageasitwouldappearaftercomposit-
ingagainstthespecifiedbackgroundcolor. Thisdefinitionisnecessarytoensurethatusefulpaletteentries
aregeneratedforpixelshavingfractionalalphavalues. Theresultingpalettewillprobablyonlybeuseful
toviewersthatpresenttheimageagainstthesamebackgroundcolor. ItisrecommendedthatPNGeditors
deleteorrecomputethepaletteiftheyalterorremovethebKGDchunkinanimageofcolortype6.IfPLTE
appearswithoutbKGDinanimageofcolortype6,thecircumstancesunderwhichthepalettewascomputed
areunspecified.
9.6 Filterselection
Forimagesofcolortype3(indexedcolor),filtertype0(None)isusuallythemosteffective.Notethatcolor
imageswith256orfewercolorsshouldalmostalwaysbestoredinindexedcolorformat;truecolorformatis
likelytobemuchlarger.
Filtertype0isalsorecommendedforimagesofbitdepthslessthan8.Forlow-bit-depthgrayscaleimages,
itmaybeanetwintoexpandtheimageto8-bitrepresentationandapplyfiltering,butthisisrare.
Fortruecolorandgrayscaleimages,anyofthefivefiltersmayprovethemosteffective.Ifanencoderusesa
fixedfilter,thePaethfilterismostlikelytobethebest.
Forbestcompressionoftruecolorandgrayscaleimages,werecommendanadaptivefilteringapproachin
whichafilterischosenforeachscanline. Thefollowingsimpleheuristichasperformedwellinearlytests:
computetheoutputscanlineusingallfivefilters,andselectthefilterthatgivesthesmallestsumofabsolute
valuesofoutputs.(Considertheoutputbytesassigneddifferencesforthistest.)Thismethodusuallyoutper-
formsanysinglefixedfilterchoice. However,itislikelythatmuchbetterheuristicswillbefoundasmore
experienceisgainedwithPNG.
Filteringaccordingtotheserecommendationsiseffectiveoninterlacedaswellasnoninterlacedimages.
9.7 Textchunkprocessing
Anonemptykeywordmustbeprovidedforeachtextchunk.Thegenerickeyword“Comment”canbeused
ifnobetterdescriptionofthetextisavailable. Ifauser-suppliedkeywordisused,besuretocheckthatit
meetstherestrictionsonkeywords.
40
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
PNGtextstringsareexpectedtousetheLatin-1characterset.Encodersshouldavoidstoringcharactersthat
arenotdefinedinLatin-1,andshouldprovidecharactercoderemappingifthelocalsystem’scharactersetis
notLatin-1.
Encodersshoulddiscouragethecreationofsinglelinesoftextlongerthan79characters,inordertofacilitate
easyreading.
Itisrecommendedthattextitemslessthan1K(1024bytes)insizeshouldbeoutputusinguncompressed
tEXtchunks. Inparticular,itisrecommendedthatthebasictitleandauthorkeywordsshouldalwaysbe
outputusinguncompressedtEXtchunks. Lengthydisclaimers,ontheotherhand,areidealcandidatesfor
zTXt.
PlacinglargetEXtandzTXtchunksaftertheimagedata(afterIDAT)canspeedupimagedisplayinsome
situations,sincethedecoderwon’thavetoreadoverthetexttogettotheimagedata.Butitisrecommended
thatsmalltextchunks,suchastheimagetitle,appearbeforeIDAT.
9.8 Useofprivatechunks
ApplicationscanusePNGprivatechunkstocarryinformationthatneednotbeunderstoodbyotherapplica-
tions.Suchchunksmustbegivennameswithlowercasesecondletters,toensurethattheycanneverconflict
withanyfuturepublicchunkdefinition.Note,however,thatthereisnoguaranteethatsomeotherapplication
willnotusethesameprivatechunkname.Ifyouuseaprivatechunktype,itisprudenttostoreadditional
identifyinginformationatthebeginningofthechunkdata.
Useanancillarychunktype(lowercasefirstletter),notacriticalchunktype,forallprivatechunksthatstore
informationthatisnotabsolutelyessentialtoviewtheimage.Creationofprivatecriticalchunksisdiscour-
agedbecausetheyrenderPNGfilesunportable.Suchchunksshouldnotbeusedinpubliclyavailablesoft-
wareorfiles.Ifprivatecriticalchunksareessentialforyourapplication,itisrecommendedthatoneappear
nearthestartofthefile,sothatastandarddecoderneednotreadveryfarbeforediscoveringthatitcannot
handlethefile.
Ifyouwantothersoutsideyourorganizationtounderstandachunktypethatyouinvent,contactthemain-
tainersofthePNGspecificationtosubmitaproposedchunknameanddefinitionforadditiontothelistof
special-purposepublicchunks(seeAdditionalchunktypes,Section4.4).Notethataproposedpublicchunk
name(withuppercasesecondletter)mustnotbeusedinpubliclyavailablesoftwareorfilesuntilregistration
hasbeenapproved.
Ifanancillarychunkcontainstextualinformationthatmightbeofinteresttoahumanuser,youshouldnot
createaspecialchunktypeforit. InsteaduseatEXtchunkanddefineasuitablekeyword. Thatway,the
informationwillbeavailabletousersnotusingyoursoftware.
KeywordsintEXtchunksshouldbereasonablyself-explanatory,sincetheideaistoletotherusersfigure
outwhatthechunkcontains.Ifofgeneralusefulness,newkeywordscanberegisteredwiththemaintainers
ofthePNGspecification.Butitispermissibletousekeywordswithoutregisteringthemfirst.
Documents you may be interested
Documents you may be interested