Tải bản đầy đủ - 0 (trang)
Chapter 3. Graphics Programming with the Java 2D API

Chapter 3. Graphics Programming with the Java 2D API

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

(AWT)toprovideclassesforprofessional2Dgraphics,text,and

imaging.ThesubjectofthischapteristheuseofJava2Dfor

graphicsandtext.Java2DimagingisthesubjectofChapter4,

"TheImmediateModeImagingModel."

Keepinmindthat,forthemostpart,alldiscussionreferringto

shapeswillapplyequallytotextbecauseforallintentsand

purposes,textisrepresentedasshapes.Operationssuchas

texturemapping,stroking,andalphacompostingcanbe

appliedequallytoshapesandtext.

ThekeytousingJava2Dforgraphicsistounderstandasimple

basicprogrammingparadigmthatwewillrefertoastheBasic

Java2DRecipe.



JAIIO

OneofthemostusefulaspectsofJAIistheabilitytoeasilyread

andwriteimagedata.Imagescanbeloadedintoa

PlanarImageiftheyarecontainedinaformattedimagefile,a

nonformattedimagefile,oraBufferedImage.Likewise,the

datacontainedinaPlanarImagecanbewrittenintoafileas

eitherformattedorunformatteddataorthePlanarImagecan

beconvertedintoaBufferedImage.



FileOperator

Thereareanassortmentofoperatorsforreadingaspecific

imageformatsuchasBMP,GIF,FPX,JPEG,PNG,PNM,and

TIFF(seeTable6.11).

Note

TheIOforJAIisbuiltontheImageIOpackage

discussedinChapter5,sothereshouldn'tbea

discrepancybetweenthefileformatstheImageIO

packagecandecode/encodeandthefileformatsthe

JAIpackagecandecode/encode.



InTable6.11,thelistofIOoperatorsispresented.Notethat

manyofthemallowoptionalencoderordecoderobjectsin

ordertoprovidemorecontroloverreadingandwritingimages

ofspecificformats.

Table6.11.SummaryofFileOperators

Operator



ParameterBlockFormat/Description



AWTImage



add(java.awt.Imageimage);

TheAWTImageoperatorconvertsajava.awt.Imageintoa

PlanarImage.



BMP



add(com.sun.media.jai.codec.SeekableStream

stream);

TheBMPoperatordecodesthebmpimagecontainedinstream.



Encode



addSource(PlanarImagepi);

add(java.io.OutputStreamstream);

add(Stringformat);

add(com.sun.media.jai.codec.ImageEncodeParam

param);

TheEncodeoperatorencodespiontostreamusinggivenformatand

encodingparameters.Thedefaultvalueforformatis"tiff",andthe

defaultvalueforparamisnull.



FileLoad



add(Stringfilename);

add(com.sun.media.jai.codec.ImageDecodeParam

param);

add(booleancheckFileLocally);

TheFileLoadoperatordecodestheimagecontainedinfilefilename

usingthegivendecodingparameters.Theimageformatisn'tspecified.

Whenloadingremotefiles,checkFileLocallyshouldbesetto

false;otherwise,anIllegalArgumentExceptionwillbethrown

whenthefileisn'tfoundonthelocalfilesystem.Thedefaultvaluefor

paramisnull,andthedefaultvalueforcheckFileLocallyis

true.



FileStore



addSource(PlanarImagepi);

add(Stringfilename);

add(Stringformat);

add(com.sun.media.jai.codec.ImageEncodeParam

param);

TheFileStoreoperatorencodespiintofilefilenameusinggiven

formatandencodingparameters.Thedefaultvalueforformatis

"tiff"andthedefaultvalueforparamisnull.



FPX



add(com.sun.media.jai.codec.SeekableStream

stream);

add(com.sun.media.jai.codec.FPXDecodeParamparam);

TheFPXoperatordecodesthefpximagecontainedinstream.The

defaultvalueofparamisnull.



GIF



add(com.sun.media.jai.codec.SeekableStream

stream);

TheGIFoperatordecodesthegifimagecontainedinstream.



IIP



add(Stringurl);

add(int[]subImages);

add(floatfilter);

add(floatcontrast);

add(Rectangle2D.FloatsourceROI);

add(AffineTransformtransform);

add(floataspectRatio);

add(Rectangle2DFloatdestROI);

add(introtation);

