0

Some years ago I took a couple of courses in programming. Now I'm in a situation where some very basic image processing might save me loads of time. Unfortunately I'm a bit stuck trying to read an image. I haven't done this before and basically just copied some code I found, but I get "javax.imageio.IIOException: Can't read input file!". I've tried moving the image "Test.jpg" and change the path. I don't understand what is causing the issue. I use macOS, not sure if this is relevant.

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class MyImage{
  public static void main(String args[])throws IOException{
    BufferedImage image = null;
    File f = null;
    
    try {
        f = new File("Users/simonprobert/eclipse-workspace/LineLengthCounter/src/Test.jpg");
        image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
        image = ImageIO.read(f);
        System.out.println("Reading complete.");
    } catch(IOException e){
        System.out.println("Error: "+e);
    }
  }
}

(Currently I'm just trying to read the image, the rest is not important at this point)

  • 1
    I'm on Mac. "Users" is a folder on the "Macintosh HD". The local workspace is the "LineLengthCounter", so I'm guessing I should be able to just have the path "src/Test.jpg", but this doesn't work. – Simon Probert Nov 03 '20 at 11:21
  • 2
    The filepath looks incorrect. `"/src/Test.jpg"` might work, otherwise you could use the absolute path to the file, e.g. `"C:/Users/simonprobert/eclipse-workspace/LineLengthCounter/src/Test.jpg"`. If you plan on loading that resource in a JAR later on, you should take a look at [this answer](https://stackoverflow.com/a/16313299/11441011), which is the preffered way to load a resource. Furthermore, here is some information on [Absolute, Relative and Canonical Paths](https://www.programmergate.com/java-io-difference-absoluterelative-canonical-path/). – maloomeister Nov 03 '20 at 11:46
  • You should probably probably use an absolute path (starting with "/"), otherwise the path will be relative to the current directory. However, it's usually not a good idea to hardcode paths like this. If the image is part of your application, use a resource, otherwise consider using the program arguments like this: `f = new File(args[0]);` and specify the file on the command line. It's usually easier to find the file using path completion in a shell. – Harald K Nov 04 '20 at 07:57
  • Thank you! I tried around some more with the path and now i works! – Simon Probert Nov 04 '20 at 09:09

0 Answers0