I'm working on a grayscale image compression program and I've so far been able to(almost) convert an image into a 2D array. The code below is what I have right now. It seems fine to me but when I run it it gives me a null pointer exception error at line 15 of the code, it's main, and error are written below.
Any help would be really really appreciated!! =)
The code and main is:
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.*;
import javax.imageio.ImageIO;
public class gsTo2d {
private static String dir="C:/Documents and Settings/Administrator/workspace/GrayScaleBitmapCompressor/inputImage"; // add here the directory to the folder contains the image
public int [][] compress() throws IOException
{
File file = new File(dir , "2.TIF");// file object to get the file, the second argument is the name of the image file
BufferedImage image = ImageIO.read(file);
Raster image_raster = image.getData();
int[][] original; // where we'll put the image
//get pixel by pixel
int[] pixel = new int[1];
int[] buffer = new int[1];
// declaring the size of arrays
original = new int[image_raster.getWidth()][image_raster.getHeight()];
//get the image in the array
for(int i = 0 ; i < image_raster.getWidth() ; i++)
for(int j = 0 ; j < image_raster.getHeight() ; j++)
{
pixel = image_raster.getPixel(i, j, buffer);
original[i][j] = pixel[0];
}
return original;
}
}
public static void main(String[] args) throws IOException{
gsTo2d obj = new gsTo2d();
int[][] imageArray = obj.compress();
System.out.println(imageArray);
}
The error is:
Exception in thread "main" java.lang.NullPointerException
at gsTo2d.compress(gsTo2d.java:15)a
at convTest.main(convTest.java:9)
Image will be null if no registered ImageReader can read the image on the following line:
BufferedImage image = ImageIO.read(file);
That would trigger a NullPointerException on the next line.
Maybe your image is invalid in some way? Try to break on the line and check whether image is null.