首页 > 解决方案 > (Java) 如何使用 setRGB() 和缓冲图像

问题描述

在我的 addMarking 方法中获取空指针异常。

我是缓冲图像的新手,所以我不完全确定问题出在哪里。我有一个单独的类,它将图像分解为 3x3 数组并用它调用 findEnds()。当 findEnds 在 3x3 数组中找到正确的条件时,它会调用 addMarking 并使用坐标在图片上制作一个红点。注意:以前我尝试使用 2dGraphic 在 bufferedImage 上写入图片,但为了解决此问题而将其取出并使用 setRGB 手动复制像素(尚未编写此方法)。注意:我不能只用原始文件制作缓冲图像的原因是该文件具有黑白颜色类型而不是 TYPE_INT_RGB。

错误:

Exception in thread "main" java.lang.NullPointerException
    at findFeatures.addMarking(findFeatures.java:43)
    at getImage.getColor(getImage.java:44)
    at fingerprintDriver.main(fingerprintDriver.java:15)

getImage 是一个将照片分解为 3x3 数组的类,它还将请求数组的坐标返回给 addMarking 类。

指纹驱动:

/**
 * Driver for the ElevationScanner Class
 * 
 * @author benjamincole
 * @version 4/23/18
 */
public class fingerprintDriver {
    public static void main(String[] args) {
        String fileName = JOptionPane.showInputDialog("Please enter a name for the file");
        getImage test = new getImage(fileName);
        findFeatures find = new findFeatures();
        find.imageConstructor();
        test.getColor();

    }
}

findFeatures 类:

 /**
     * This class tests a 3x3 array. The method findEnds tests this array for
     * two black pixels. If this condition is found it is an end and the x  
     * and y-coords are marked.
     * 
     * @author benjamincole
     *
 */
public class findFeatures {
    BufferedImage markedImage;
    int counter;
    public void imageConstructor() { // creates image to add markings to
            markedImage = new BufferedImage(getImage.width, getImage.height, BufferedImage.TYPE_INT_RGB);
    }

    public void findEnds(boolean[][] colorArray) { // finds the ends of arches
        counter = 0;
        System.out.println();
        for (int x = 0; x < 3; x++) {
            System.out.println();
            for (int y = 0; y < 3; y++) {
                System.out.print(" " + colorArray[x][y]);
                if (colorArray[x][y])
                    counter++;
            }
        }
            if (counter == 2 || counter == 1) { // if only 2 or less pixels are
                                                // black in the 3x3
                System.out.println(getImage.xCord + " " + getImage.yCord);
                System.out.println(" end found"); // end has been found
                addMarking(getImage.getXCord(), getImage.getYCord(), Color.red.getRGB());
            }   
        }

    public void addMarking(int x, int y, int rgb) { // adds red `marking to image`
        markedImage.setRGB(x, y, rgb); //ERROR HERE! (Null Pointer)
        markedImage.setRGB(x + 1, y + 1, rgb);
        markedImage.setRGB(x + 2, y + 2, rgb);
        markedImage.setRGB(x, y + 2, rgb);
        markedImage.setRGB(x + 2, y, rgb);
    }

标签: javabufferedimage

解决方案


推荐阅读