Here is a little class that I wrote that might be helpful . . . enjoy.

Carl

[EMAIL PROTECTED] wrote:

I wrote:

> What is the meaning of url.toExportedForm() from image contained in JAR
> called something like this?
>
> systemresources://FILE1/+/images/new.gif
>
> I had a lot of trouble reading image file (GIFs) from JARs.

I had a long look at the FAQ (www.afu.com) and applied the getResourceAsStream()
example there.

This normally results in stack trace, which I forget to add in the last post:

java.lang.NullPointerException:
        at java.util.Hashtable.get(Hashtable.java)
        at sun.awt.SunToolkit.getImageFromHash(SunToolkit.java:117)
        at sun.awt.SunToolkit.getImage(SunToolkit.java:129)
        at com.sun.java.swing.ImageIcon.<init>(ImageIcon.java:64)
        at com.sun.java.swing.ImageIcon.<init>(ImageIcon.java:83)
        at xenon.jsql.editor.JsqlEdit.<init>(JsqlEdit.java:173)
        at xenon.jsql.editor.JsqlEditList.createNewFrame(JsqlEditList.java:101)
        at xenon.jsql.editor.Jsql.<init>(Jsql.java:144)
        at xenon.jsql.editor.Jsql.main(Jsql.java:592)

Here is some code:

    /** retrieves the image (GIF/JPEG) data from URL.
     * implements performs URL.
     */
    protected byte[] getImageData( String url_image )
    {
    byte[] imageBytes=null;
    if (debug) System.out.println( "getImageData("+url_image+")" );

    //
    // First try reading the resource as a system file.
    //
    InputStream imageStream=null;        // Reset this
    try {
        imageStream = new FileInputStream( url_image );
    }
    catch ( FileNotFoundException fe ) { ; }

    if (imageStream == null) {
        //
        // Well that didn't work
        // Second, Try to opening the resource as an URL specification.
        //
        try {
        URL url = new URL( url_image );
        // Try creating a socket which connects to the
        // int port = (url.getPort() == -1) ? 80: url.getPort();
        // Socket s = new Socket( url.getHost, port );
        imageStream = url.openStream();
        if (debug) System.out.println("*opening stream URL*");
        }
        catch (IOException ioe ) { ; }
    }

    if (imageStream == null)
        //
        // Well that also didn't work
        //
        // Third, Try to opening the resource as as CLASSPATH specification.
        // e.g. It may be part of JAR or ZIP
        imageStream = getClass().getClassLoader().getSystemResourceAsStream(url_image);
    Image img = null;
    try {
        if (debug)
        System.out.println("imageStream:" +
                   ((imageStream==null) ?"NULL!!":"EXISTS") );
        imageBytes = new byte[imageStream.available()];
        imageStream.read(imageBytes);
    }
    catch (IOException ex) {
        System.err.println( getClass().getName()+".getImageData: failed to load image from URL: " + url_image );
    }

    if (imageBytes != null)
        System.out.println( "imageBytes.length =" + imageBytes.length );

    return (imageBytes);
    }
 

Solution?

BTW: linux-jdk1.1.6-libc5 .tar.gz   swing-1.1beta.zip

Cheers

Peter

--
import java.std.disclaimer.*;           // "Dontcha just love the API, baby bop!"
Peter Pilgrim      Dept:OTC Derivatives IT,
Deutsche Bank (UK) Ltd, Groundfloor 133 Houndsditch, London, EC3A 7DX
Tel: +44-545-8000  Direct: +44 (0)171-545-9977  Fax: 0171-545-4313
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

 
-- 
* -----------------------
Carl Hewitt
CTO / oop.com
Tools and training for enterprise 
business object development
* -----------------------
JBOT - business object toolkit for Java
www.oop.com
* -----------------------
 
