1

I'm trying to read an image from a relative path:

String fp = "../resources/img/wc/text/039.tiff";

The following code succeeds:

File fi = new File(getClass().getResource(fp).getPath());
System.out.println("fi: " + fi);
if (fi.exists() && !fi.isDirectory()) {
    System.out.println("file exists");  // <-- console prints this
}

try {
    img = ImageIO.read(getClass().getResource(fp));
    System.out.println("file read");  // <-- console prints this
} catch (IOException e) {
    e.printStackTrace();
}

... but the following code just after it:

System.out.println(img.getType());

... fails, reporting:

Exception in thread "main" java.lang.NullPointerException
at com.ddc.fmwscanner.java.LoadImageApp.ddNextImage(LoadImageApp.java:60)
at com.ddc.fmwscanner.java.LoadImageApp.<init>(LoadImageApp.java:85)
at com.ddc.fmwscanner.main.FmwScanner.main(FmwScanner.java:15)

I know the image is valid, because I can open it using non-Java methods. However, those methods will not open the image from a .jar, so I need to use a pure Java method.

Any insight is appreciated.

c0der
  • 18,467
  • 6
  • 33
  • 65
dave_d
  • 159
  • 1
  • 9
  • 1
    Your path is likely incorrect. Understand that resources start at the class-path, meaning the location of your class files. – Hovercraft Full Of Eels Jun 10 '17 at 16:08
  • How would I verify an incorrect path? (ugh, can't post code easily in these comments.) The following: `System.out.println(getClass().getResource(fp).getPath());` returns an absolute path that is definitely correct. – dave_d Jun 10 '17 at 16:11
  • 1
    Don't treat classpath resources as files. Resources are loaded from the classpath. Files are loaded from the file system. A resource path may not contain .. Read the javadoc. – JB Nizet Jun 10 '17 at 16:11
  • Hmm, perhaps, @IlarioPierbattista. I'll try it with a .jpg. – dave_d Jun 10 '17 at 16:15
  • 1
    @IlarioPierbattista: [perhaps a better duplicate](https://stackoverflow.com/questions/6023039/java-nullpointerexception-from-class-getresource) or [this one](https://stackoverflow.com/questions/13796331/jar-embedded-resources-nullpointerexception). – Hovercraft Full Of Eels Jun 10 '17 at 16:17
  • Wow, .jpg worked fine. I never would have dreamt a .tiff would be problematic. Thanks, guys! – dave_d Jun 10 '17 at 16:21
  • I'll post the solution when I find a means of loading a .tiff. – dave_d Jun 10 '17 at 16:22
  • For opening 'esoteric' TIFF files, you may find this extension useful: https://github.com/geosolutions-it/imageio-ext – tevemadar Jun 10 '17 at 16:33

1 Answers1

1

This ended up being a problem with loading .tiff files in pure Java. Installing TwelveMonkeys ImageIO plugin did the trick. Thanks again, especially to @IlarioPierbattista, who directed me to the solution!

dave_d
  • 159
  • 1
  • 9