-4

我正在研究灰度图像压缩程序,到目前为止我已经能够(几乎)将图像转换为二维数组。下面的代码是我现在所拥有的。对我来说似乎很好,但是当我运行它时,它在代码的第 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)
4

1 回答 1

0

如果没有注册的 ImageReader 可以读取以下行中的图像,则 Image 将为 null:

BufferedImage image = ImageIO.read(file);

这将在下一行触发 NullPointerException。

也许您的图像在某些方面无效?尝试断线并检查图像是否为空。

于 2013-01-21T20:37:01.813 回答