Tải bản đầy đủ - 0 (trang)
Chapter 5.  An Introduction to Java Imaging

Chapter 5.  An Introduction to Java Imaging

Tải bản đầy đủ - 0trang

ImageFormats

AgamewilltypicallyuseamixoftheGIF,JPEG,andPNG

images,populargraphicsformatsthathaveadvantagesand

disadvantages.

AGraphicsInterchangeFormat(GIF)imageisbestforcartoonstylegraphicsusingfewcolors,sinceonlyamaximumof256

colorscanberepresentedinafile.ThisisduetoGIF'suseofa

256-elementcolortabletostoreinformation.



Oneofthesecolortableentriescanrepresenta"transparent"color,

whichJavahonorsbynotdrawing.



GIFoffersrudimentaryanimationbypermittingafiletocontain

severalimages.Thesearedrawnconsecutivelywhenthefileis

displayed(e.g.,withdrawImage()inJava).Thisfeatureisn'tof

muchusesincethere'snosimplewayofcontrollingthe

animationfromwithinJava.

AJointPhotographicExpertsGroup(JPEG)fileemploys3bytes

(24bits)perpixel(1byteforeachofthered,green,andblue

[RGB]components),butalossycompressionschemereduces

thespacequiteconsiderably.Thismaycauselargeareasusing

asinglecolortoappearblotchy,andsharpchangesincontrast

canbecomeblurred(e.g.,attheedgesofblacktextonawhite

background).JPEGfilesarebestforlargephotographicimages,

suchasgamebackgrounds.JPEGfilesdonotoffer

transparency.

ThePortableNetworkGraphics(PNG)formatisintendedasa

replacementforGIF.Itincludesanalphachannelalongwiththe



usualRGBcomponents,whichpermitsanimagetoinclude

translucentareas.Translucencyisparticularlyusefulforgaming

effectslikelaserbeams,smoke,andghosts(ofcourse).Other

advantagesoverGIFaregammacorrection,whichenables

imagebrightnesstobecontrolledacrossplatforms,aswellas

2Dinterlacingand(slightly)betterlosslesscompression.This

lastfeaturemakesPNGagoodstoragechoicewhilea

photographicimageisbeingedited,butJPEGisprobablybetter

forthefinishedimagesinceitslossycompressionachieves

greatersizereductions.



SomedeveloperspreferPNGsinceit'sanopensourcestandard(see

http://www.libpng.org/pub/png/),withnopatentsinvolved;theGIF

formatisownedbyCompuServe.



TheAWTImagingModel

JDK1.0introducedtheAWTimagingmodelfordownloading

anddrawingimages.Backthen,itwasthoughtthatthemost

commonuseofimagingwouldinvolveappletspullinggraphics

fromtheWeb.Astandard'90sexample(withtheexceptionof

usingJApplet)isshowninExample5-1.



Example5-1.ShowImageapplet(Version1)

usingImage

importjavax.swing.*;

importjava.awt.*;

publicclassShowImageextendsJApplet

{

privateImageim;

publicvoidinit()

{im=getImage(getDocumentBase(),"ball.gif");}

publicvoidpaint(Graphicsg)

{g.drawImage(im,0,0,this);}

}



ThegetdocumentBase()methodreturnstheURLofthedirectory

holdingtheoriginalwebdocument,andthisisprependedtothe

image'sfilenametogetaURLsuitableforgetImage().

Thecentralproblemwithnetworkedimageretrievalisspeed.

Consequently,theJavadesignersconsidereditabadideato

haveanappletstopwhileanimagecrawledoverfromthe



serverside.Asaresult,wehaveconfusingbehaviorforgetImage(

)anddrawImage().Neitherofthesedowhattheirnameimplies.

ThegetImage()methodispoorlynamedsinceitdoesn'tget(or

download)theimageatall;insteaditpreparesanemptyImage

object(im)forholdingtheimage,returningimmediatelyafter

that.ThedownloadingistriggeredbydrawImage()inpaint(),

whichiscalledastheappletisloadedintothebrowserafter

init()hasfinished.

ThefourthargumentsuppliedtodrawImage()isanImageObserver

(usuallytheappletorJFrameinanapplication),whichwill

monitorthegradualdownloadingoftheimage.Asdataarrives,

theComponent'simageUpdate()isrepeatedlycalled.imageUpdate()'s

