1

I usually use this to load from the same package

Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();

How can I load an image from a package specified for images?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
JayManHall
  • 11
  • 1
  • 4
  • Well where *is* the image, relative to the class? Please give more context, and it should be pretty easy to help you. – Jon Skeet Apr 05 '14 at 19:53
  • Find the solution here [How to retrieve image from project folder?](http://stackoverflow.com/questions/22744920/how-to-retrieve-image-from-project-folderel?answertab=votes#tab-top) – Braj Apr 05 '14 at 19:56

3 Answers3

3

You can try any one

// Read from same package 
ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));

// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));

Use

ImageIcon icon=new ImageIcon(<any one from above>);

You can use BufferedImage also in place of ImageIcon directly.

For more information read it here How to retrieve image from project folder?

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
1
Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();

Suggests that "image.png" resides within the same package as the class represented by this

You can use absolute paths to reference resources that reside within different packages

String img = "/path/to/images/image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));

The important concept here is to understand that the path is suffixed to class path

Personally, you should be using ImageIO over ImageIcon, apart from supporting more formats, it throws an IOException when something goes wrong and is guaranteed to return a fully loaded image (when successful).

See How to read images for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You don't need to use(like "this") locally: this.getClass().getResource( img ); Just use class loader globally : ClassLoader.getSystemResource( path ); I'm gonna show you my library function below

public final class PackageResourceLoader {

    // load image icon
    public static final ImageIcon loadImageIcon( final String path ) {

        final URL res = ClassLoader.getSystemResource( path );

        return new ImageIcon( res );
    }


    // load buffered image
    public static final BufferedImage loadBufferedImage( final String path ) {

        final URL res = ClassLoader.getSystemResource( path );

        try { return ImageIO.read( res ); }
        catch( final Exception ex ) { return null; }
    }
}

if your img.png is in package pack use PackageResourceLoader.loadImageIcon( "pack/img.png" );