tech2504
tech2504

Reputation: 977

Get Image from local directory using Swing?

I trying to load image from local directory into ImageIcon(URL).This images files access from .jar file.The jar file name is swingex.jar.The project structure like

F:/>SwingExample
         |
         |___src
         |
         |___build.xml
         |
         |___lib
               |
               |___swingsex.jar(generated through build.xml file)
         |
         |__resource
                   |
                   |_____images
                            |
                            |___logo1.png

How to read logo1.png file?

I'm trying to like this

  1. file:///f://resources//images//processedimages// returns null

  2. ClassLoader.getSystemResource("resources/images/processedimages/"); returns null

Update :- Still i have problem.because i created jar file on SwingExample and excludes the resource/images directory .When run the jar file its not recognized the resource/images folder.But i ran the SwingExample Project through eclipse it working fine.The code is

File directory = new File (".");
Image img = null;
String path="";
URL url=null;
try {
  path=directory.getCanonicalPath()+"/resources/images/logo1.png";
               img = ImageIO.read(new File(getDefaultImageUploadPath());

} catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}
        return new ImageIcon(img);

Upvotes: 2

Views: 6464

Answers (3)

Sazzad Hissain Khan
Sazzad Hissain Khan

Reputation: 40255

For java projects, default directory always starts from src. Your code will work fine only if you organize resource in below way.... :)

SwingExample
         |
         |___src
         |    |
         |    |_____resource
         |          |
         |          |_____images
         |                   |
         |                   |___logo1.png
         |___build.xml
         |
         |___lib
               |
               |___swingsex.jar(generated through build.xml file)

This time getClassLoader().getResourceAsStream( "/resource/images/logo1.png" ); wont return null.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347332

Depending on the execution context of your application, you could use a relative path instead

URL imgURL = new File( "resource/images/logo1.png" ).toURI().toURL();

Or

URL imgURL = new File( "../resource/images/logo1.png" ).toURI().toURL();

Might work, but Aubin is correct, it would be easier to embed the image within your application and access via the class loader context

Upvotes: 1

Aubin
Aubin

Reputation: 14883

URL imgURL =
   new File( "F:/SwingExample/resource/images/logo1.png" ).toURI().toURL();

But I suggest to put resource into src.

If resource is in src, you may access them by class loader easily.

getClassLoader().getResourceAsStream( "resource/images/logo1.png" );

Upvotes: 3

Related Questions