我正在研究灰度图像压缩程序,到目前为止我已经能够(几乎)将图像转换为2D数组。下面的代码就是我现在所拥有的。对我来说似乎很好,但是当我运行它时,它在代码的第15行给出了一个空指针异常错误,它是主要的,并且错误写在下面。
任何帮助都会非常感激!! =)
代码和主要是:
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);
}
错误是:
Exception in thread "main" java.lang.NullPointerException
at gsTo2d.compress(gsTo2d.java:15)a
at convTest.main(convTest.java:9)
答案 0 :(得分:0)
如果没有已注册的ImageReader可以读取以下行中的图像,则图像将为null:
BufferedImage image = ImageIO.read(file);
这会在下一行触发NullPointerException。
也许您的图片在某种程度上无效?尝试打破线并检查图像是否为空。