2013-03-19 70 views
0

我一直在使用bookClasses類來操作圖像,並且在嘗試刪除圖像中的紅眼時出現NullPointerException錯誤。下面是代碼:NullPointerException(幫助!)

首先removeRedEye方法,它是Picture.Java類中:

public void removeRedEye(int startX, int startY, int endX, int endY, Color newColor){ 

    Pixel pixel = null; 

    for (int x = startX; x < endX; x++){ 
     for (int y = startY; y < endY; y++){ 
      if (pixel.colorDistance(Color.RED) < 167){ 
         pixel.setColor(newColor); 
      } 
     } 
    } 
    } 
} 

和測試類:

public class TestRemoveRedEye{ 

    public static void main(String[] args){ 

     String fileName = FileChooser.getMediaPath("//jenny-red.jpg"); 

     Picture jennyPicture = new Picture(fileName); 

     jennyPicture.removeRedEye(109,91,202,107,java.awt.Color.BLACK); 

     jennyPicture.explore(); 

    } 
} 

如果任何人都可以說明爲什麼我的程序ISN」工作它將不勝感激。從removeRedEye方法

jennyPicture.removeRedEye(109,91,202,107,java.awt.Color.BLACK);從測試類

回答

1

分配null以pixel if (pixel.colorDistance(Color.RED) < 167){,你只是後調用一個方法就可以了:

這些生產線在錯誤挑出來。因此NPE。

Pixel pixel = null; 
for (int x = startX; x < endX; x++){ 
    for (int y = startY; y < endY; y++){ 
     if (pixel.colorDistance(Color.RED) < 167){ // <==== pixel is null ! 
        pixel.setColor(newColor); 
     } 
    } 
} 
2

像素你需要調用它的參考方法之前進行初始化。

Pixel pixel = null;// neew to initialize this. 
pixel = new Pixel(); // somethin like this 
for (int x = startX; x < endX; x++){ 
    for (int y = startY; y < endY; y++){ 
     if (pixel.colorDistance(Color.RED) < 167){