-4
我正在研究灰度圖像壓縮程序,至今我已經能夠(幾乎)將圖像轉換爲二維數組。下面的代碼是我現在所擁有的。對我來說似乎很好,但是當我運行它時,它在代碼的第15行給了我一個空指針異常錯誤,它是主要的,並且錯誤寫在下面。Java空指針異常圖像光柵
任何幫助將真的非常感謝! =)
的代碼和主要是:
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)
'image'是'null',你在調用'ImageIO.read()'後沒有檢查是否是這種情況。你有什麼問題? –
@BrianRoach:嗨,謝謝你的迴應。不,我猜想圖像不是空的。在同一行中聲明的文件「2.TIF」存在於指定的目錄中。問題是,儘管我已經指定了文件並將其傳遞給了Raster。它仍然在該行提供空指針異常。 ps:對不起,如果我聽起來不夠清楚 - 我仍然是一個編程noob。 – user1892655
Tif不支持開箱即用,您需要包含來自[Java Advanced Image API](http://java.net/projects/jai-imageio)的庫, – MadProgrammer