c# free pdf viewer component : Add a page to a pdf file application Library tool html .net winforms online REC-png4-part865

10. RECOMMENDATIONSFORDECODERS
41
9.9 Privatetypeandmethodcodes
Thisspecificationdefinesthemeaningofonlysomeofthepossiblevaluesofsomefields. Forexample,
onlycompressionmethod0andfiltertypes0through4aredefined.Numbersgreaterthan127mustbeused
wheninventingexperimentalorprivatedefinitionsofvaluesforanyofthesefields.Numbersbelow128are
reservedforpossiblefuturepublicextensionsofthisspecification. Notethatuseofprivatetypecodesmay
renderafileunreadablebystandarddecoders.Suchcodesarestronglydiscouragedexceptforexperimental
purposes,andshouldnotappearinpubliclyavailablesoftwareorfiles.
10 RecommendationsforDecoders
Thischaptergivessomerecommendationsfordecoderbehavior. TheonlyabsoluterequirementonaPNG
decoderisthatitsuccessfullyreadanyfileconformingtotheformatspecifiedintheprecedingchapters.
However,bestresultswillusuallybeachievedbyfollowingtheserecommendations.
10.1 Errorchecking
Toensureearlydetectionofcommonfile-transferproblems,decodersshouldverifythatalleightbytesof
thePNGfilesignaturearecorrect. (SeeRationale:PNGfilesignature,Section12.11.)Adecodercanhave
additionalconfidenceinthefile’sintegrityifthenexteightbytesareanIHDRchunkheaderwiththecorrect
chunklength.
UnknownchunktypesmustbehandledasdescribedinChunknamingconventions(Section3.3). Anun-
knownchunktypeisnottobetreatedasanerrorunlessitisacriticalchunk.
ItisstronglyrecommendedthatdecodersshouldverifytheCRConeachchunk.
Insomesituationsitisdesirabletocheckchunkheaders(lengthandtypecode)beforereadingthechunk
dataandCRC. ThechunktypecanbecheckedforplausibilitybyseeingwhetherallfourbytesareASCII
letters(codes65-90and97-122);notethatthisneedonlybedoneforunrecognizedtypecodes. Ifthetotal
filesizeisknown(fromfilesysteminformation,HTTPprotocol,etc),thechunklengthcanbecheckedfor
plausibilityaswell.
IfCRCsarenotchecked,dropped/addeddatabytesoranerroneouschunklengthcancausethedecoderto
getoutofstepandmisinterpretsubsequentdataasachunkheader. Verifyingthatthechunktypecontains
lettersisaninexpensivewayofprovidingearlyerrordetectioninthissituation.
Forknown-lengthchunkssuchasIHDR,decodersshouldtreatanunexpectedchunklengthasanerror.Future
extensionstothisspecificationwillnotaddnewfieldstoexistingchunks;instead,newchunktypeswillbe
addedtocarrynewinformation.
Unexpectedvaluesinfieldsofknownchunks(forexample,anunexpectedcompressionmethodintheIHDR
chunk)mustbecheckedforandtreatedaserrors.However,itisrecommendedthatunexpectedfieldvalues
betreatedasfatalerrorsonlyincriticalchunks.Anunexpectedvalueinanancillarychunkcanbehandled
Add a page to a pdf file - 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 page number to pdf document; add page numbers to a pdf document
Add a page to a pdf file - 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 in reader; add page number to pdf
42
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
byignoringthewholechunkasthoughitwereanunknownchunktype.(Thisrecommendationassumesthat
thechunk’sCRChasbeenverified.IndecodersthatdonotcheckCRCs,itissafertotreatanyunexpected
valueasindicatingacorruptedfile.)
10.2 Pixeldimensions
Non-squarepixelscanberepresented(seethepHYschunk),butviewersarenotrequiredtoaccountforthem;
aviewercanpresentanyPNGfileasthoughitspixelsaresquare.
Conversely,viewersrunningondisplayhardwarewithnon-squarepixelsarestronglyencouragedtorescale
imagesforproperdisplay.
10.3 Truecolorimagehandling
ToachievePNG’sgoalofuniversalinterchangeability,decodersarerequiredtoacceptalltypesofPNGim-
age:indexed-color,truecolor,andgrayscale.Viewersrunningonindexed-colordisplayhardwareneedtobe
abletoreducetruecolorimagestoindexedformatforviewing.Thisprocessisusuallycalled“colorquanti-
zation”.
Asimple,fastwayofdoingthisistoreducetheimagetoafixedpalette.Paletteswithuniformcolorspac-
ing(“colorcubes”)areusuallyusedtominimizetheper-pixelcomputation. Forphotograph-likeimages,
ditheringisrecommendedtoavoiduglycontoursinwhatshouldbesmoothgradients;however,dithering
introducesgraininessthatcanbeobjectionable.
Thequalityofrenderingcanbeimprovedsubstantiallybyusingapalettechosenspecificallyfortheimage,
sinceacolorcubeusuallyhasnumerousentriesthatareunusedinanyparticularimage.Thisapproachre-
quiresmorework,firstinchoosingthepalette,andsecondinmappingindividualpixelstotheclosestavail-
ablecolor.PNGallowstheencodertosupplyasuggestedpaletteinaPLTEchunk,butnotallencoderswill
doso,andthesuggestedpalettemaybeunsuitableinanycase(itmayhavetoomanyortoofewcolors).
High-qualityviewerswillthereforeneedtohaveapaletteselectionroutineathand.Alargelookuptableis
usuallythemostfeasiblewayofmappingindividualpixelstopaletteentrieswithadequatespeed.
Numerousimplementationsofcolorquantizationareavailable.ThePNGreferenceimplementation,libpng,
includescodeforthepurpose.
10.4 Sampledepthrescaling
DecodersmaywishtoscalePNGdatatoalessersampledepth(dataprecision)fordisplay. Forexample,
16-bitdatawillneedtobereducedto8-bitdepthforuseonmostpresent-daydisplayhardware. Reduction
of8-bitdatato5-bitdepthisalsocommon.
Themostaccuratescalingisachievedbythelinearequation
output = = ROUND(input t * * MAXOUTSAMPLE E / MAXINSAMPLE)
C# PDF File & Page Process Library SDK for C#.net, ASP.NET, MVC
C# File: Split PDF; C# Page: Insert PDF pages; C# Page: Delete PDF pages; C# C# Read: PDF Image Extract; C# Write: Insert text into PDF; C# Write: Add Image to
add page numbers pdf; add page numbers to pdf files
VB.NET PDF Password Library: add, remove, edit PDF file password
On this page, we will illustrate how to protect PDF document via Add necessary references Visual Basic coding example will help you open an encrypted PDF file.
add page numbers to pdf in reader; add page to pdf preview
10. RECOMMENDATIONSFORDECODERS
43
where
MAXINSAMPLE = (2ˆsampledepth)-1
MAXOUTSAMPLE = (2ˆdesired_sampledepth)-1
A
slightly
less
accurate
conversion
is
achieved
by
simply
shifting
right
by
sampledepth-desired_sampledepthplaces. Forexample, , to o reduce 16-bit samples to 8-bit,
oneneedonlydiscardthelow-orderbyte. Inmanysituationstheshiftmethodissufficientlyaccuratefor
displaypurposes,anditiscertainlymuchfaster. (Butifgammacorrectionisbeingdone,samplerescaling
canbemergedintothegammacorrectionlookuptable,asisillustratedinDecodergammahandling,Section
10.5.)
WhenansBITchunkispresent,theoriginalpre-PNGdatacanberecoveredbyshiftingrighttothesample
depthspecifiedbysBIT.Notethatlinearscalingwillnotnecessarilyreproducetheoriginaldata,because
theencoderisnotrequiredtohaveusedlinearscalingtoscalethedataup.However,theencoderisrequired
tohaveusedamethodthatpreservesthehigh-orderbits,soshiftingalwaysworks. Thisistheonlycasein
whichshiftingmightbesaidtobemoreaccuratethanlinearscaling.
WhencomparingpixelvaluestotRNSchunkvaluestodetecttransparentpixels,itisnecessarytodothe
comparisonexactly.Therefore,transparentpixeldetectionmustbedonebeforereducingsampleprecision.
10.5 Decodergammahandling
SeeGammaTutorial(Chapter13)ifyouaren’talreadyfamiliarwithgammaissues.
Toproducecorrecttonereproduction,agoodimagedisplayprogramshouldtakeintoaccountthegammas
oftheimagefileandthedisplaydevice,aswellastheviewing_gammaappropriatetothelightingconditions
nearthedisplay.Thiscanbedonebycalculating
gbright = insample / MAXINSAMPLE
bright = = gbright t ˆ (1.0 0 / / file_gamma)
vbright = bright t ˆ ˆ viewing_gamma
gcvideo = vbright ˆ ˆ (1.0 0 / / display_gamma)
fbval = = ROUND(gcvideo o * * MAXFBVAL)
whereMAXINSAMPLEis themaximumsample valueinthe file(255 for8-bit, 65535for16-bit, etc),
MAXFBVAListhemaximumvalueofaframebuffersample(255for8-bit,31for5-bit,etc),insample
isthevalueofthesampleinthePNGfile,andfbvalisthevaluetowriteintotheframebuffer. Thefirst
lineconvertsfromintegersamplesintoanormalized0to1floatingpointvalue,thesecondundoesthegamma
encodingoftheimagefiletoproducealinearintensityvalue,thethirdadjustsfortheviewingconditions,
thefourthcorrectsforthedisplaysystem’sgammavalue,andthefifthconvertstoanintegerframebuffer
sample.Inpractice,thesecondthroughfourthlinescanbemergedinto
gcvideo = gbrightˆ(viewing_gamma a / / (file_gamma*display_gamma))
soastoperformonlyonepowercalculation.Forcolorimages,theentirecalculationisperformedseparately
forR,G,andBvalues.
C# PDF Password Library: add, remove, edit PDF file password in C#
your PDF document in C# project, XDoc.PDF provides some PDF security settings. On this page, we will talk about how to achieve this via Add necessary references
add page number to pdf reader; add pages to pdf file
VB.NET PDF File & Page Process Library SDK for vb.net, ASP.NET
there is a newly created page, you may need to add it into Files, adding a page into PDF document, deleting unnecessary page from PDF file and changing
add page number to pdf online; add a page to a pdf file
44
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
Itisnotnecessarytoperformtranscendentalmathforeverypixel.Instead,computealookuptablethatgives
thecorrectoutputvalueforeverypossiblesamplevalue.Thisrequiresonly256calculationsperimage(for
8-bitaccuracy),notoneorthreecalculationsperpixel. Foranindexed-colorimage,aone-timecorrection
ofthepaletteissufficient,unlesstheimageusestransparencyandisbeingdisplayedagainstanonuniform
background.
Insomecaseseventhecostofcomputingagammalookuptablemaybeaconcern.Inthesecases,viewers
areencouragedtohaveprecomputedgammacorrectiontablesforfile_gammavaluesof1.0and0.5with
somereasonablechoiceofviewing_gammaanddisplay_gamma,andtousethetableclosesttothegamma
indicatedinthefile.Thiswillproduceacceptableresultsforthemajorityofrealfiles.
Whentheincomingimagehasunknowngamma(nogAMAchunk),choosealikelydefaultfile_gammavalue,
butallowtheusertoselectanewoneiftheresultprovestoodarkortoolight.
Inpractice,itisoftendifficulttodeterminewhatvalueofdisplay_gammashouldbeused.Insystemswithno
built-ingammacorrection,thedisplay_gammaisdeterminedentirelybytheCRT.AssumingaCRT_gamma
of2.5isrecommended,unlessyouhavedetailedcalibrationmeasurementsofthisparticularCRTavailable.
However,manymodernframebuffershavelookuptablesthatareusedtoperformgammacorrection,and
onthesesystemsthedisplay_gammavalueshouldbethegammaofthelookuptableandCRTcombined.
Youmaynotbeabletofindoutwhatthelookuptablecontainsfromwithinanimageviewerapplication,
soyoumayhavetoasktheuserwhatthesystem’sgammavalueis.Unfortunately,differentmanufacturers
usedifferentwaysofspecifyingwhatshouldgointothelookuptable,sointerpretationofthesystemgamma
valueissystem-dependent.GammaTutorial(Chapter13)givessomeexamples.
Theresponseofrealdisplaysisactually morecomplexthancanbedescribedbyasinglenumber(dis-
play_gamma).Ifactualmeasurementsofthemonitor’slightoutputasafunctionofvoltageinputareavail-
able,thefourthandfifthlinesofthecomputationabovecanbereplacedbyalookupinthesemeasurements,
tofindtheactualframebuffervaluethatmostnearlygivesthedesiredbrightness.
Thevalueofviewing_gammadependsonlightingconditions;seeGammaTutorial(Chapter13)formore
detail. Ideally,aviewerwouldallowtheusertospecifyviewing_gamma, , eitherdirectlynumerically,or
viaselectingfrom“brightsurround”,“dimsurround”,and“darksurround”conditions. Viewersthatdon’t
wanttodothisshouldjustassumeavalueforviewing_gammaof1.0,sincemostcomputerdisplayslivein
brightly-litrooms.
Whenviewingimagesthataredigitizedfromvideo,orthataredestinedtobecomevideoframes,theuser
mightwanttosettheviewing_gammatoabout1.25regardlessoftheactuallevelofroomlighting.Thisvalue
ofviewing_gammais“builtinto”NTSCvideopractice,anddisplayinganimagewiththatviewing_gamma
allowstheusertoseewhataTVsetwouldshowunderthecurrentroomlightingconditions.(Thisisnotthe
samethingastryingtoobtainthemostaccuraterenditionofthecontentofthescene,whichwouldrequire
adjustingviewing_gammatocorrespondtotheroomlightinglevel.)Thisisanotherreasonviewersmight
wanttoallowuserstoadjustviewing_gammadirectly.
C# PDF insert image Library: insert images into PDF in C#.net, ASP
using RasterEdge.Imaging.Basic; using RasterEdge.XDoc.PDF; Have a try with this sample C#.NET code to add an image to the first page of PDF file.
adding a page to a pdf document; add a blank page to a pdf
VB.NET PDF insert image library: insert images into PDF in vb.net
using RasterEdge.XDoc.PDF; Have a try with this sample VB.NET code to add an image to the first page of PDF file. ' Open a document.
add blank page to pdf preview; add page number to pdf hyperlink
10. RECOMMENDATIONSFORDECODERS
45
10.6 Decodercolorhandling
SeeColorTutorial(Chapter14)ifyouaren’talreadyfamiliarwithcolorissues.
Inmanycases,decoderswilltreatimagedatainPNGfilesasdevice-dependentRGBdataanddisplayit
withoutmodification(exceptforappropriategammacorrection). ThisprovidesthefastestdisplayofPNG
images. Butunlesstheviewerusesexactlythesamedisplayhardwareastheoriginalimageauthorused,
thecolorswillnotbeexactlythesameastheoriginalauthorsaw,particularlyfordarkerornear-neutralcol-
ors.ThecHRMchunkprovidesinformationthatallowsclosercolormatchingthanthatprovidedbygamma
correctionalone.
DecoderscanusethecHRMdatatotransformtheimagedatafromRGBtoXYZandthenceintoaperceptually
linearcolorspacesuchasCIELAB.Theycanthenpartitionthecolorstogenerateanoptimalpalette,because
thegeometricdistancebetweentwocolorsinCIELABisstronglyrelatedtohowdifferentthosecolorsappear
(unlike,forexample,RGBorXYZspaces).Theresultingpaletteofcolors,oncetransformedbackintoRGB
colorspace,couldbeusedfordisplayorwrittenintoaPLTEchunk.
DecodersthatarepartofimageprocessingapplicationsmightalsotransformimagedataintoCIELABspace
foranalysis.
Inapplicationswherecolorfidelityiscritical,suchasproductdesign,scientificvisualization,medicine,archi-
tecture,oradvertising,decoderscantransformtheimagedatafromsource_RGBtothedisplay_RGBspace
ofthemonitorusedtoviewtheimage.Thisinvolvescalculatingthematrixtogofromsource_RGBtoXYZ
andthematrixtogofromXYZtodisplay_RGB,thencombiningthemtoproducetheoveralltransformation.
Thedecoderisresponsibleforimplementinggamutmapping.
DecodersrunningonplatformsthathaveaColorManagementSystem(CMS)canpasstheimagedata,gAMA
andcHRMvaluestotheCMSfordisplayorfurtherprocessing.
DecodersthatprovidecolorprintingfacilitiescanusethefacilitiesinLevel2PostScripttospecifyimage
dataincalibratedRGBspaceorinadevice-independentcolorspacesuchasXYZ.Thiswillprovidebetter
colorfidelitythanasimpleRGBtoCMYKconversion. ThePostScriptLanguageReferencemanualgives
examplesofthisprocess[POSTSCRIPT].Suchdecodersareresponsibleforimplementinggamutmapping
betweensource_RGB(specifiedinthecHRMchunk)andthetargetprinter.ThePostScriptinterpreteristhen
responsibleforproducingtherequiredcolors.
DecoderscanusethecHRMdatatocalculateanaccurategrayscalerepresentationofacolorimage. Con-
versionfromRGBtograyissimplyacaseofcalculatingtheY(luminance)componentofXYZ,whichisa
weightedsumoftheRGandBvalues.Theweightsdependonthemonitortype,i.e.,thevaluesinthecHRM
chunk.DecodersmaywishtodothisforPNGfileswithnocHRMchunk.Inthatcase,areasonabledefault
wouldbetheCCIR709primaries[ITU-BT709].DonotusetheoriginalNTSCprimaries,unlessyoureally
dohaveanimagecolor-balancedforsuchamonitor. FewmonitorseverusedtheNTSCprimaries,sosuch
imagesareprobablynonexistentthesedays.
C# PDF File Split Library: Split, seperate PDF into multiple files
If your page number is set as 1, then the two output PDF files will contains the first page and the later C# DLLs: Split PDF Document. Add necessary references:
add pdf pages to word; add multi page pdf to word document
VB.NET PDF File Split Library: Split, seperate PDF into multiple
Length outputFilePaths.Add(Program.RootPath + "\\" outputFileName + "_" + i.ToString() + ".pdf") Next ' Split input PDF file to 4 files: ' File 0: page 0
add page numbers to pdf reader; add pages to pdf in preview
46
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
10.7 Backgroundcolor
ThebackgroundcolorgivenbybKGDwilltypicallybeusedtofillunusedscreenspacearoundtheimage,as
wellasanytransparentpixelswithintheimage.(Thus,bKGDisvalidandusefulevenwhentheimagedoes
notusetransparency.) IfnobKGDchunkispresent,theviewerwillneedtomakeitsowndecisionabouta
suitablebackgroundcolor.
Viewersthathaveaspecificbackgroundagainstwhichtopresenttheimage(suchasWebbrowsers)should
ignorethebKGDchunk,ineffectoverridingbKGDwiththeirpreferredbackgroundcolororbackgroundim-
age.
ThebackgroundcolorgivenbybKGDisnottobeconsideredtransparent,evenifithappenstomatchthe
colorgivenbytRNS(or,inthecaseofanindexed-colorimage,referstoapaletteindexthatismarkedas
transparentbytRNS).Otherwiseonewouldhavetoimaginesomething“behindthebackground”tocom-
positeagainst.Thebackgroundcoloriseitherusedasbackgroundorignored;itisnotanintermediatelayer
betweenthePNGimageandsomeotherbackground.
Indeed,itwillbecommonthatbKGDandtRNSspecifythesamecolor,sincethenadecoderthatdoesnotim-
plementtransparencyprocessingwillgivetheintendeddisplay,atleastwhennopartially-transparentpixels
arepresent.
10.8 Alphachannelprocessing
Inthemostgeneralcase,thealphachannelcanbeusedtocompositeaforegroundimageagainstabackground
image;thePNGfiledefinestheforegroundimageandthetransparencymask,butnotthebackgroundimage.
Decodersarenotrequiredtosupportthismostgeneralcase.Itisexpectedthatmostwillbeabletosupport
compositingagainstasinglebackgroundcolor,however.
Theequationforcomputingacompositedsamplevalueis
output = = alpha a * * foreground d + (1-alpha) * * background
wherealphaandtheinputandoutputsamplevaluesareexpressedasfractionsintherange0to1.Thiscom-
putationshouldbeperformedwithlinear(non-gamma-encoded)samplevalues.Forcolorimages,thecom-
putationisdoneseparatelyforR,G,andBsamples.
Thefollowingcodeillustratesthegeneralcaseofcompositingaforegroundimageoverabackgroundimage.
Itassumesthatyouhavetheoriginalpixeldataavailableforthebackgroundimage,andthatoutputistoa
framebufferfordisplay.Othervariantsarepossible;seethecommentsbelowthecode.Thecodeallowsthe
sampledepthsandgammavaluesofforegroundimage,backgroundimage,andframebuffer/CRTalltobe
different.Don’tassumetheyarethesamewithoutchecking.
ThiscodeisstandardC,withlinenumbersaddedforreferenceinthecommentsbelow.
10. RECOMMENDATIONSFORDECODERS
47
01
int foreground[4];
/* image e pixel: R, G, B, A */
02
int background[3];
/* background d pixel: R, G, B */
03
int fbpix[3];
/* frame e buffer pixel */
04
int fg_maxsample;
/* foreground d max sample */
05
int bg_maxsample;
/* background d max sample */
06
int fb_maxsample;
/* frame e buffer max sample */
07
int ialpha;
08
float alpha, compalpha;
09
float gamfg, linfg, gambg, , linbg, , comppix, gcvideo;
/* Get max sample values s in n data and frame buffer */
10
fg_maxsample = (1 « fg_sample_depth) ) - - 1;
11
bg_maxsample = (1 « bg_sample_depth) ) - - 1;
12
fb_maxsample = (1 « frame_buffer_sample_depth) ) - - 1;
/*
* Get integer version n of f alpha.
* Check for opaque and d transparent t special cases;
* no compositing needed d if f so.
*
* We show the whole e gamma a decode/correct process in
* floating point, but t it t would more likely be done
* with lookup tables.
*/
13
ialpha = foreground[3];
48
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
14
if (ialpha == 0) {
/*
* Foreground image e is s transparent here.
* If the background d image e is already in the frame
* buffer, there e is s nothing to do.
*/
15
;
16
} else if (ialpha == = fg_maxsample) ) {
/*
* Copy foreground d pixel l to frame buffer.
*/
17
for (i = 0; i < 3; ; i++) ) {
18
gamfg = (float) ) foreground[i] ] / fg_maxsample;
19
linfg = pow(gamfg, , 1.0/fg_gamma);
20
comppix = linfg;
21
gcvideo = pow(comppix,viewing_gamma/display_gamma);
22
fbpix[i] = (int) ) (gcvideo o * fb_maxsample + 0.5);
23
}
24
} else {
/*
* Compositing is s necessary.
* Get floating-point t alpha a and its complement.
* Note: alpha is s always s linear; gamma does not
* affect it.
*/
25
alpha = (float) ialpha a / / fg_maxsample;
26
compalpha = 1.0 - - alpha;
27
for (i = 0; i < 3; ; i++) ) {
/*
* Convert foreground d and d background to floating
* point, then n linearize e (undo gamma encoding).
*/
28
gamfg = (float) ) foreground[i] ] / fg_maxsample;
29
linfg = pow(gamfg, , 1.0/fg_gamma);
30
gambg = (float) ) background[i] ] / bg_maxsample;
31
linbg = pow(gambg, , 1.0/bg_gamma);
/*
* Composite.
*/
32
comppix = linfg g * * alpha + linbg * compalpha;
/*
* Gamma correct t for r display.
* Convert to o integer r frame buffer pixel.
*/
33
gcvideo = pow(comppix,viewing_gamma/display_gamma);
34
fbpix[i] = (int) ) (gcvideo o * fb_maxsample + 0.5);
35
}
36
}
10. RECOMMENDATIONSFORDECODERS
49
Variations:
1. IfoutputistoanotherPNGimagefileinsteadofaframebuffer,lines21,22,33,and34shouldbe
changedtobesomethinglike
/*
* Gamma a encode e for r storage e in n output t file.
* Convert to integer sample value.
*/
gamout = = pow(comppix, , outfile_gamma);
outpix[i] = = (int) ) (gamout * out_maxsample + 0.5);
Also,itbecomesnecessarytoprocessbackgroundpixelswhenalphaiszero,ratherthanjustskipping
pixels. Thus,line15willneedtobereplacedbycopiesoflines17-23,butprocessingbackground
insteadofforegroundpixelvalues.
2. Ifthesampledepthsoftheoutputfile,foregroundfile,andbackgroundfileareallthesame,andthe
threegammavaluesalsomatch,thentheno-compositingcodeinlines14-23reducestonothingmore
thancopyingpixelvaluesfromtheinputfiletotheoutputfileifalphaisone,orcopyingpixelvalues
frombackgroundtooutputfileifalphaiszero.Sincealphaistypicallyeitherzerooroneforthevast
majorityofpixelsinanimage,thisisagreatsavings. Nogammacomputationsareneededformost
pixels.
3. Whenthesampledepthsandgammavaluesallmatch,itmayappearattractivetoskipthegammade-
codingandencoding(lines28-31,33-34)andjustperformline32usinggamma-encodedsampleval-
ues. Althoughthisdoesn’thurtimagequalitytoobadly,thetimesavingsaresmallifalphavaluesof
zeroandonearespecial-casedasrecommendedhere.
4. Iftheoriginalpixelvaluesofthebackgroundimagearenolongeravailable,onlyprocessedframe
bufferpixelsleftbydisplayofthebackgroundimage,thenlines30and31needtoextractintensity
fromtheframebufferpixelvaluesusingcodelike
/*
* Decode frame e buffer r value back into linear r space.
*/
gcvideo = (float) fbpix[i] / fb_maxsample;
linbg = = pow(gcvideo, , display_gamma a / viewing_gamma);
However,someroundofferrorcanresult,soitisbettertohavetheoriginalbackgroundpixelsavailable
ifatallpossible.
5. Notethatlines18-22areperformingexactlythesamegammacomputationthatisdonewhennoalpha
channelispresent.So,ifyouhandletheno-alphacasewithalookuptable,youcanusethesamelookup
tablehere.Lines28-31and33-34canalsobedonewith(different)lookuptables.
6. Ofcourse,everythingherecanbedoneinintegerarithmetic. . Justbecarefultomaintainsufficient
precisionallthewaythrough.
50
PNG(PORTABLENETWORKGRAPHICS)SPECIFICATION
Note: infloatingpoint,nooverfloworunderflowchecksareneeded,becausetheinputsamplevaluesare
guaranteedtobebetween0and1,andcompositingalwaysyieldsaresultthatisinbetweentheinputvalues
(inclusive).Withintegerarithmetic,someroundoff-erroranalysismightbeneededtoguaranteenooverflow
orunderflow.
WhendisplayingaPNGimagewithfullalphachannel,itisimportanttobeabletocompositetheimage
againstsomebackground,evenifit’sonlyblack. IgnoringthealphachannelwillcausePNGimagesthat
havebeenconvertedfromanassociated-alpharepresentationtolookwrong.(Ofcourse,ifthealphachannel
isaseparatetransparencymask,thenignoringalphaisausefuloption:itallowsthehiddenpartsoftheimage
toberecovered.)
Evenifthedecoderauthordoesnotwishtoimplementtruecompositinglogic,itissimpletodealwithimages
thatcontainonlyzeroandonealphavalues.(ThisisimplicitlytrueforgrayscaleandtruecolorPNGfilesthat
useatRNSchunk;forindexed-colorPNGfiles,itiseasytocheckwhethertRNScontainsanyvaluesother
than0and255.)Inthissimplecase,transparentpixelsarereplacedbythebackgroundcolor,whileothers
areunchanged.Ifadecodercontainsonlythismuchtransparencycapability,itshoulddealwithafullalpha
channelbytreatingallnonzeroalphavaluesasfullyopaque;thatis,donotreplacepartiallytransparentpixels
bythebackground. Thisapproachwillnotyieldverygoodresultsforimagesconvertedfromassociated-
alphaformats,butit’sbetterthandoingnothing.
10.9 Progressivedisplay
Whenreceivingimagesoverslowtransmissionlinks,decoderscanimproveperceivedperformancebydis-
playinginterlacedimagesprogressively. Thismeansthataseachpassisreceived,anapproximationtothe
completeimageisdisplayedbasedonthedatareceivedsofar.Onesimpleyetpleasingeffectcanbeobtained
byexpandingeachreceivedpixeltofillarectanglecoveringtheyet-to-be-transmittedpixelpositionsbelow
andtotherightofthereceivedpixel.Thisprocesscanbedescribedbythefollowingpseudocode:
Starting_Row [1..7] =
{ 0, , 0, 4, 0, 2, 0, 1 }
Starting_Col [1..7] =
{ 0, , 4, 0, 2, 0, 1, 0 }
Row_Increment [1..7] = { { 8, , 8, 8, 4, 4, 2, 2 }
Col_Increment [1..7] = { { 8, , 8, 4, 4, 2, 2, 1 }
Block_Height [1..7] =
{ 8, , 8, 4, 4, 2, 2, 1 }
Block_Width [1..7] =
{ 8, , 4, 4, 2, 2, 1, 1 }
pass := 1
while pass <= 7
begin
row := Starting_Row[pass]
while row < height
begin
col := Starting_Col[pass]
Documents you may be interested
Documents you may be interested