Problem in reading image file
i am getting following errors when trying to read an image files pixel:
HTML Code:
F:\tm\final>java pixelcheck
1
2
no. of row is:-1
no. of col is:-1
Exception in thread "main" java.lang.NegativeArraySizeException
at get3dimagepixelobj.get3ddata(get3dimagepixelobj.java:33)
at pixelcheck.main(pixelcheck.java:15)
my image file is in f:\tm\final .
class file and image file is in same folder.
Code :
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
class pixelcheck
{
public static void main(String args[])
{
get3dimagepixelobj j1=new get3dimagepixelobj();
int[][][] datareturned = new int[400][][];//size of image file is //400X299
String fname="f2.jpeg";
datareturned=j1.get3ddata(fname);
for (int i=0;i<4 ;i++ )
{
System.out.println(datareturned[0][0][i]);
}
}
}
The other class get3dimagepixel obj is (few lines as it is very large):
Code :
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
class pixeldetails
{
int alpha;
int red;
int green;
int blue;
int area;
}
class get3dimagepixelobj extends pixeldetails
{
public int[][][] get3ddata(String imagefile)
{
//String imagefile;
//Image rawimage=getImage(imagefile);
System.out.println("1");//to check the error
Image rawimage=Toolkit.getDefaultToolkit().getImage(imagefile);
System.out.println("2");//to check the error
int imagerows=rawimage.getHeight(null);
System.out.println("no. of row is:"+imagerows);//to check //the error
int imagecols=rawimage.getWidth(null);
System.out.println("no. of col is:"+imagecols);
// int imagecols=rawimage.getWidth(java.awt.image.ImageObserver);
int[] onedpix=new int[imagerows*imagecols];
int[][][] threedpix=new int[imagerows][imagecols][4];
System.out.println("3.1");
Re: Problem in reading image file
The API for Image states that getWidth/getHeight can return -1 if the height is not yet known. Use ImageIO to read the file, as using the Toolkit seems to result in this behavior (at least on my system):
Code java:
Image image = Toolkit.getDefaultToolkit().getImage("myImage.jpg");
System.out.println(image.getWidth(null));//prints -1
try{
image = ImageIO.read(new File("myImage.jpg"));
System.out.println(image.getWidth(null));//prints correctly
}catch(Exception e){
e.printStackTrace();
}