/*
 * this source file is part of the JBOT - the business object framework for Java(tm)
 * and can be used only in accordance with the terms of its license.  Please read
 * license details for more information.
 *
 * Copyright 1998 oop.com and Carlton D. Hewitt
 *
 * for more information, contact [EMAIL PROTECTED]
 */

 
/**
  @Author Carl Hewitt
  @Version 1.0
  The image extractor is to encapsulate the getting of images from
  ZIP/JAR files.  The constructor must either have a zip or a jar
  file name in it.  This will enable image files to be distributed
  in a compressed format and then extracted on the fly as nessasary

  You will note a couple of things about this object.
<UL>
  <LI>The object takes a constructor of either a URL or a JAR file.
      This allows the utility to be used either in an applet over the
      web or in an application.
  <LI>It keeps a list of all of the input streams and does not destroy
      them until the final version release of the application is done.
      this is to save overhead of regetting the images. <I>Note: this object
      object now also caches images that need to be accesed multiple times.  The
      default behavior is to cache them, but you can choose not to cache one
      by calling the extract image method with a false parm</I>
</UL>
*/

package com.oop.util;

import java.awt.*;
import java.util.*;
import java.util.zip.*;
import java.io.*;
import java.net.*;
import java.awt.image.*;
import com.sun.java.swing.*;

public class ImageExtractor {
  final static Object nullObject = new Object();
  final static private Hashtable images = new Hashtable();

  /*
    This is the index of the current URL/etc into the inputStreams
  */
  Object hashTableIndex;

