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.

Similar Messages

  • Loading images from a jar file

    Hi,
    My application displays images, until it's placed in a JAR file, then it can't display them even though the JAR file contains the images.
    I saw this problem in a previous question which was solved using
    URL url = MyClass.class.getResource("abc.gif");
    Image img=Toolkit.getDefaultToolkit().getImage(url);
    ....which btw didn't work for me either......
    This method should be made obsolete using ImageIcon, which I am using, but the images still won't appear...
    Any suggestions?

    It works fine that way (...getClass().getResource....) until I create the jar file, and then I get a null pointer exception when it tries to load the image.
    When I use
    javax.swing.ImageIcon icon = new javax.swing.ImageIcon(("/images/imageName.jpg"));
    the application works but without the images.......

  • Read images from a jar file?

    Hello, I'm converting a 6i app to 10g. This app does a ton of read_image_file() calls to
    change GIF images on the screen based on user actions. In 6i the images are all stored on the local hard drive. The images are not icons for buttons, but images that appear in different locations on the screen.
    For 10g, is it possible to leave the images in a jar file and effectively read the images from that? Otherwise, I suppose I'm looking at using webutil functionality to download the jar file and unjar it into an images directory for reading from the client?
    Any best-practice scenario for this sort of thing?
    Thanks for any info,
    Gary

    We are migrating from 6i to 10g too. And I try to not use webutil. All my pictures (icons gif files) are in a jar file.
    Just make attention of the size of your pictures. The jar file is loaded when you launch the application (the first time, and after, only if the jar file has changed).

  • 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.

  • Need help with loading images in executable Jar

    Hi,
    I've developed an application using netbeans that needs to load and display images.
    I use netbeans Clean and Build function to create an executable Jar file. When I run the executable Jar file it runs fine but when I come to a section of the application that needs images it freezes and can't load the images.
    When I then return to netbeans the part of the program that did successfully run before Clean and Build doesn't work anymore and I get an error message saying Uncaught error fetching image:
    I use,
    URL url = getClass().getResource("images/image1.png");
    Image image1 = Toolkit.getDefaultToolkit().getImage(url);to load an image.
    Can someone tell me why, when I clean and build my project to create a JAR, my images fail to load.
    Should I be storing the images in a specific folder or something??
    Thanks

    I've opened the JAR using winzip and, for some reason, the JAR hasn't preserved my file structure. So, when I try to look for an image as follows:
    URL url = getClass().getResource("images/file1.png");
    Image img= Toolkit.getDefaultToolkit().getImage(url);The folder doesn't exist and so it can't find the image.
    Can someone tell me how to keep my file structure when I create the JAR or an alternative way to find the images within the JAR file.
    Cheers

  • Issue in loading images from Apache webserver in JSF image tags on WLS 10

    I have configured the apache webserver2.0 for passing on the request to weblogic 10.0. I have images in apache webserver. In my application on weblogic i am using JSF f. In JSF for <h:graphics> tag i am not able to load images from apache webserver. issue we found out that it prepend a context url on it.
              pls provide if u have any solution for it.
              Edited by neerajr at 11/16/2007 3:33 PM

    Hi, Neeraj,
              Are you actually telling <h:graphicImage>? As per html_basic.tld, the "uri" attribute is context-relative.
              Using "value" attribute instead of "url" attribute may be helpful. Something like
              <h:graphicImage id="fooImage" value="http://www.foosite.com/image/foo.jpg"/>
              This should work on WLS10.0 if you are using the JSF library bundled in it.
              Thanks,
              -Fred.

  • Loading images from a JAR

    Hi,
    My class is currently stored in a subdirectory of my JAR file, and in the directory with the class is a "textures" directory, containing all of my images.
    When I run my class from the directory before I zip it up to be a JAR, it works fine. But, as soon as I run it as a JAR file, it crashes when loading the images.
    Here's the code I'm using to load the images:
    BufferedImage temp = null;
    String path = this.getClass().getResource("textures/" + imagePath).toString();
    temp = ImageIO.read(new File(new URI(path)));What am I doing wrong?
    Thanks for any assistance! =)

    Hiii bro ,
    I think this will help u ,,,,,,,,
    suppose you have a folder Image , under that folder there are some image files and you have a main class say TestMain.class .
    In your main class(TestMain)
    import javax.swing.ImageIcon;
    Now write this code into your main class----------->
    public ImageIcon customOpenIcon = new ImageIcon(TestMain.class.getResource("/image/expanded.gif"));Thanks,
    sb

  • ? SplashScreen - retrieving an image from a jar file ?

    When you want to use the Java SplashScreen you provide a run flag of the form:
    -splash:image.png
    Is there a way to have the 'image.png' reference a file in one of the jar files?I don't believe the jar files are loaded by the time SplashScreen activates so that might be why I can't seem to be able to do it, but that was when I checked over a year ago ... have things changed?
    Alternatively (and probably the preferred option for me) is there a way to tell the SplashScreen to create an empty splash so that one exists when I use the 'splash.setImageUrl()' method? Currently I have to set the splash image to be some empty/transparent image via:
    -splash:empty.png
    Then I set my own desired image via the 'splash.setImageUrl()' method...BUT, I still need to have the 'empty.png' file contained in the root folder of my project and this sucks. I'd like to be able to tell java that I want to create an empty splash, without having to provide an empty image, and then when the splash is created, I can use the image url method as normal to write my own image to the splash display.
    thx.

    morgalr, this is independent of code, it's just the splash screen that start up before any code runs so you could do this with any of your projects that you have.
    You need to specify splash image via run command of:
    -splash:image.png
    so, if you have a jar file that has an image in it, and you place it on your classpath and then try to run your code with
    -splash:package/path/image.png
    it doesn't seem to work...you'll know because either you'll see a splash screen or you won't. Note that the splash screen disappears the first time an AWT/Swing event is encountered (ie a frame is displayed, etc) so it may only last a few milliseconds but it still should come up. All of the links that discuss this talk about specifying a path to an images directory, but this images directory has to be in your project root folder and not in the source tree (as best as I can tell through experimentation).
    I guess what I would ultimately want would be to be able to create a SplashScreen instance through each program in my project without having to provide a runtime flag that only generates the instance if the provided image is available. If I it still provided a SplashScreen instance then I would be able to use the setImageUrl() method from code to provide the desired image. Also, it would be nice if the splashscreen remained some set time even after the application window popped up with an AWT/Swing event that now causes it to disappear instantly...but that one I can overcome with my own JWindow post-splash display that mimics the effect.
    thanks.

  • Load image from URL on file open, then embed image

    I am trying to create a PDF form with an image field that is empty/blank by default. When the PDF is opened, I want it to load the image at C:\picture.jpg and embed that image in that document.
    I need it to load on file open because C:\picture.jpg will be different each time the file is opened. Currently, if I set the image URL and embed it, it uses the image at the first time it's embedded.

    Okay, I created userInfo.js and placed it in C:\Program Files (x86)\Adobe\Acrobat 10.0\Acrobat\Javascripts. That file (adapted from How do I change an image in a button automatically without changing its location?):
    myIcon = app.trustedFunction( function (){app.beginPriv();
    this.getField("userInfo").buttonImportIcon("C:\\picture.jpg")
    app.endPriv();})
    I then added event.target.myIcon(event.target) to topmostSubform.Page1::initialize.
    I get the following error when opening my pdf:
    TypeError: this.getField("userInfo") is null
    2:XFA:topmostSubform[0]:Page1[0]:initialize
    I know the field is null. I want it to be null until I open the pdf. Is there another reason that error would be appearing?

  • How To Load Sound From Inside jar File?

    Hello There
    i've made a jar file that contains Images&Pictures But I Can't Use Them
    So I Used For Loading Images
      URL url = this.getClass().getResource("image.jpg");
             setIconImage(new ImageIcon(url).getImage());and for loading sound when i use
      URL url = this.getClass().getResource("Bond2.wav");         
           AudioInputStream stream = AudioSystem.getAudioInputStream(new File(url));there's an error That The file Constructor doesn't take url
    how can i fix it?

    First_knight wrote:
    and for loading sound when i use
      URL url = this.getClass().getResource("Bond2.wav");         
    AudioInputStream stream = AudioSystem.getAudioInputStream(new File(url));there's an error That The file Constructor doesn't take url
    how can i fix it?Remove the "new File()". There is a getAudioInputStream() method that takes a URL.
    AudioInputStream in = AudioSystem.getAudioInputStream(url);

  • Problem with loading Images from Google

    if i click on one of this pictures & chose open in new tab https://fud.community.services.support.microsoft.com/Fud/FileDownloadHandler.ashx?fid=23a96ac6-b84d-4e5a-be5f-ee9132199fac new windows starts loading, but the loading never ends, in past it use to open this page full screen if i chose open in next tab https://fud.community.services.support.microsoft.com/Fud/FileDownloadHandler.ashx?fid=bab88957-319a-4363-94c3-3249dffdb36a, & firefox starts to consume a lot of Disk usage when its loading endlessly https://fud.community.services.support.microsoft.com/Fud/FileDownloadHandler.ashx?fid=0da2dd58-2534-4f61-80e7-c5810795a79d, whats up with fox? tried that thing with IE to, no endless loading, but kind of like plank page, background same color like u see on the link (dark), but no picture full page dark, & IE has no adds, did google change how this works?, but they are just not finished removing the stuff & that left plank page & fox is unable to load this blank page?, so i guess its not much issue with images, but didn't know how to name the topic
    all my adds, for extra information
    Adblock Edge
    Enforce Encryption
    Ghostery
    More In Content UI +

    Test in a similar manner to my suggestion in your memory leaks question [/questions/1048975]
    You are using plugins that are designed to block things and that is probably what is occurring, especially with multiple such plugins.
    See also
    * [[Use the Profile Manager to create and remove Firefox profiles]]
    * [[Firefox uses too much memory (RAM) - How to fix]]
    *[[Disable or remove Add-ons]]
    Additionally also see
    *[[Websites show a spinning wheel and never finish loading]]
    *[[Firefox can't load websites but other browsers can]]
    Must admit I have not got a clue what ms fud.community.services. is

  • Loading classes from another jar file

    I've set up my jnpl file so that it references a core jar file (contains main() function). The jnlp also references another jar file (app.jar) which contains class files that I load and instantiate dynamically (using ClassLoader). The core.jar file contains a manifest that includes a reference to app.jar.
    The app works fine when I use "java -jar core.jar" from the command line.
    However, when I wrap the jars using jnlp, I always get a null pointer exception because it cannot find any class that is in the app.jar file. I've tried different strategies, such as trying to load a class file that sits on the server (in a jar file and not in a jar file), but that also fails if I use jnlp (However, it works if I use "java -jar core.jar")
    Any ideas what is going on?

    This is the "OckCore.jar" manifest before signing:
    Manifest-Version: 1.0
    Main-Class: com.Ock.OckCore.OckApp
    Class-Path: . OckMaths.jar
    Created-By: 1.4.0-beta3 (Sun Microsystems Inc.)
    Name: com.Ock.OckCore.OckApp.class
    Java-Bean: FalseThis is the manifest after signing:
    Manifest-Version: 1.0
    Main-Class: com.Ock.OckCore.OckApp
    Created-By: 1.4.0-beta3 (Sun Microsystems Inc.)
    Class-Path: http://hazel/Ock/. http://hazel/Ock/OckMaths.jar
    Name: com/Ock/OckCore/OckApp.class
    SHA1-Digest: KRZmOryizx9o2L61nN+DbUYCgwo=I have removed a load of irrelevant stuff from the "after" manifest to keep it readable.
    note that :-
    The OckApp.class loads normally from webstart and tries to load a class from OckMaths.jar.
    I can prove that OckApp.class does load because it creates a log file when it does.
    The OckApp.class tries to load a class from the OckMaths.jar. This fails if webstart is used but works if OckCore is launched using "java -jar OckCore.jar".
    The jars do exist at the location specified by the manifest.
    The application launches normally if I use "java -Jar OckCore.jar"
    Here is the jnlp file
    <?xml version='1.0' encoding='UTF-8'?>
    <jnlp
         spec="1.0"
         codebase="http://hazel/Ock"
         href="OckMaths.jnlp">
         <information>
              <title>Ock Maths Demo</title>
              <vendor>Rodentware Inc</vendor>
              <description>Demo of a ported app running as a Java Webstart application</description>
              <description kind="short">An app running as a Java Webstart application"></description>
              <offline-allowed/>
         </information>
         <security>
              <all-permissions/>          
         </security>
         <resources>
              <j2se version="1.3"/>
              <jar href="OckCore.jar"/>
              <jar href="OckMaths.jar"/>
         </resources>
         <application-desc main-class="com.Ock.OckCore.OckApp">
    </jnlp> I have also signed the jars outside of a webdirectory. I get the following manifest file:
    Manifest-Version: 1.0
    Main-Class: com.Ock.OckCore.OckApp
    Created-By: 1.4.0-beta3 (Sun Microsystems Inc.)
    Class-Path: . OckMaths.jar
    Name: com/Ock/OckCore/OckApp.class
    SHA1-Digest: KRZmOryizx9o2L61nN+DbUYCgwo=
    note that :-
    The jars do exist at the location specified by the manifest.
    The application launches normally if I use "java -Jar OckCore.jar".
    The application doesn't launch from webstart.
    I've found that cache, but the jar files have been renamed.
    OckCore.jar is anOckCore.jar, etc... so I'm not sure if trying to write a cmdline will work anyway.

  • Issue with displaying images from bestseller.inc.jsp

    Hello all,
    I'm new in developing with NWDI and I'm having this small problem:
    in bestseller.inc.jsp (which includes productlist.jsp) there are two links with a product's code and a products description, which when clicked, navigate to productDetailsISA.jsp with the details of the product. While the images of all the products from other jsp's (for example from ProductsISA.jsp) display correctly in the ProductDetailsISA.jsp, there is a problem with the images of the products from bestseller and recommendations jsp's (they both include productlist jsp).
    The code for creating the links *in productlist.jsp is the following:
    <li> <a href="<isa:webappsURL name="b2b/productdetail.do"/><%=ShowProductDetailAction.createDetailRequest(product,displayScenario) %>">
                          <%=JspUtil.encodeHtml(product.getDescription()) %>
                        </a> </li>
    and the code for displaying products's images in ProductDetailsISA.jsp is this:
    <td width="7%" rowspan="2" headers="Product image">
                   <img src="<isa:imageAttribute guids="DOC_PC_CRM_IMAGE,DOC_P_CRM_IMAGE" name="webCatItem" defaultImg="mimes/shared/no_pic.gif"/>"   width="250"  height="250"/>
              </td>
    I have no idea how isa:imageAttribute tag works, so I was wandering if this problem is somehow connection with the inner workings of this tag.
    Could someone help please?
    Thank you very much in advance

    I think this is not the right forum to post your Question

  • Issue in loading images from Apache webserver in JSF image tags

    I am looking for a way to sever up images in my JSF App.
    I wish to allow members to upload jpg files (I worked this out) and display them later.
    I would like to store the uploaded jpgs in a dir outside of the war file...example c:\imagesUploaded
    Any help out there ???
    Thanks
    Phil

    Here is my problem.
    The first example I use the h:graphicImage to display a jpg from a url. Works Fine.
    <h:column>
    <f:facet name="header">
    <h:outputText value="" />
    </f:facet>
    <h:graphicImage url="http://www.me.com/test.JPG" height="75" width="75" />
    </h:column>
    Second example I use a gif in the images folder in a war file.
    <h:column>
    <f:facet name="header">
    <t:commandSortHeader columnName="distance" arrow="false" immediate="false">
    <f:facet name="ascending">
    <t:graphicImage value="images/ascending-arrow.gif" rendered="true" border="0"/>
    </f:facet>
    <f:facet name="descending">
    <t:graphicImage value="images/descending-arrow.gif" rendered="true" border="0"/>
    </f:facet>
    <h:outputText styleClass="dataTableCss" value="miles" />
    </t:commandSortHeader>
    </f:facet>
    </h:column>
    Third example. I would like to display images in a t:datatable.
    These images are located outside of the war file. Lets say c:\images.
    The location is stored in Oracle Table. Then location loaded in a bean.
    <h:column>
    <f:facet name="header">
    <h:outputText value="" />
    </f:facet>
    -- this does not work since you cant call out of war file....--
    <h:graphicImage value="c:\images\test.gif" height="75" width="75" />
    -- this is what I want to work with a bean holding location....--
    <h:graphicImage value="#{searchBean.gifLocation}" height="75" width="75" />
    </h:column>
    I have stored the name and address in an Oracle Table (test.gif = searchBean.gifLocation ).
    The question is how do I get the jpg or gif to display?
    Phil

Maybe you are looking for