0

I'm trying to write a program that converts images to grayscale and then saves copies of the images with a new name ("gray-" + fname), but I'm getting error message java.lang.NullPointerExeption when I run the program.

The

gray.save();

line at the bottom of the below code gets highlighted. I'm not sure why the program says the variable gray is null. Should I change the order of the lines? Thanks for your help.

import edu.duke.*;
import java.io.File;
    public class ImageConverterAndSaver {
        public ImageResource makeGray(ImageResource inImage) {
        ImageResource outImage = new ImageResource(inImage.getWidth(), inImage.getHeight());
        for (Pixel px:outImage.pixels()){
            Pixel inPixel = inImage.getPixel(px.getX(), px.getY());
            int grayConversion = (inPixel.getRed() + inPixel.getGreen() + inPixel.getBlue()/3);
            px.setRed(grayConversion);
            px.setGreen(grayConversion);
            px.setBlue(grayConversion);
        }
        return outImage;
    }
        public void doSave(){
        DirectoryResource dr = new DirectoryResource();
        for (File f: dr.selectedFiles()) {
            ImageResource image = new ImageResource(f);

            String fname = image.getFileName();
            String newName = "gray-" + fname;
            image.setFileName(newName);
            ImageResource gray = makeGray(image);
            gray.draw();
            gray.save();
        }
    }
    }
Ekaterina1234
  • 400
  • 1
  • 7
  • 20

0 Answers0