KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > batik > svggen > AbstractImageHandlerEncoder


1 /*
2
3    Copyright 2001,2003 The Apache Software Foundation
4
5    Licensed under the Apache License, Version 2.0 (the "License");
6    you may not use this file except in compliance with the License.
7    You may obtain a copy of the License at
8
9        http://www.apache.org/licenses/LICENSE-2.0
10
11    Unless required by applicable law or agreed to in writing, software
12    distributed under the License is distributed on an "AS IS" BASIS,
13    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14    See the License for the specific language governing permissions and
15    limitations under the License.
16
17  */

18 package org.apache.batik.svggen;
19
20 import java.awt.Dimension JavaDoc;
21 import java.awt.Graphics2D JavaDoc;
22 import java.awt.Image JavaDoc;
23 import java.awt.geom.AffineTransform JavaDoc;
24 import java.awt.image.BufferedImage JavaDoc;
25 import java.awt.image.RenderedImage JavaDoc;
26 import java.awt.image.renderable.RenderableImage JavaDoc;
27 import java.io.File JavaDoc;
28 import java.lang.reflect.Method JavaDoc;
29 import java.net.MalformedURLException JavaDoc;
30
31 import org.w3c.dom.Element JavaDoc;
32
33 /**
34  * This abstract implementation of the ImageHandler interface
35  * is intended to be the base class for ImageHandlers that generate
36  * image files for all the images they handle. This class stores
37  * images in an configurable directory. The xlink:href value the
38  * class generates is made of a configurable url root and the name
39  * of the file created by this handler.
40  *
41  * @author <a HREF="mailto:vincent.hardy@eng.sun.com">Vincent Hardy</a>
42  * @version $Id: AbstractImageHandlerEncoder.java,v 1.17 2005/03/27 08:58:35 cam Exp $
43  * @see org.apache.batik.svggen.SVGGraphics2D
44  * @see org.apache.batik.svggen.ImageHandlerJPEGEncoder
45  * @see org.apache.batik.svggen.ImageHandlerPNGEncoder
46  */