  /**
    This is the constructor that works with a file name.  This is
    very similar to the constuctor (next) that works with a URL

    The file is tested to see if it has the proper extension, and
    then an input stream is created off of it.  This is held open
    so that the overhead of opening the file only has to be paid once.

    added method to locate the images.jar file

  */
  public ImageExtractor(String zipFileName) {
    if (!(zipFileName.toLowerCase().endsWith(".zip") ||
         zipFileName.toLowerCase().endsWith(".jar"))) {
      throw new RuntimeException("Invalid extension in image extractor");
    }
    File f = new File(zipFileName);
    if (!f.exists()) {
      System.out.println("Could not find the " + zipFileName + " file");
      System.out.println("  please modify your jbot.properties file to locate this 
image file correctly.");
      System.out.println("  This file is typically found in your current directory or 
specified by a -proploc ");
      System.out.println("  parameter on the command line. ");
      com.sun.java.swing.JFileChooser fc = new com.sun.java.swing.JFileChooser();
      fc.setName("Find the image file : " + zipFileName);
      Msg.getInstance().MBox("Could not find image library, please choose\r\n choosing 
a file here will update your properties (jbot.properties) \r\n to reflect the current 
images.jar file.\r\nThis file is typically found (during development) in the <jbot 
home>/images/ directory.");

      if (fc.showOpenDialog(null) == -1) {
        hashTableIndex = null;
      } else {
        File f1 = new File(fc.getSelectedFile().getAbsolutePath());
        if (!f1.exists()) {
          hashTableIndex = null;
        } else {
          hashTableIndex = fc.getSelectedFile().getAbsolutePath();
        }
        com.oop.fwork.Global.getFramework().addToProperties("0.image.category.path", 
hashTableIndex.toString());
      }
    } else
      hashTableIndex = zipFileName;
  }

  /**
    You can also locate the jar with the images in it at a URL.  If this
    is the case, this constructor would be the one that is called.
   */
  public ImageExtractor(URL zipFileURL) {
    if (!(zipFileURL.getFile().toLowerCase().endsWith(".zip") ||
         zipFileURL.getFile().toLowerCase().endsWith(".jar"))) {
      throw new RuntimeException("Invalid extension in image extractor");
    }
    hashTableIndex = zipFileURL;
  }

  /**
    Return an image icon (as used by swing controls)
   */
  public ImageIcon extractImageIcon(String ImageName) {
    return extractImageIcon(ImageName, true);
  }

  /**
    Extracts an image icon and creates a disabled image of it
    and returns it.
   */
  public ImageIcon extractDisabledImageIcon(String IconName) {
    Image i = null;
    try {
      i = extractImage(IconName);
    } catch (Exception e) {
      return null;
    }
    if (i == null) {
      return null;
    } else {
      return new ImageIcon(com.sun.java.swing.GrayFilter.createDisabledImage(i));
    }
  }

  /**
    Returns an image icon and optionally excludes it from the ImageCache (allows
    access to the image without reading it in from the file.
   */
  public ImageIcon extractImageIcon(String ImageName, boolean cache) {
    Image i = extractImage(ImageName, cache);
    if (i == null) {
      return null;
    } else {
      return new ImageIcon(i);
    }
  }


  /**
    Returns an image from the image library.
   */
  public Image extractImage(String ImageName) {
    return extractImage(ImageName, true);
  }

  /**
   This is the method of this object that does all of the work.  This
   method is responsible for extracting the image from the JAR file,
   converting it to image file etc.

   This method also creates the input stream if this is the first time that it is
   called.

   This method first checks to see if the image is still in the cache.
   If not, it reads it in from the image library and may put it in the cache.  If
   it is unable to find it, it will put a holder in the cache to allow
   you not have to look up the image every time that it is used.
   */
  public Image extractImage(String ImageName, boolean cache) {
    // this should only happen when the file is not found for
    // the hash table
    if (hashTableIndex == null)
      return null;

    try {
      // see if this image has already been retieved
      // if so just return it
      if (images.containsKey(hashTableIndex.toString() + ImageName)) {
        Object o = images.get(hashTableIndex.toString() + ImageName);
        if (o == nullObject)
          return null;
        else
          return (Image)o;
      }

      InputStream inputStream = null;
      if (hashTableIndex instanceof String) {
        inputStream = new FileInputStream((String)hashTableIndex);
      } else if (hashTableIndex instanceof URL) {
        URL u = (URL)hashTableIndex;
        inputStream = u.openStream();
      }

      // The input stream is first put into the hash table so that it does
      // not have to be opened each time an image is requested.
      if (inputStream == null) throw new Exception("No image archive file/url was 
specified");

      // create a zip entry stream
      ZipInputStream zstream = new ZipInputStream(inputStream);
      ZipEntry ze = null;
      while (true) {
        // find the proper zip image
        if (ze != null) {
          ze = null;
          zstream.closeEntry();
        }
        ze = zstream.getNextEntry();
        if (ze == null) {
          // did not find the requested file, break here
          break;
        } else if ( ze.getName().toUpperCase().equals(ImageName.toUpperCase())) {
          break;
        }
      }

      // if it did not find the proper image throw an exception
      if (ze == null) {
        images.put(hashTableIndex.toString() + ImageName, nullObject);
        return null;
      }

      // create an output stream
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      byte buffer[] = new byte[1024];

      // fill the output stream from the zip entry
      while (true) {
        int nRead = zstream.read(buffer, 0, buffer.length);
        if (nRead <= 0) {
          break;
        }
        baos.write(buffer, 0, nRead);
      }

    // close the zip entry and the input stream.
    // there is a possible problem here where the zip stream
    // may not need to be closed because it cannot be reentered . . .
    zstream.closeEntry();
    inputStream.close();

    // create an image from the output stream.
    Image output =
      Toolkit.getDefaultToolkit().createImage(baos.toByteArray());

    // close the output stream
    baos.close();

    if (cache)
      images.put(hashTableIndex.toString() + ImageName, output);
    // return the image
    return output;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

}
begin:          vcard
fn:             Carl  Hewitt
n:              Hewitt;Carl 
org:            oop.com
email;internet: [EMAIL PROTECTED]
title:          CTO
tel;work:       877-891-5846
note;quoted-printable:=0D=0A=
	
x-mozilla-cpt:  ;0
x-mozilla-html: TRUE
version:        2.1
end:            vcard

Reply via email to