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.