ImageIO.read can’t read input file BufferedImage always null no error

I assume your image path is /resources/image.png. Below code show you how to read image from spring class path

if you got error

javax.imageio.IIOException: Can’t read input file!

or

java.lang.IllegalArgumentException: URI is not hierarchical

You should be using

getResourceAsStream(...);

when the resource is bundled as a jar/war or any other single file package for that matter.

then just change your code from

private BufferedImage getOverly() throws IOException {
   File classPathInput = null;
   try {
      classPathInput = new File(getClass().getResource("/image.png").toURI());
   } catch (URISyntaxException e) {
      e.printStackTrace();
   }
   return ImageIO.read(classPathInput);
}

to

private BufferedImage getOverly() throws IOException {

    InputStream in = getClass().getResourceAsStream("/image.png");

    return ImageIO.read(in);
}

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

Any other image type(ICO,WEBP) will return BufferedImage is null without error. You can’t rename the extension of file but you must convert image data to available image types.

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

https://stackoverflow.com/a/15726292/2090568

Related posts:

This entry was posted in spring boot. Bookmark the permalink.