Get Image from local directory using Swing?

被刻印的时光 ゝ 提交于 2021-01-27 17:40:44

问题


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);

回答1:


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" );



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/14819454/get-image-from-local-directory-using-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!