defaultbehavioristocallrepaint(),toredrawtheimagesince

moredataareavailable,andreturnTRue.However,ifanerror

hasoccurredwiththeimageretrievalthenimageUpdate()will

returnfalse.imageUpdate()canbeoverriddenandmodifiedby

theprogrammer.

Theoveralleffectisthatpaint()willbecalledrepeatedlyasthe

imageisdownloaded,causingtheimagetoappeargradually

on-screen.Thiseffectisonlynoticeableiftheimageiscoming

overthenetwork;ifthefileisstoredlocally,thenitwillbe

drawninfullalmostinstantaneously.

TheresultofthiscodingstylemeansthattheImage(im)contains

nodatauntilpaint()iscalledandeventhenmaynotcontain

completeinformationforseveralsecondsorminutes.This

makesprogrammingdifficult:forinstance,aGUIcannoteasily

allocateanon-screenspacetotheimagesinceithasnoknown

widthorheightuntilpaintinghasstarted.

SincetheintroductionofJDK1.0,experiencehasshownthat

mostprogramsdonotwantgraphicstobedrawnincrementally

duringexecution.Forexample,gamespritesshouldbefully

realizedfromthestart.

ThegetImage()methodisonlyforapplets;thereisaseparate



getImage()methodforapplications,accessiblefromToolkit.For



example:



