Loading an image into an Applet from a JAR file

Hello everyone, hopefully a simple question for someone to help me with!
Im trying to load some images into an applet, currently it uses the JApplet.getImage(url) method just before registering with a media tracker, which works but for the sake of efficiency I would prefer the images all to be contained in the jar file as oppossed to being loaded individually from the server.
Say I have a class in a package eg, 'com.mydomain.myapplet.class.bin' and an images contained in the file structure 'com.mydomain.myapplet.images.img.gif' how do I load it (and waiting for it to be loaded before preceeding?
I've seen lots of info of the web for this but much of it is very old (pre 2000) and im sure things have changed a little since then.
Thanks for any help!

I don't touch applets, so I can't help you there, but here's some Friday Fun: tracking image loading.
import java.awt.*;
import java.awt.image.*;
import java.beans.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.imageio.event.*;
import javax.imageio.stream.*;
import javax.swing.*;
public class ImageLoader extends SwingWorker<BufferedImage, Void> {
    private URL url;
    private JLabel target;
    private IIOReadProgressAdapter listener = new IIOReadProgressAdapter() {
        @Override public void imageProgress(ImageReader source, float percentageDone) {
            setProgress((int)percentageDone);
        @Override public void imageComplete(ImageReader source) {
            setProgress(100);
    public ImageLoader(URL url, JLabel target) {
        this.url = url;
        this.target = target;
    @Override protected BufferedImage doInBackground() throws IOException {
        ImageInputStream input = ImageIO.createImageInputStream(url.openStream());
        try {
            ImageReader reader = ImageIO.getImageReaders(input).next();
            reader.addIIOReadProgressListener(listener);
            reader.setInput(input);
            return reader.read(0);
        } finally {
            input.close();
    @Override protected void done() {
        try {
            target.setIcon(new ImageIcon(get()));
        } catch(Exception e) {
            JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
    //demo
    public static void main(String[] args) throws IOException {
        final URL url = new URL("http://blogs.sun.com/jag/resource/JagHeadshot.jpg");
        EventQueue.invokeLater(new Runnable(){
            public void run() {
                launch(url);
    static void launch(URL url) {
        JLabel imageLabel = new JLabel();
        final JProgressBar progress = new JProgressBar();
        progress.setBorderPainted(true);
        progress.setStringPainted(true);
        JScrollPane scroller = new JScrollPane(imageLabel);
        scroller.setPreferredSize(new Dimension(800,600));
        JPanel content = new JPanel(new BorderLayout());
        content.add(scroller, BorderLayout.CENTER);
        content.add(progress, BorderLayout.SOUTH);
        JFrame f = new JFrame("ImageLoader");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(content);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        ImageLoader loader = new ImageLoader(url, imageLabel);
        loader.addPropertyChangeListener( new PropertyChangeListener() {
             public  void propertyChange(PropertyChangeEvent evt) {
                 if ("progress".equals(evt.getPropertyName())) {
                     progress.setValue((Integer)evt.getNewValue());
                     System.out.println(evt.getNewValue());
                 } else if ("state".equals(evt.getPropertyName())) {
                     if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
                         progress.setIndeterminate(true);
        loader.execute();
abstract class IIOReadProgressAdapter implements IIOReadProgressListener {
    @Override public void imageComplete(ImageReader source) {}
    @Override public void imageProgress(ImageReader source, float percentageDone) {}
    @Override public void imageStarted(ImageReader source, int imageIndex) {}
    @Override public void readAborted(ImageReader source) {}
    @Override public void sequenceComplete(ImageReader source) {}
    @Override public void sequenceStarted(ImageReader source, int minIndex) {}
    @Override public void thumbnailComplete(ImageReader source) {}
    @Override public void thumbnailProgress(ImageReader source, float percentageDone) {}
    @Override public void thumbnailStarted(ImageReader source, int imageIndex, int thumbnailIndex) {}
}

Similar Messages

  • How to add multiple images to a JLabel from the jar file

    I want to add multiple images in a JLabel but the icon property only allows me to add one. I thought I could use html rendering to add the images I need by using the <img> tab, but I need to use a URL that points to the image.
    How do I point to an image inside the jar file? If I can't, is there another way to show multiple images in a JLabel from the jar file?

    Thanks, it works perfectly. It's a really smart way of fixing the problem too :)
    I also found your toggle button icon classes which is something I've also had a problem with.
    Thanks.

  • Trouble loading camera images into Photoshop 11 from Canon EOS

    I am having problems having the Adobe Photoshop 11 load pictures from my Canon EOS camera.  It says NO DEVICE FOUND when i go to import.  Worked fine with the older Adobe Photoshop had.   I can't figure this out.  My Sony camera is working fine.   Any suggestions??  Thanks

    when you connect your eos, does your os show it as connected (using a file browser, for example)?

  • I cannot seem to load raw images into LR 2.5.  I've been using this for years.  I always load from memory card, but it gives me an unknown error message.  I tried to load from camera, hard drive, & external drive and still will not work.  I checked import

    I cannot seem to load raw images into LR 2.5.  I've been using this for years.  I always load from memory card, but it gives me an unknown error message.  I tried to load from camera, hard drive, & external drive and still will not work.  I checked import menu and nothing has changed.  I loaded the photos onto my tablet and images are fine, so do not feel it is the memory card.  Any thoughts?

    The error message probably said "unsupported or damaged"
    The T3 requires Lightroom 3.4.1 or later. You can either upgrade to a more current version of Lightroom (version 5.6 is the most recent) or you can use the free Adobe DNG Converter to convert the RAWs to DNG, which should import into Lightroom properly.

  • Issues with Loading Images from a Jar File

    This code snippet basically loops through a jar of gifs and loads them into a hashmap to be used later. The images all load into the HashMap just fine, I tested and made sure their widths and heights were changing as well as the buffer size from gif to gif. The problem comes in when some of the images are loaded to be painted they are incomplete it looks as though part of the image came through but not all of it, while other images look just fine. The old way in which we loaded the graphics didn't involve getting them from a jar file. My question is, is this a common problem with loading images from a jar from an applet? For a while I had tried to approach the problem by getting the URL of the image in a jar and passing that into the toolkit and creating the image that way, I was unsuccessful in getting that to work.
    //app is the Japplet
    MediaTracker tracker = new MediaTracker(app);
    //jf represents the jar file obj, enum for looping through jar entries
    Enumeration e = jf.entries();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    //buffer for reading image stream
    byte buffer [];
    while(e.hasMoreElements())
    fileName = e.nextElement().toString();
    InputStream inputstream = jf.getInputStream(jf.getEntry(fileName));
    buffer = new byte[inputstream.available()];
    inputstream.read(buffer);
    currentIm = toolkit.createImage(buffer);
    tracker.addImage(currentIm, 0);
    tracker.waitForAll();
    images.put(fileName.substring(0, fileName.indexOf(".")), currentIm);
    } //while
    }//try
    catch(Exception e)
    e.printStackTrace();
    }

    compressed files are not the problem. It is just the problem of the read not returning all the bytes. Here is a working implementation:
    InputStream is = jar.getInputStream(entry);
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
    try{
    byte[] buf = new byte[1024];
    int read;
    while((read = is.read(buf)) > 0) {
    os.write(buf, 0, read);
    catch(Exception e){
         e.printStackTrace();
         return null;
    image = Toolkit.getDefaultToolkit().createImage(os.toByteArray());
    This works but I think you end up opening the jar a second time and downloading it from the server again. Another way of getting the images is using the class loader:
    InputStream is = MyApplet.class.getResourceAsStream(strImageName);
    In this case, the image file needs to be at the same level than MyApplet.class but you don't get the benefit of enumerating of the images available in the jar.

  • Fastest way to load an image into memory

    hi, ive posted before but i was kinda vague and didnt get much of a response so im going into detail this time. im making a java program that is going to contol 2 robots in a soccer competition. ive decided that i want to go all out and use a webcam instead of the usual array of sensors so the first step is to load an image into the memory. (ill work on the webcam once ive got something substanical, lol) since these robots have to be rather small (21cm in diameter) i can only use some pretty crappy processors. the robots are going to be both running gentoo linux on a 600 mhz processor, therefore it is absoleutely vital i have a fast method of loading and analyzing images. i need to be able to both load the image quickly, and more importainly analyze it quickly. ive looked at pixelgrabber which looks good, but ive read several things about javas image handling beging crap. these articles are a few years old, and im therefore wonding if there anything from the JAI that will do this for me. thx in advance.

    well i found out why i was having so much trouble
    installing JAI. im now back on windows and i cant
    stand it, so hopefully the bug will be fixed soon. oIt's not so bad. I mean, that's why we love Java! Once your linux problem is fixed you can just transfer your code there as is.
    well. i like the looks of JAI.create() but im not so
    sure how to use it. at this stage im tying to load an
    image from a file. i no to do this with pixelgrabber
    you use getcodebase(), but i dont know how to do it
    with JAI.create. any advice is appreciated. thx.Here are some example statements for handling a JAI image. There are other ways, I'm sure, but I've no idea which are faster, sorry. But this is quite fast on my machine.
    PlanarImage pi = JAI.create("fileload", imgFilename);
    WritableRaster wr = Raster.createWritableRaster(pi.getSampleModel(), null);
    int width = pi.getWidth(); // in case you need to loop through the image
    int height = pi.getHeight();
    wr = pi.copyData(); // copy data from the planar image to the writable one
    wr.getPixel(w,h,pixel); //  pixel is an int array with three elements.
    int red = pixel[0];     // to find out what's the red component
    int[] otherPixel = {0,0,0}
    wr.setPixel(w,h,otherPixel); // make pixel at location (w,h) black.                And here's a link with sample code using JAI. I've tried several of the programs there and they work.
    https://jaistuff.dev.java.net/

  • How to load an image into blob in a custom form

    Hi all!
    is there some docs or how to, load am image into a database blob in a custom apps form.
    The general idea is that the user has to browse the local machine find the image, and load the image in a database blob and also in the custom form and then finally saving the image as blob.
    Thanks in advance
    Soni

    If this helps:
    Re: Custom form: Take a file name input from user.
    Thanks
    Nagamohan

  • Read images from external jar file (Sun's Java L&F Graphics repository)

    Hi!
    I don't know how to read images from an external jar file. Sun has a Java Look and Feel graphics repository that contains a lot of good images that can be used on buttons and so on. This repository is delivered as a jar file, containing only images, and I want to read the image files from that jar file directly without including them inside my application jar file. The application and image jar files will be in the same directory.
    I have absolutely no clue how to solve this. Is it necessary to include the images inside my application jar file or is it possible to have them separate as I want.
    Would really appreciate some help!
    Best regards
    Lars

    Hi,
    There is two ways :
    1) Add your jarfile to the classpath.
    Use the class loader :
    URL url = ClassLoader.getSystemResource("your/package/image.gif");
    Image im = (new ImageIcon(url)).getImage();
    or
    Image im = Toolkit.getDefaultToolkit().getImage(url);2)If you don't want to add the jar to the classpath you can use this (under jdk 1.4):
    import java.util.*;
    import java.util.jar.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class ImageUtilities {
         public static Image getImage(String jarFileName, String fileName) {
              BufferedImage image = null;
              try {
                   JarFile jar = new JarFile(new File(jarFileName), false, JarFile.OPEN_READ);
                   JarEntry entry = jar.getJarEntry(fileName);
                   BufferedInputStream stream = new BufferedInputStream(jar.getInputStream(entry));
                   image = ImageIO.read(stream) ;
              catch (Exception ex) {
                   System.out.println(ex);
              return(image);
    }I hope this helps,
    Denis

  • Is it possible to load classes from a jar file

    Using ClassLoader is it possible to load the classes from a jar file?

    URL[] u = new URL[1] ;
    u[0] = new URL( "file://" + jarLocation + jarFileName + "/" );
    URLClassLoader jLoader = new URLClassLoader( u );
    Object clsName = jLoader.loadClass( clsList.elementAt(i).toString() ).newInstance();
    I get this error message.
    java.lang.ClassNotFoundException: ExceptionTestCase
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:297)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
    // "file://" + fileLocation + fileName + "/" This works fine from a browser.
    Is there anything I am missing? Thanks for the reply.

  • Reading an xml file from a jar file

    Short question:
    Is it possible to read an xml file from a jar file when the dtd is
    placed inside the jar file? I am using jdom (SAXBuilder) and the default
    sax parser which comes with it.
    Long Question:
    I am trying to create an enterprise archive file on Weblogic 6.1. We
    have a framework that is similar to the struts framework which uses it's
    own configuration files
    I could place the dtd files outside the jar ear file and specify the
    absolute path in an environment variable in web.xml which is
    configurable through the admin console.
    But I want to avoid this step and specify a relative path within the jar
    file.
    I have tried to use a class which implements the entityresolver as well
    as try to extend the saxparser and set the entity resolver within this
    class explicitly, but I always seem to sun into problems like:
    The setEntityresolver method does not get called or there is a
    classloader problem. i.e. JDOM complains that it cannot load My custom
    parser which is part of the application
    Vijay

    Please contact the main BEA Support team [email protected]
    They will need to check with product support to determine
    the interoperatablity of Weblogic Server with these other
    products.

  • Urgent help for processing XML stream read from a JAR file

    Hi, everyone,
         Urgently need your help!
         I am reading an XML config file from a jar file. It can print out the result well when I use the following code:
    ===============================================
    InputStream is = getClass().getResourceAsStream("conf/config.xml");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;
    while ((line = br.readLine()) != null) {
    System.out.println(line); // It works fine here, which means that the inputstream is correct
    // process the XML stream I read from above
    NodeIterator ni = processXPath("//grid/gridinfo", is);
    Below is the processXPath() function I have written:
    public static NodeIterator processXPath(String xpath, InputStream byteStream) throws Exception {
    // Set up a DOM tree to query.
    InputSource in = new InputSource(byteStream);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setNamespaceAware(true);
    Document doc = dfactory.newDocumentBuilder().parse(in);
    // Use the simple XPath API to select a nodeIterator.
    System.out.println("Querying DOM using " + xpath);
    NodeIterator ni = XPathAPI.selectNodeIterator(doc, xpath);
    return ni;
    It gives me so much errors:
    org.xml.sax.SAXParseException: The root element is required in a well-formed doc
    ument.
    at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1213
    at org.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(XM
    LDocumentScanner.java:570)
    at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.endO
    fInput(XMLDocumentScanner.java:790)
    at org.apache.xerces.framework.XMLDocumentScanner.endOfInput(XMLDocument
    Scanner.java:418)
    at org.apache.xerces.validators.common.XMLValidator.sendEndOfInputNotifi
    cations(XMLValidator.java:712)
    at org.apache.xerces.readers.DefaultEntityHandler.changeReaders(DefaultE
    ntityHandler.java:1031)
    at org.apache.xerces.readers.XMLEntityReader.changeReaders(XMLEntityRead
    er.java:168)
    at org.apache.xerces.readers.UTF8Reader.changeReaders(UTF8Reader.java:18
    2)
    at org.apache.xerces.readers.UTF8Reader.lookingAtChar(UTF8Reader.java:19
    7)
    at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.disp
    atch(XMLDocumentScanner.java:686)
    at org.apache.xerces.framework.XMLDocumentScanner.parseSome(XMLDocumentS
    canner.java:381)
    at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1098)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.
    java:195)
    at processXPath(Unknown Source)
    Thank you very much!
    Sincerely Yours
    David

    org.xml.sax.SAXParseException: The root element is required in a well-formed document.This often means that the parser can't find the document. You think it should be able to find the document because your test code could. However if your test code was not in the same package as your real (failing) code, your test is no good because getResourceAsStream("conf/config.xml") is looking for that file name relative to the package of the class that contains that line of code.
    If your test code wasn't in any package, put a slash before the filename and see if that works.

  • Problem parsing XML with schema when extracted from a jar file

    I am having a problem parsing XML with a schema, both of which are extracted from a jar file. I am using using ZipFile to get InputStream objects for the appropriate ZipEntry objects in the jar file. My XML is encrypted so I decrypt it to a temporary file. I am then attempting to parse the temporary file with the schema using DocumentBuilder.parse.
    I get the following exception:
    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element '<root element name>'
    This was all working OK before I jarred everything (i.e. when I was using standalone files, rather than InputStreams retrieved from a jar).
    I have output the retrieved XML to a file and compared it with my original source and they are identical.
    I am baffled because the nature of the exception suggests that the schema has been read and parsed correctly but the XML file is not parsing against the schema.
    Any suggestions?
    The code is as follows:
      public void open(File input) throws IOException, CSLXMLException {
        InputStream schema = ZipFileHandler.getResourceAsStream("<jar file name>", "<schema resource name>");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
          factory.setNamespaceAware(true);
          factory.setValidating(true);
          factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
          factory.setAttribute(JAXP_SCHEMA_SOURCE, schema);
          builder = factory.newDocumentBuilder();
          builder.setErrorHandler(new CSLXMLParseHandler());
        } catch (Exception builderException) {
          throw new CSLXMLException("Error setting up SAX: " + builderException.toString());
        Document document = null;
        try {
          document = builder.parse(input);
        } catch (SAXException parseException) {
          throw new CSLXMLException(parseException.toString());
        }

    I was originally using getSystemResource, which worked fine until I jarred the application. The problem appears to be that resources returned from a jar file cannot be used in the same way as resources returned directly from the file system. You have to use the ZipFile class (or its JarFile subclass) to locate the ZipEntry in the jar file and then use ZipFile.getInputStream(ZipEntry) to convert this to an InputStream. I have seen example code where an InputStream is used for the JAXP_SCHEMA_SOURCE attribute but, for some reason, this did not work with the InputStream returned by ZipFile.getInputStream. Like you, I have also seen examples that use a URL but they appear to be URL's that point to a file not URL's that point to an entry in a jar file.
    Maybe there is another way around this but writing to a file works and I set use File.deleteOnExit() to ensure things are tidied afterwards.

  • Running scripts, bat files, etc from a jar file

    Hello,
    Does anyone know of a way, or even if it is possible to run a script or batch file from a jar file?
    For instance, lets say I have a batch file that I can run from the command prompt by typing :
    myBatchFile.bat
    and now I write a very simple java app that will do the same:
    public class Test {
    public static void main(String[] args) {
    try {
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(�myBatchFile.bat�);
    } catch (Exception e) {
    e.getMessage();
    The above app will work as long as the batch file is in the current directory, but how or can I make it work if I stick the batch file in a jar file along with the app?
    I tried using the manifest file with no luck.
    I tried creating a URI to the jar file, wrapping it in a File and then passing that File to the exec method also with no luck.
    I searched all the forums on Sun but came up with nothing.
    I performed a google search also with no luck.
    Does anyone have the answer to this? Even if I can get a definitive �No it can�t be done� answer. Although I would think that it should be able to be done.
    Thanks

    Hi,
    you cannot execute anything being inside a jar-file. The OS doesn't know anythig about jar-files and cannot look inside one to find the program/script/batch you want to execute.
    You could do a workaround by extracting the file from the jar-file before calling exec(). But normally OS dependent files should not be inside a jar-file and remain in a own directiory.
    Andre

  • How to read a text file from a Jar file

    Hi
    How can I read a text file from a Jar file?
    Thanx in advance..

    thanx
    helloWorld it works.damn, I didn't remove it fast enough. Even if it is urgent, it is best not to mention it, telling people just makes them take longer.

  • How to call a function from a JAR file

    Hi ALL,
    I am trying to call a Public function from a JAR file from my JAVA
    file. Can you please provide an example or suggest a good resource?
    Basically my java file Test.Java should call a function called 'export_a_doc' from a JAR file Export.jar. How do I refer this in my Java file and call 'export_a_doc'?
    Thanx

    Hi,
    HERE IS MY JAVA FILE
    // We need this for Starting our Export Process
    import com.newexport.Myclass;
    public class MyTest {
         // Our function to Start Export
         protected static void test(String[] args) {
         System.out.println("Starting. \n---------------------");
         Myclass p = new Myclass();
         try {
    p.Start_Export(args);
    System.out.println("Finished. \n---------------------");
         } catch(Exception e) {
    e.printStackTrace();
         public static void main(String[] args) {
         test(args);
    HERE IS THE BATCH FILE TO BUILD AND RUN
    cd \JNI\Srcs
    echo "-------------"
    c:\JBuilder7\jdk1.3.1\bin\javac -classpath C:\JNI\Export.jar MyTest.java
    echo "-------------"
    \JBuilder7\jdk1.3.1\bin\java.exe -classpath c:\JNI\Export.jar MyTest
    The Export.jar uses other jar files
    Raj

Maybe you are looking for