47 public abstract class AbstractImageHandlerEncoder extends DefaultImageHandler {
48     private static final AffineTransform JavaDoc IDENTITY = new AffineTransform JavaDoc();
49
50     /**
51      * Directory where all images are placed
52      */

53     private String JavaDoc imageDir = "";
54
55     /**
56      * Value for the url root corresponding to the directory
57      */

58     private String JavaDoc urlRoot = "";
59
60     // for createGraphics method.
61
private static Method JavaDoc createGraphics = null;
62     private static boolean initDone = false;
63     private final static Class JavaDoc[] paramc = new Class JavaDoc[] {BufferedImage JavaDoc.class};
64     private static Object JavaDoc[] paramo = null;
65
66     /**
67      * This method creates a <code>Graphics2D</code> from a
68      * <code>BufferedImage</code>. If Batik extensions to AWT are
69      * in the CLASSPATH it uses them, otherwise, it uses the regular
70      * AWT method.
71      */

72     private static Graphics2D JavaDoc createGraphics(BufferedImage JavaDoc buf) {
73         if (!initDone) {
74             try {
75                 Class JavaDoc clazz = Class.forName("org.apache.batik.ext.awt.image.GraphicsUtil");
76                 createGraphics = clazz.getMethod("createGraphics", paramc);
77                 paramo = new Object JavaDoc[1];
78             } catch (ThreadDeath JavaDoc td) {
79                 throw td;
80             } catch (Throwable JavaDoc t) {
81                 // happen only if Batik extensions are not their
82
} finally {
83                 initDone = true;
84             }
85         }
86         if (createGraphics == null)
87             return buf.createGraphics();
88         else {
89             paramo[0] = buf;
90             Graphics2D JavaDoc g2d = null;
91             try {
92                 g2d = (Graphics2D JavaDoc)createGraphics.invoke(null, paramo);
93             } catch (Exception JavaDoc e) {
94                 // should not happened
95
}
96             return g2d;
97         }
98     }
99
100     /**
101      * @param imageDir directory where this handler should generate images.
102      * If null, an SVGGraphics2DRuntimeException is thrown.
103      * @param urlRoot root for the urls that point to images created by this
104      * image handler. If null, then the url corresponding to imageDir
105      * is used.
106      */

107     public AbstractImageHandlerEncoder(String JavaDoc imageDir, String JavaDoc urlRoot)
108         throws SVGGraphics2DIOException {
109         if (imageDir == null)
110             throw new SVGGraphics2DRuntimeException(ERR_IMAGE_DIR_NULL);
111
112         File JavaDoc imageDirFile = new File JavaDoc(imageDir);
113         if (!imageDirFile.exists())
114             throw new SVGGraphics2DRuntimeException(ERR_IMAGE_DIR_DOES_NOT_EXIST);
115
116         this.imageDir = imageDir;
117         if (urlRoot != null)
118             this.urlRoot = urlRoot;
119         else {
120             try{
121                 this.urlRoot = imageDirFile.toURL().toString();
122             } catch (MalformedURLException JavaDoc e) {
123                 throw new SVGGraphics2DIOException(ERR_CANNOT_USE_IMAGE_DIR+
124                                                    e.getMessage(),
125                                                    e);
126             }
127         }
128     }
129
130     /**
131      * This template method should set the xlink:href attribute on the input
132      * Element parameter
133      */

134     protected void handleHREF(Image JavaDoc image, Element JavaDoc imageElement,
135                               SVGGeneratorContext generatorContext)
136         throws SVGGraphics2DIOException {
137         // Create an buffered image where the image will be drawn
138
Dimension JavaDoc size = new Dimension JavaDoc(image.getWidth(null),
139                                        image.getHeight(null));
140         BufferedImage JavaDoc buf = buildBufferedImage(size);
141
142         Graphics2D JavaDoc g = createGraphics(buf);
143
144         g.drawImage(image, 0, 0, null);
145         g.dispose();
146
147         // Save image into file
148
saveBufferedImageToFile(imageElement, buf, generatorContext);
149     }
150
151     /**
152      * This template method should set the xlink:href attribute on the input
153      * Element parameter
154      */

155     protected void handleHREF(RenderedImage JavaDoc image, Element JavaDoc imageElement,
156                               SVGGeneratorContext generatorContext)
157         throws SVGGraphics2DIOException {
158         // Create an buffered image where the image will be drawn
159
Dimension JavaDoc size = new Dimension JavaDoc(image.getWidth(), image.getHeight());
160         BufferedImage JavaDoc buf = buildBufferedImage(size);
161
162         Graphics2D JavaDoc g = createGraphics(buf);
163
164         g.drawRenderedImage(image, IDENTITY);
165         g.dispose();
166
167         // Save image into file
168
saveBufferedImageToFile(imageElement, buf, generatorContext);
169     }
170
171     /**
172      * This template method should set the xlink:href attribute on the input
173      * Element parameter
174      */

175     protected void handleHREF(RenderableImage JavaDoc image, Element JavaDoc imageElement,
176                               SVGGeneratorContext generatorContext)
177         throws SVGGraphics2DIOException {
178         // Create an buffered image where the image will be drawn
179
Dimension JavaDoc size = new Dimension JavaDoc((int)Math.ceil(image.getWidth()),
180                                        (int)Math.ceil(image.getHeight()));
181         BufferedImage JavaDoc buf = buildBufferedImage(size);
182
183         Graphics2D JavaDoc g = createGraphics(buf);
184
185         g.drawRenderableImage(image, IDENTITY);
186         g.dispose();
187
188         // Save image into file
189
saveBufferedImageToFile(imageElement, buf, generatorContext);
190     }
191
192     private void saveBufferedImageToFile(Element JavaDoc imageElement,
193                                          BufferedImage JavaDoc buf,
194                                          SVGGeneratorContext generatorContext)
195         throws SVGGraphics2DIOException {
196         if (generatorContext == null)
197             throw new SVGGraphics2DRuntimeException(ERR_CONTEXT_NULL);
198
199         // Create a new file in image directory
200
File JavaDoc imageFile = null;
201
202         // While the files we are generating exist, try to create another
203
// id that is unique.
204
while (imageFile == null) {
205             String JavaDoc fileId = generatorContext.idGenerator.generateID(getPrefix());
206             imageFile = new File JavaDoc(imageDir, fileId + getSuffix());
207             if (imageFile.exists())
208                 imageFile = null;
209         }
210
211         // Encode image here
212
encodeImage(buf, imageFile);
213
214         // Update HREF
215
imageElement.setAttributeNS(XLINK_NAMESPACE_URI,
216                                     ATTR_XLINK_HREF, urlRoot + "/" +
217                                     imageFile.getName());
218     }
219
220     /**
221      * @return the suffix used by this encoder. E.g., ".jpg" for
222      * ImageHandlerJPEGEncoder
223      */

224     public abstract String JavaDoc getSuffix();
225
226     /**
227      * @return the prefix used by this encoder. E.g., "jpegImage" for
228      * ImageHandlerJPEGEncoder
229      */

230     public abstract String JavaDoc getPrefix();
231
232     /**
233      * Derived classes should implement this method and encode the input
234      * BufferedImage as needed
235      */

236     public abstract void encodeImage(BufferedImage JavaDoc buf, File JavaDoc imageFile)
237         throws SVGGraphics2DIOException;
238
239     /**
240      * This method creates a BufferedImage of the right size and type
241      * for the derived class.
242      */

243     public abstract BufferedImage JavaDoc buildBufferedImage(Dimension JavaDoc size);
244 }
245
Popular Tags