7

The following code is running successfully in BlueJ IDE, but not in Eclipse.

String path="images/pic1.jpg";

BufferedImage myPicture = null;
    try {
        myPicture = ImageIO.read(new File(path));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

My image path is same in both the IDE. Also, I observed directory structure is same for *.class file and image files.

Why this happens in eclipse only?

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
paraguma
  • 187
  • 1
  • 1
  • 7
  • Is `"images/pic1.jpg"` an application resource? An 'application resource' might be an icon used for a button or menu item, an application BG or splash, etc. If so, the code is using an entirely wrong approach. It should be accessing the image by URL from the run-time class-path. Will explain further if intelligent questions are posed. – Andrew Thompson Aug 21 '12 at 05:54
  • Before calling `read`, you should `assert` that the file exists, to rule out more possibilities of failure. – Volker Stolz Aug 21 '12 at 09:56
  • if i used runtime class-path then i should include images path to it. my question is that what is the correct approach to use images from files in java application? – paraguma Aug 22 '12 at 09:03

7 Answers7

4

You must use

System.getProperty("user_dir")+File.separator+"image"+File.separator+"im0001.jpg";
aleroot
  • 71,077
  • 30
  • 176
  • 213
Prasad
  • 1,188
  • 3
  • 11
  • 29
2

This is not an Eclipse bug. You need to copy the image files into the Eclipse Project Main Folder (not src subfolder).

Chaos
  • 11,213
  • 14
  • 42
  • 69
Pazhaniapa
  • 21
  • 1
1

Please make sure your images folder is resource folder (which mean it is on the CLASSPATH) and write

  BufferedImage myPicture = null;
   try {
      myPicture = ImageIO.read("images/pic1.jpg");
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

or use the alternative.

   BufferedImage myPicture = null;
   try {
      myPicture = ImageIO.read(this.getClass().getResource("/images/pic1.jpg"));
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
Sai Ye Yan Naing Aye
  • 6,622
  • 12
  • 47
  • 65
1

Eclipse sets the default file location to the root bin folder, not to root or to the package folder. Make sure your files are in the bin folder.

st1ph1n
  • 11
  • 1
0

Try this..

String path="d:\\images\\pic1.jpg";

BufferedImage myPicture = null;
    try {
        myPicture = ImageIO.read(new File(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
0

just check your image path with System.out.println(System.getProperty("user.dir"));

aleroot
  • 71,077
  • 30
  • 176
  • 213
0

Default libraries in eclipse does not support "ImageIO".

Asanga Ranasinghe
  • 72
  • 1
  • 1
  • 11