javaimageswingembedded-resourceillegalargumentexception

Display an image in java


public void loadStdImage() throws IOException
{
    Image image = ImageIO.read(this.getClass().getResource("/Resources/Images/Student/Capture.png"));  //Line 350
    ImageIcon icon = new ImageIcon(image);
    JLabel lblImage = new JLabel(icon);
    lblImage.setIcon(icon);
    lblImage.setBounds(753, 50, 149, 171);
    add(lblImage);
}

I tried many things... but nothing works out. Continuously showing the following run-time error

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at View.Student.loadStdImage(Student.java:350)

Project folder structure is:

Project Explorer view in Eclipse for a project


Solution

  • I have standard Eclipse project:

    Eclipse project

    and my test class looks like (minimal):

    package q34460547;
    
    import java.awt.Image;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    
    public class LoadTest {
    
        public static void main(String[] args) throws IOException {
            new LoadTest().loadStdImage();
        }
    
        public void loadStdImage() throws IOException {
            Image image = ImageIO.read(this.getClass().getResource("/ScreenShot005.png"));
        }
    
    }
    

    and now, when I used

    ImageIO.read(this.getClass().getResource("/ScreenShot005.png"));
    

    image is loaded from res so called source folder in Eclipse.

    When I used

    ImageIO.read(this.getClass().getResource("ScreenShot005.png"));
    

    image s loaded from the folder in which LoadTest.java file is (to be precise it is also compiled to same folder - in Eclipse it's bin).

    You can find more info for example here - What is the difference between Class.getResource() and ClassLoader.getResource()?

    edit:

    The image has to be on classpath (when using Class.getResource), that's why it was not loaded from Resources folder. There are two options, use another version of ImageIO.read() or make your Resources folder a source folder:

    Project properties - source folders in Eclipse