free web hosting | free website | Web Hosting | Free Website Submission | shopping cart | Promoter Online | php hosting
affordable web hosting Pets web page hosting web hosting website hosting web hosting service web hosting web host
Reading Pixel Values in Java

Reading Pixel Values in Java

Image File to Image Class Object

Reading an image file in Java is easy. Call Toolkit.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();}
    }

Code 1. Image File to Image Class Object

Image Class Object to int array

To obtain pixel values from the Image 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;
	    }
    }

Code 2. Image Class Object to int array

Image File to int Array Class Object to Image Object

To convert the integer array to an Image object, call Toolkit.createImage(ImageProducer).


  ImageProducer ip=new MemoryImageSource(w,h,memory,0,w);
  image=getToolkit().createImage(ip);

Code 3. Image File to int Array Class Object to Image Object

Sample Code

Click here for a sample Java source code which writes first 10 x 10 blue pixel values to standard output.


Return to Home
Erica Asai
Last Modified: Fri Sep 03 11:58:21 2004