0

我一直在使用 bookClasses 类集来操作图像,并且在尝试消除图像中的红眼时出现 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();

    }
}

如果有人能提出为什么我的程序不工作,将不胜感激。

这些行在错误中被挑出来: if (pixel.colorDistance(Color.RED) < 167){来自 removeRedEye 方法

jennyPicture.removeRedEye(109,91,202,107,java.awt.Color.BLACK); 从测试班

4

2 回答 2

2

pixel is null you need to initialize it before you invoke methods on its reference.

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){
于 2013-03-19T20:36:06.337 回答
1

You assign null to pixel and you call a method on it just after. Hence the 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);
        }
    }
}
于 2013-03-19T20:36:05.657 回答