![]() |
Image Class ObjectToolkit.getImage(String) and specify the file name. Java
will read the image file and convert it to Image class
object.
To ensure that the decode process has finished the job, instantiate
MediaTracker. Call
MediaTracker.waitForID(int) to check if there is any
error. In the sample code below, it throws an exception when it can
not load the specified image file.
Image image;
public void readImageFile(String fileName)
{
try
{
image= getToolkit().getImage(fileName);
MediaTracker tracker=new MediaTracker(this);
tracker.addImage(image,0);
tracker.waitForID(0);
if(tracker.isErrorAny())
{
throw new Exception();
}
}
catch(Exception e){e.printStackTrace();}
}
Image Class Object
Image Class Object to int arrayImage object, call
PixelGrabber.grabPixels(). First, prepare an integer
array of size width x height of the image. Call
Image.getWidth(ImageObserver) and
Image.getHeight(ImageObserver) which will return the
width and height of the Image object, respectively. Make
sure that ImageObserver is passed as an argument. Then
instantiate PixelGrabber(Image,
int,int,int,int,int[],int,int) class object. Call
PixelGrabber.grabPixels() within try-catch block.
PixelGrabber.getStatus() will tell you if anything goes
amiss.
int memory[];
int imageWidth=0;
int imageHeight=0;
void captureImage()
{
imageWidth=image.getWidth(this);
imageHeight=image.getHeight(this);
memory=new int[imageWidth*imageHeight];
PixelGrabber pg=
new PixelGrabber(image,
0,
0,
imageWidth,
imageHeight,
memory,
0,
imageWidth);
try
{
pg.grabPixels();
}
catch(Exception e){e.printStackTrace();}
if(((pg.getStatus())&ABORT)!=0)
{
System.err.println("Can not capture the image");
return;
}
}
Image Class Object to int array
int Array Class Object to Image ObjectImage object, call
Toolkit.createImage(ImageProducer).
ImageProducer ip=new MemoryImageSource(w,h,memory,0,w); image=getToolkit().createImage(ip);
int Array Class Object to Image Object