add(StringmirrorAxis);

add(ICC_Profileiccprofile);

add(intjpegquality);

add(intjpegtable);

TheIIPoperatorcreatesajava.awt.image.RenderedImageora

java.awt.image.renderable.RenderableImagebasedonthe

datareceivedfromtheInternetImagingProtocol(IIP)server.Itcan

optionallyapplyasequenceofoperationstothecreatedimage.Refer

totheIIPspecificationsfoundathttp://www.digitalimaging.orgfor

morecompleteinformationonthisoperator.



IIPResolution add(Stringurl);

add(intresolution);

add(intsubImage);

TheIIPResolutionoperatorrequestsfromtheIIPserveranimage

locatedaturlwitharesolutionlevelofresolution.Itthencreates

ajava.awt.image.RenderedImagebasedonthedatareceived

fromtheserver.Thedefaultvalueforresolutionis

IIPResolutionDescriptor.MAX_RESOLUTION,andthedefault

valueforsubImageis0.



JPEG



add(com.sun.media.jai.codec.SeekableStream



stream);

TheJPEGoperatordecodesthejpegimagecontainedinstream.



PNG



add(com.sun.media.jai.codec.SeekableStream

stream);

add(com.sun.media.jai.codec.PNGDecodeParamparam);

ThePNGoperatordecodespngimagescontainedinstream.The

defaultvalueofparamisnull.



PNM



add(com.sun.media.jai.codec.SeekableStream

stream);

add(com.sun.media.jai.codec.PNGDecodeParamparam);

ThePNMoperatordecodesthepnmimagecontainedinstream.The

defaultvalueofparamisnull.



Stream



add(com.sun.media.jai.codec.SeekableStream

stream);

add(com.sun.media.jai.codec.ImageDecodeParam

param);

TheStreamoperatordecodestheimagecontainedinstream.The

imageformatisn'tspecified.Thedefaultvalueofparamisnull.



TIFF



add(com.sun.media.jai.codec.SeekableStream

stream);

add(com.sun.media.jai.codec.TIFFDecodeParam

param);

add(intpage);

TheTIFFoperatordecodespagepageofthetiffimagecontainedin

stream.Thedefaultvalueofparamisnull,andthedefaultvalueof

pageis0.



URL



add(java.net.URLurl);

add(com.sun.media.jai.codec.ImageDecodeParam

param);

TheURLoperatordecodestheimagecontainedinurl.Theimage

formatisn'tspecified.Thedefaultvalueofparamisnull.



Therearealsothreemainoperatorsforreadingimageswithout

specifyinganimageformat.TheyaretheFileLoad,Stream,

andURLoperators.Theseoperatorsexaminetheimagebytes

todecodetheimageformatandthencalltheappropriate

operatorthatis,TIFF,GIF,andsoon.Listing6.13showsall

threeoperatorsbeingusedtoreadthesameimagedata.

WritingformattedimagedataisdonebyusingtheFileStore

andEncodeoperators,whichwriteoutimagedataofa

specifiedformattoafileortoastream,respectively.

Listing6.13ImageLoadTester



packagech6;

importjava.awt.*;

importjava.awt.image.*;

importjavax.swing.*;

importjava.io.*;

importjava.net.*;

importjava.awt.image.renderable.ParameterBlock;

importjavax.media.jai.RenderedOp;

importjavax.media.jai.JAI;

importcom.sun.media.jai.codec.SeekableStream;



/**

ImageLoadTester--loadsanimageusingtheJAIclas

Thismethoduses3differentoperatornamestoload

in3differentmanners,namely"stream","fileload"



Itthenprintsoutthepropertiesoftheloadedimag

*/

