0

I was trying to get RGB values for every pixel of an image. Like any other insanely inexperienced coder, I went to the internet. I found a snippet of code that I could understand. After copying, pasting, and tweaking the code, the code wouldn't work. Can someone please help. I have an error. Here is the code:

import java.io.File;
import java.io.FileWriter;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Art {
   public static void main(String args[])throws Exception {
      FileWriter writer = new FileWriter("pixel_values.txt");
      //Reading the image
      File file = new File("Mountain.jpg");
      BufferedImage img = ImageIO.read(file);
      for (int y = 0; y < img.getHeight(); y++) {
         for (int x = 0; x < img.getWidth(); x++) {
            //Retrieving contents of a pixel
            int pixel = img.getRGB(x,y);
            //Creating a Color object from pixel value
            Color color = new Color(pixel, true);
            //Retrieving the R G B values
            int red = color.getRed();
            int green = color.getGreen();
            int blue = color.getBlue();
            writer.append(red+":");
            writer.append(green+":");
            writer.append(blue+"");
            writer.append("\n");
            writer.flush();
         }
      }
      writer.close();
      System.out.println("RGB values at each pixel are stored in the specified file");
   }
}

After this, I get, "Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.awt.image.BufferedImage.getHeight()" because "img" is null at Art.main(Art.java:12)"
Why is the img null? Can someone please help me fix this?

Kyotiq
  • 1
  • 2
  • 1
    Maybe because [ImageIO.read returns NULL, with no errors](https://stackoverflow.com/questions/9943962/imageio-read-returns-null-with-no-errors) – MadProgrammer Aug 04 '22 at 00:07
  • Because it's named `.jpg` doesn't mean it's a valid jpg or a format of jpg that `ImageIO` can read, you might need to check the file with a image editor and possibly convert it – MadProgrammer Aug 04 '22 at 00:10

0 Answers0