Imageim=Toolkit.getDefaultToolkit().getImage("http://..



AswiththegetImage()methodforapplets,itdoesn'tdownload

anything.Thattaskisdonebypaint().



TheMediaTrackerClass

Mostprograms(andmostgames)wanttopreloadimages

beforedrawingthem.Inotherwords,wedonotwanttotie

downloadingtopainting.

Onesolutionisthejava.awt.MediaTrackerclass:aMediaTracker

objectcanstartthedownloadofanimageandsuspend

executionuntilithasfullyarrivedoranerroroccurs.Theinit()

methodintheShowImageclasscanbemodifiedtodothis:

publicvoidinit()

{

im=getImage(getDocumentBase(),"ball.gif");

MediaTrackertracker=newMediaTracker(this);

tracker.addImage(im,0);

try{

tracker.waitForID(0);

}

catch(InterruptedExceptione)

{System.out.println("DownloadError");}

}



waitForID()startstheseparatedownloadthread,andsuspends



untilitfinishes.TheIDusedintheMediaTrackerobjectcanbeany

positiveinteger.



Thisapproachmeansthattheappletwillbeslowertostartsinceinit(

)'sexecutionwillbesuspendedwhiletheimageisretrieved.



Inpaint(),drawImage()willonlydrawtheimagesincea

downloadisunnecessary.Consequently,drawImage()canbe

suppliedwithanull(empty)ImageObserver:

drawImage(im,0,0,null);



Acommonwayofacceleratingthedownloadingofmultiple

imagesistospawnapoolofthreads,eachoneassignedtothe

retrievalofasingleimage.Onlywheneverythreadhas

completedwillinit()return.



ImageIcon

WritingMediaTrackercodeineveryapplet/applicationcanbe

boring,soanImageIconclasswasintroduced,whichsetsupa

MediaTrackerbyitself.TheImageIconnameisabitmisleading:any

sizeofimagecanbedownloaded,notjustanicon.

UsingImageIcon,theinit()methodbecomes:



publicvoidinit()

{im=newImageIcon(getDocumentBase()+"ball.gif").getIma



TheImageIconobjectcanbeconvertedtoanImage(ashere)or

canbepaintedwithImageIcon'spaintIcon()method.



TheRiseofJARs

AJARfileisawayofpackagingcodeandresourcestogether

intoasingle,compressedfile.Resourcescanbealmost

anything,includingimagesandsounds.

Ifanapplet(orapplication)isgoingtoutilizealotofimages,

repeatednetworkconnectionstodownloadthemwillseverely

reduceexecutionspeed.It'sbettertocreateasingleJARfile

containingtheapplet(orapplication)andalltheimagesandto

havethebrowser(oruser)downloadit.Then,whenanimage

comestobeloaded,it'safast,localloadfromtheJARfile.

Fromauser'spointofview,thedownloadofthecodetakesa

littlelonger,butitexecuteswithoutanyannoyingdelayscaused

byimageloading.

AttheendofChapter6,I'llexplainhowtopackagethe

ImagesTestscode,andthelargenumberofimagesituses,asa

JARfile.Theonlycodingchangeoccursinspecifyingthe

locationofanimagefile.Goingbacktoasimplerexample,the

ImageIconexamplefromabovewouldneedtoberewrittenthis

way:



im=newImageIcon(getClass().getResource("ball.gif")).g



getClass()getstheClassreferencefortheobject(e.g.,

ShowImage),andgetresource()specifiestheresourceisstoredin



thesameplaceasthatclass.



AWTImageProcessing

ItcanbedifficulttoaccessthevariouselementsofanImage

object,suchaspixeldataorthecolormodel.Forinstance,the

imagemanipulationfeaturesinAWTareprimarilyaimedat

modifyingindividualpixelsastheypassthroughafilter.A

streamofpixeldataissentoutbyaImageProducer,passes

throughanImageFilter,andontoanImageConsumer(seeFigure51).Thisisknownasthepushmodelsincestreamdataare

"pushed"outbytheproducer.



Figure5-1.ImageprocessinginAWT



ThetwopredefinedImageFiltersubclassesareCropImageFilterfor

croppingregionsofpixelsandRGBImageFilterforprocessing

individualpixels.



Chainingfilterstogetherispossiblebymakingaconsumerofonefilter

theproducerforanother.



Thisstream-viewoffilteringmakesitdifficulttoprocessgroups

ofpixels,especiallyonesthatarenoncontiguous.Forexample,

aconvolutionoperationforimagesmoothingwouldrequirea

newsubclassofImageFilterandanewImageConsumertodealwith

thedisruptiontothepixelsstream.

AnalternativeapproachistousethePixelGrabberclasstocollect

allthepixeldatafromanimageintoanarray,whereitcanthen

beconvenientlyprocessedinitsentirety.TheMemoryImageSource

classisnecessarytooutputthechangedarray'sdataasa

streamtoaspecifiedImageConsumer.Theadditionalstepsinthe

pushmodelareshowninFigure5-2.



Figure5-2.Processingtheimageasanarray



ModernJavacode(sinceJ2SE1.2)canutilizetheimage

processingcapabilitiesofJava2D,withitsmanypredefined

operations,soyou'reunlikelytomeetthepushmodelexceptin

legacycode.IfJava2Disinsufficient,thenJAIshouldbe



considered.



AnOverviewofJava2D

Java2Doffersasetofgraphicsfeaturesthataddressthe

inadequaciesintheolderAWTgraphicsclasses.Weaknessesin

AWTincludeonlysupportingsinglepixelthicknesslines,limited

fonts,poorshapemanipulation(e.g.,norotation),andno

specialfills,gradients,orpatternsinsideshapes.

Java2DreplacesmostoftheshapeprimitivesinAWT(e.g.,

rectangles,arcs,lines,ellipses,polygons)withversionsthatcan

takedoubleorfloatingpointingcoordinates,thoughmany

peoplestillusetheolddrawLine(),drawRect(),andfillRect()

methods.Ofmoreinterestistheabilitytocreatearbitrary

geometricshapesbyusingsetoperationsonothershapeswith

union,intersection,subtraction,andexclusive-or.AGeneralPath

classpermitsashapetobebuiltfromaseriesofconnected

linesandcurves,andcurvescanbedefinedusingsplines.(A

spline'scurvinessisspecifiedusingaseriesofcontrolpoint.)

Java2Ddistinguishesbetweenshapestrokingandfilling.

Strokingisthedrawingoflinesandshapeoutlines,whichmay

employvariouspatternsandthicknesses.Shapefillingcanuse

asolidcolor(asinAWT),andpatterns,colorgradients,and

imagesactingastextures.

Affinetransformationscanbeappliedtoshapesandimages,

includingtranslation,rotation,scaling,andshearing,and

groupsoftransformationscanbecomposedtogether.drawImage(

)canbesuppliedwithsuchatransformation,whichisapplied

beforetheimageisrendered.Shapesandimagescanbedrawn

togetherusingeightdifferentcompositingrules,optionally

combinedwithvaryingtransparencyvalues.Clippingcanbe

applied,basedonanarbitraryshape(notjustarectangle,asin

AWT).

Renderinghintsincludetheanti-aliasingofshapesandtext



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 5.  An Introduction to Java Imaging

Tải bản đầy đủ ngay(0 tr)

×