I'm able to import a JPG
file, but every time I run my program to output the image it gives this exception :
Exception in thread "main" java.lang.NullPointerException
at InvertImage.main(InvertImage.java:24)
Don't know why, here my code:
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class InvertImage{
public static void main(String args[])throws IOException{
BufferedImage img = null;
File imgFile = null;
try {
imgFile = new File("Cake.jpg");
img = ImageIO.read(imgFile);
} catch(IOException e){
System.out.println(e);
}
int width = img.getWidth();
int height = img.getHeight();
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
int pixel = img.getRGB(x, y);
int a = (pixel >> 24) & 0xff;
int r = (pixel >> 16) & 0xff;
int g = (pixel >> 8) & 0xff;
int b = pixel & 0xff;
r = 255 - r;
g = 255 - g;
b = 255 - b;
//set new RGB values
pixel = (a << 24) | ( r << 16) | ( g << 8) | b;
img.setRGB(x, y, pixel);
}
}
try{
imgFile = new File("Cake_invert.jpg")
ImageIO.write(img, "jpg", imgFile);
}catch(IOException e){
System.out.println(e);
}
}
}
Don't know what I'm missing here, just need to output a jpg file once my program finish running.
You're getting NullPointerException. That means you're trying to do something with an object that is empty
. It even tells you the error occurs in class InvertImage
and line 24
- (InvertImage.java:24)
.
Probably your image Cake.jpg
was not found and that happens often when you launch your application from Eclipse and place a file in a wrong folder. That's why it's a good practice to give full path to a file you want to open when you're not sure where to put it. If you want to keep relative path put your image into the main folder of your project, on the same level as src
and bin
folders.
Your code works for me. The only thing I changed was giving full path to Cake.jpg
, for example C:\\Cake.jpg
. The same applies to Cake_invert.jpg
, otherwise it will be saved in your project's main folder.