Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageIO.read returns NULL, with no errors

Tags:

java

image

The following code seems not to work, even though the file appears to be found just fine.

    images = new BufferedImage[32];
    FileInputStream fis = null;
    for (int i = 0; i < 32; i++) {
        File file = new File("tiles\\"+i+".bmp");
        if (!file.exists()){
            System.out.println("File  "+i+" failed");
        }
        try { 
            fis = new FileInputStream(file); 
        } catch (FileNotFoundException e) { 
            System.err.println(e + "" + i); 
        }
        try { 
            images[i] = ImageIO.read(fis); 
        } catch (IOException e) { 
            System.err.println(e + "" + i); 
        }
        if (images[i] == null) {
            System.out.println("Image "+i+" failed");
        }
    }

Thanks in advance for any help.

Edit: The result is me attempting to Graphics.drawImage(images[0]);, and it giving me a null pointer exception. This code here completes fine.

Edit: Changed moved the if(!file.exists()) as suggested, and wrapped the file in an input stream.

like image 325
Naberius Avatar asked Mar 30 '12 13:03

Naberius


People also ask

Why ImageIO read return null?

read(file); will return null if no registered ImageReader is found. Please check whether you have registered any ImageReader.

What does ImageIO read do?

Image I/O recognises the contents of the file as a JPEG format image, and decodes it into a BufferedImage which can be directly used by Java 2D.

What kind of exception does the ImageIO class cause?

imageio. ImageIO. write and that failure is causing a null pointer exception.

What is ImageIO in Java?

ImageIO is a utility class which provides lots of utility method related to images processing in Java. Most common of them is reading form image file and writing images to file in java. You can write any of . jpg, . png, .


2 Answers

ImageIO.read(*...) will only load these image types GIF, PNG, JPEG, BMP, and WBMP.

Any other image type will return null without error.

reference: http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

I do realize this is not a solution to the specific original problem but it is a solution to the question asked.

like image 85
Irrationalkilla Avatar answered Oct 19 '22 16:10

Irrationalkilla


ImageIO.read(file); will return null if no registered ImageReader is found. Please check whether you have registered any ImageReader.

I think this code snippet could help you

File file = new File("bear.jpg"); // I have bear.jpg in my working directory  
    FileInputStream fis = new FileInputStream(file);  
    BufferedImage image = ImageIO.read(fis); //reading the image file  

You just need to wrap the file into an FileInputStream and then pass it to read()

like image 25
Chandra Sekhar Avatar answered Oct 19 '22 18:10

Chandra Sekhar