publicclassImageLoadTesterextendsJFrame{



publicImageLoadTester(Stringfilename){

SeekableStreamstream=null;

URLurl=null;



try{

url=newURL("file:"+filename);

stream=SeekableStream.wrapInputStream(url

fal

}

catch(IOExceptionioe){

System.err.println("IOException:"+ioe.ge

}



params=newParameterBlock();

params.add(stream);

RenderedOpstreamImage=JAI.create("stream",p



params=newParameterBlock();

params.add(filename);

RenderedOpfileImage=JAI.create("fileload",p



params=newParameterBlock();

params.add(url);

RenderedOpurlImage=JAI.create("url",params)



//DisplayImageProperties

String[]props=streamImage.getPropertyNames()

for(inti=0;i
System.out.print("Property:"+props[i]+

System.out.println(streamImage.getProperty(

}



getContentPane().setLayout(newGridLayout(1,3)



getContentPane().add(newch6Display(streamImage

getContentPane().add(newch6Display(fileImage))

getContentPane().add(newch6Display(urlImage));

pack();

show();

}



publicstaticvoidmain(String[]args){

if(args.length!=1)

System.err.println("USAGE:ImageLoadTester

else

newImageLoadTester(args[0]);

}

privateParameterBlockparams;

}

ReadingUnformattedImages

IfthereisnodefinedformatforanimageortheJAIdecoders

cannotdecodetheimage'sformat,you'llneedtoconvertthe

rawpixeldataintoaPlanarImageyourself.Listing6.14

illustrateshowtoreadinaseriesoftilesconcatenatedintoa

singleimage.Acommonsituationinmedicalimagingoccurs

whenaseriesofslicesareconcatenatedintoasingleimagefile.

Inthislisting,thetilesareassumedtobecomposedofasingle

bandcontainingfloatdata.

Listing6.14FloatViewer



packagech6;

importjavax.media.jai.*;



importjava.awt.*;

importjava.awt.color.*;

importjava.awt.image.*;

importjava.awt.image.renderable.*;

importjavax.swing.*;

importjava.io.*;



/**

FloatViewer.java-readsaimagefilecomposesoffl

scalesitfordisplaypurposesanddisplaysit.



Thisimagefilecanbecomposedofanynumberofdif

aslongastheyarethesamedimensions(referredto

andtileHeight);

*/

publicclassFloatViewerextendsJFrame{

publicFloatViewer(Stringfilename,StringtileWidt

StringtileHeight){

Filef=newFile(filename);

if(!(f.exists())){

System.err.println("File:"+filename+"

System.exit(1);

}

this.tileWidth=Integer.parseInt(tileWidth);

this.tileHeight=Integer.parseInt(tileHeight);



float[][]dataArray=getData(f);

PlanarImageinputImage=getTiledImage(dataArra

doublescaleFactor=findScale(inputImage);

ParameterBlockpb=newParameterBlock();

pb.addSource(inputImage);

pb.add(newdouble[]{1.0/scaleFactor});



pb.add(newdouble[]{0.0});



RenderedOpscaledImage=JAI.create("rescale",

getContentPane().setLayout(newBorderLayout());

getContentPane().add(newJScrollPane(newch6Dis

BorderLayout.CENTER);

show();

pack();

}



/**

providesascalefactorfordisplayingtheimage

*/

privatedoublefindScale(PlanarImagepi){

ParameterBlockpb=newParameterBlock();

pb.addSource(pi);

PlanarImagepi2=JAI.create("extrema",pb);

double[]maximum=(double[])pi2.getProperty("m

doublemaxValue=maximum[0];

returnmaxValue/2.0;

}



/**

readstheimagedatafromthefileandstoresit

arrayofjavax.media.jai.DataBufferFloatelement

witheachtilebeingstoredina

separatejavax.media.jai.DataBufferFloatelement

*/

privatefloat[][]getData(Filefile){

numberFloats=(int)(file.length()/4);//4byte

numberFloatsPerTile=tileWidth*tileHeight;

numberTiles=numberFloats/numberFloatsPerTile;



float[][]floatArray=null;

floatArray=newfloat[numberTiles][numberFloat



try{

FileInputStreamfis=newFileInputStream(f

BufferedInputStreambis;

bis=newBufferedInputStream(fis,numberFl

DataInputStreamdis=newDataInputStream(b

for(inti=0;i
for(intj=0;j
floatArray[i][j]=dis.readFloat();

}

dis.close();

}

catch(IOExceptionioe){

System.err.println("IOException:"+ioe.g

System.exit(1);

}

returnfloatArray;

}



/**

createsaTiledImagefromanarrayof

javax.media.jai.DataBufferFloats

*/

privatePlanarImagegetTiledImage(float[][]dataArr

intnumberHorizontalTiles;

intnumberVerticalTiles;



//calculatenumberoftilespercolumnandper

doubletmp=Math.sqrt((double)numberTiles);

numberVerticalTiles=(int)tmp;



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

Chapter 3. Graphics Programming with the Java 2D API

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

×