Share this page 

Load an Image from a JAR fileTag(s): AWT


[JDK1.1 application]
String imgName = "image.jpg";
URL imgURL = getClass().getResource(imgName);
Toolkit tk = Toolkit.getDefaultToolkit();
Image img = null;
try {
 MediaTracker m = new MediaTracker(this);
 img = tk.getImage(imgURL);
 m.addImage(img, 0);
 m.waitForAll();
 }
catch (Exception e) {
 e.printStackTrace();
}
[JDK 1.1 applet]
Because of some security reason, it's not possible with some browser (like Netscape) to use the getResource() method from an Applet. Instead we must use the getResourceAsStream method.
Image img = null;

try {
  MediaTracker m = new MediaTracker(this);
  InputStream is = getClass().getResourceAsStream("image.gif");
  //
  // if your image is in a subdir in the jar then
  //    InputStream is = getClass().getResourceAsStream("img/image.gif");
  //  for example
  //
  BufferedInputStream bis = new BufferedInputStream(is);
  // a buffer large enough for our image
  //
  // can be
  //   byte[] byBuf = = new byte[is.available()];
  //   is.read(byBuf);  or something like that...
  byte[] byBuf = = new byte[10000]; 
  
  int byteRead = bis.read(byBuf,0,10000);
  img = Toolkit.getDefaultToolkit().createImage(byBuf);
  m.addImage(img, 0);
  m.waitForAll();
  }
 }
catch(Exception e) {
  e.printStackTrace();
}
[JDK 1.2 application]
URL url = this.getClass().getResource("myIcon.gif");
button.setIcon(new ImageIcon(url));