KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > oop > util > ImageExtractor


1 /*
2  * this source file is part of the JBOT - the business object framework for Java(tm)
3  * and can be used only in accordance with the terms of its license. Please read
4  * license details for more information.
5  *
6  * Copyright 1998 oop.com and Carlton D. Hewitt
7  *
8  * for more information, contact carl@oop.com
9  */

10
11  
12 /**
13   @Author Carl Hewitt
14   @Version 1.0
15   The image extractor is to encapsulate the getting of images from
16   ZIP/JAR files. The constructor must either have a zip or a jar
17   file name in it. This will enable image files to be distributed
18   in a compressed format and then extracted on the fly as nessasary
19
20   You will note a couple of things about this object.
21 <UL>
22   <LI>The object takes a constructor of either a URL or a JAR file.
23       This allows the utility to be used either in an applet over the
24       web or in an application.
25   <LI>It keeps a list of all of the input streams and does not destroy
26       them until the final version release of the application is done.
27       this is to save overhead of regetting the images. <I>Note: this object
28       object now also caches images that need to be accesed multiple times. The
29       default behavior is to cache them, but you can choose not to cache one
30       by calling the extract image method with a false parm</I>
31 </UL>
32 */

33
34 package com.oop.util;
35
36 import java.awt.*;
37 import java.util.*;
38 import java.util.zip.*;
39 import java.io.*;
40 import java.net.*;
41 import java.awt.image.*;
42 import com.sun.java.swing.*;
43
44 public class ImageExtractor {
45   final static Object JavaDoc nullObject = new Object JavaDoc();
46   final static private Hashtable images = new Hashtable();
47
48   /*
49     This is the index of the current URL/etc into the inputStreams
50   */

51   Object JavaDoc hashTableIndex;
52
53   /**
54     This is the constructor that works with a file name. This is
55     very similar to the constuctor (next) that works with a URL
56
57     The file is tested to see if it has the proper extension, and
58     then an input stream is created off of it. This is held open
59     so that the overhead of opening the file only has to be paid once.
60
61     added method to locate the images.jar file
62
63   */

64   public ImageExtractor(String JavaDoc zipFileName) {
65     if (!(zipFileName.toLowerCase().endsWith(".zip") ||
66          zipFileName.toLowerCase().endsWith(".jar"))) {
67       throw new RuntimeException JavaDoc("Invalid extension in image extractor");
68     }
69     File f = new File(zipFileName);
70     if (!f.exists()) {
71       System.out.println("Could not find the " + zipFileName + " file");
72       System.out.println(" please modify your jbot.properties file to locate this image file correctly.");
73       System.out.println(" This file is typically found in your current directory or specified by a -proploc ");
74       System.out.println(" parameter on the command line. ");
75       com.sun.java.swing.JFileChooser fc = new com.sun.java.swing.JFileChooser();
76       fc.setName("Find the image file : " + zipFileName);
77       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.");
78
79       if (fc.showOpenDialog(null) == -1) {
80         hashTableIndex = null;
81       } else {
82         File f1 = new File(fc.getSelectedFile().getAbsolutePath());
83         if (!f1.exists()) {
84           hashTableIndex = null;
85         } else {
86           hashTableIndex = fc.getSelectedFile().getAbsolutePath();
87         }
88         com.oop.fwork.Global.getFramework().addToProperties("0.image.category.path", hashTableIndex.toString());
89       }
90     } else
91       hashTableIndex = zipFileName;
92   }
93
94   /**
95     You can also locate the jar with the images in it at a URL. If this
96     is the case, this constructor would be the one that is called.
97    */

98   public ImageExtractor(URL zipFileURL) {
99     if (!(zipFileURL.getFile().toLowerCase().endsWith(".zip") ||
100          zipFileURL.getFile().toLowerCase().endsWith(".jar"))) {
101       throw new RuntimeException JavaDoc("Invalid extension in image extractor");
102     }
103     hashTableIndex = zipFileURL;
104   }
105
106   /**
107     Return an image icon (as used by swing controls)
108    */

109   public ImageIcon extractImageIcon(String JavaDoc ImageName) {
110     return extractImageIcon(ImageName, true);
111   }
112
113   /**
114     Extracts an image icon and creates a disabled image of it
115     and returns it.
116    */

117   public ImageIcon extractDisabledImageIcon(String JavaDoc IconName) {
118     Image i = null;
119     try {
120       i = extractImage(IconName);
121     } catch (Exception JavaDoc e) {
122       return null;
123     }
124     if (i == null) {
125       return null;
126     } else {
127       return new ImageIcon(com.sun.java.swing.GrayFilter.createDisabledImage(i));
128     }
129   }
130
131   /**
132     Returns an image icon and optionally excludes it from the ImageCache (allows
133     access to the image without reading it in from the file.
134    */

135   public ImageIcon extractImageIcon(String JavaDoc ImageName, boolean cache) {
136     Image i = extractImage(ImageName, cache);
137     if (i == null) {
138       return null;
139     } else {
140       return new ImageIcon(i);
141     }
142   }
143
144
145   /**
146     Returns an image from the image library.
147    */

148   public Image extractImage(String JavaDoc ImageName) {
149     return extractImage(ImageName, true);
150   }
151
152   /**
153    This is the method of this object that does all of the work. This
154    method is responsible for extracting the image from the JAR file,
155    converting it to image file etc.
156
157    This method also creates the input stream if this is the first time that it is
158    called.
159
160    This method first checks to see if the image is still in the cache.
161    If not, it reads it in from the image library and may put it in the cache. If
162    it is unable to find it, it will put a holder in the cache to allow
163    you not have to look up the image every time that it is used.
164    */

165   public Image extractImage(String JavaDoc ImageName, boolean cache) {
166     // this should only happen when the file is not found for
167
// the hash table
168
if (hashTableIndex == null)
169       return null;
170
171     try {
172       // see if this image has already been retieved
173
// if so just return it
174
if (images.containsKey(hashTableIndex.toString() + ImageName)) {
175         Object JavaDoc o = images.get(hashTableIndex.toString() + ImageName);
176         if (o == nullObject)
177           return null;
178         else
179           return (Image)o;
180       }
181
182       InputStream inputStream = null;
183       if (hashTableIndex instanceof String JavaDoc) {
184         inputStream = new FileInputStream((String JavaDoc)hashTableIndex);
185       } else if (hashTableIndex instanceof URL) {
186         URL u = (URL)hashTableIndex;
187         inputStream = u.openStream();
188       }
189
190       // The input stream is first put into the hash table so that it does
191
// not have to be opened each time an image is requested.
192
if (inputStream == null) throw new Exception JavaDoc("No image archive file/url was specified");
193
194       // create a zip entry stream
195
ZipInputStream zstream = new ZipInputStream(inputStream);
196       ZipEntry ze = null;
197       while (true) {
198         // find the proper zip image
199
if (ze != null) {
200           ze = null;
201           zstream.closeEntry();
202         }
203         ze = zstream.getNextEntry();
204         if (ze == null) {
205           // did not find the requested file, break here
206
break;
207         } else if ( ze.getName().toUpperCase().equals(ImageName.toUpperCase())) {
208           break;
209         }
210       }
211
212       // if it did not find the proper image throw an exception
213
if (ze == null) {
214         images.put(hashTableIndex.toString() + ImageName, nullObject);
215         return null;
216       }
217
218       // create an output stream
219
ByteArrayOutputStream baos = new ByteArrayOutputStream();
220
221       byte buffer[] = new byte[1024];
222
223       // fill the output stream from the zip entry
224
while (true) {
225         int nRead = zstream.read(buffer, 0, buffer.length);
226         if (nRead <= 0) {
227           break;
228         }
229         baos.write(buffer, 0, nRead);
230       }
231
232     // close the zip entry and the input stream.
233
// there is a possible problem here where the zip stream
234
// may not need to be closed because it cannot be reentered . . .
235
zstream.closeEntry();
236     inputStream.close();
237
238     // create an image from the output stream.
239
Image output =
240       Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
241
242     // close the output stream
243
baos.close();
244
245     if (cache)
246       images.put(hashTableIndex.toString() + ImageName, output);
247     // return the image
248
return output;
249     } catch (Exception JavaDoc e) {
250       e.printStackTrace();
251       return null;
252     }
253   }
254
255 }
256
Popular Tags