KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > batik > transcoder > image > AbstractImageTranscoderTest


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.transcoder.image;
19
20 import java.awt.image.BufferedImage JavaDoc;
21 import java.awt.image.RenderedImage JavaDoc;
22
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.ByteArrayInputStream JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.io.PrintWriter JavaDoc;
30 import java.io.StringWriter JavaDoc;
31
32 import java.net.MalformedURLException JavaDoc;
33 import java.net.URL JavaDoc;
34
35 import java.util.Map JavaDoc;
36
37 import org.apache.batik.ext.awt.image.spi.ImageTagRegistry;
38 import org.apache.batik.ext.awt.image.renderable.Filter;
39
40 import org.apache.batik.ext.awt.image.codec.PNGImageEncoder;
41 import org.apache.batik.ext.awt.image.codec.PNGEncodeParam;
42
43 import org.apache.batik.transcoder.TranscoderException;
44 import org.apache.batik.transcoder.TranscoderInput;
45 import org.apache.batik.transcoder.TranscoderOutput;
46
47 import org.apache.batik.transcoder.image.ImageTranscoder;
48 import org.apache.batik.transcoder.image.PNGTranscoder;
49
50 import org.apache.batik.test.AbstractTest;
51 import org.apache.batik.test.DefaultTestReport;
52 import org.apache.batik.test.TestReport;
53 import org.apache.batik.test.svg.SVGRenderingAccuracyTest;
54
55 /**
56  * The base class for the ImageTranscoder tests.
57  *
58  * @author <a HREF="mailto:Thierry.Kormann@sophia.inria.fr">Thierry Kormann</a>
59  * @version $Id: AbstractImageTranscoderTest.java,v 1.7 2004/08/18 07:17:12 vhardy Exp $
60  */

61 public abstract class AbstractImageTranscoderTest extends AbstractTest {
62
63     /**
64      * Error when the reference image and the generated image is different.
65      */

66     public static final String JavaDoc ERROR_IMAGE_DIFFER =
67     "AbstractImageTranscoderTest.error.image.differ";
68
69     /**
70      * Tag for difference image URI.
71      */

72     public static final String JavaDoc DIFFERENCE_IMAGE =
73     "AbstractImageTranscoderTest.error.difference.image";
74
75     /**
76      * Error when an exception occured while transcoding.
77      */

78     public static final String JavaDoc ERROR_TRANSCODING =
79     "AbstractImageTranscoderTest.error.transcoder.exception";
80
81     /**
82      * Constructs a new <tt>AbstractImageTranscoderTest</tt>.
83      */

84     public AbstractImageTranscoderTest() {
85     }
86
87     /**
88      * Resolves the input string as follows.
89      * + First, the string is interpreted as a file description.
90      * If the file exists, then the file name is turned into
91      * a URL.
92      * + Otherwise, the string is supposed to be a URL. If it
93      * is an invalid URL, an IllegalArgumentException is thrown.
94      */

95     protected URL JavaDoc resolveURL(String JavaDoc url){
96         // Is url a file?
97
File JavaDoc f = (new File JavaDoc(url)).getAbsoluteFile();
98         if(f.getParentFile().exists()){
99             try{
100                 return f.toURL();
101             }catch(MalformedURLException JavaDoc e){
102                 throw new IllegalArgumentException JavaDoc();
103             }
104         }
105         
106         // url is not a file. It must be a regular URL...
107
try{
108             return new URL JavaDoc(url);
109         }catch(MalformedURLException JavaDoc e){
110             throw new IllegalArgumentException JavaDoc(url);
111         }
112     }
113
114     DefaultTestReport report;
115     /**
116      * Runs this test. This method will only throw exceptions if some aspect of
117      * the test's internal operation fails.
118      */

119     public TestReport runImpl() throws Exception JavaDoc {
120     report = new DefaultTestReport(this);
121
122     try {
123         DiffImageTranscoder transcoder =
124         new DiffImageTranscoder(getReferenceImageData());
125
126         Map JavaDoc hints = createTranscodingHints();
127         if (hints != null) {
128         transcoder.setTranscodingHints(hints);
129         }
130
131         TranscoderInput input = createTranscoderInput();
132         transcoder.transcode(input, null);
133     } catch (Exception JavaDoc ex) {
134         report.setErrorCode(ERROR_TRANSCODING);
135         report.addDescriptionEntry(ERROR_TRANSCODING, toString(ex));
136             ex.printStackTrace();
137         report.setPassed(false);
138     }
139     
140     return report;
141     }
142
143     /**
144      * Creates the <tt>TranscoderInput</tt>.
145      */

146     protected abstract TranscoderInput createTranscoderInput();
147
148     /**
149      * Creates a Map that contains additional transcoding hints.
150      */

151     protected Map JavaDoc createTranscodingHints() {
152     return null;
153     }
154
155     /**
156      * Returns the reference image for this test.
157      */

158     protected abstract byte [] getReferenceImageData();
159
160     //////////////////////////////////////////////////////////////////////////
161
// Convenient methods
162
//////////////////////////////////////////////////////////////////////////
163

164     /**
165      * Gives the specified exception as a string.
166      */

167     public static String JavaDoc toString(Exception JavaDoc ex) {
168     StringWriter JavaDoc trace = new StringWriter JavaDoc();
169     ex.printStackTrace(new PrintWriter JavaDoc(trace));
170     return trace.toString();
171     }
172
173     static String JavaDoc filename;
174
175     /**
176      * Loads an image from a URL
177      */

178     public static byte [] createBufferedImageData(URL JavaDoc url) {
179         try {
180             filename = url.toString();
181             //System.out.println(url.toString());
182
InputStream JavaDoc istream = url.openStream();
183             byte [] imgData = null;
184             byte [] buf = new byte[1024];
185             int length;
186             while ((length = istream.read(buf, 0, buf.length)) == buf.length) {
187                 if (imgData != null) {
188                     byte [] imgDataTmp = new byte[imgData.length + length];
189                     System.arraycopy
190                         (imgData, 0, imgDataTmp, 0, imgData.length);
191                     System.arraycopy
192                         (buf, 0, imgDataTmp, imgData.length, length);
193                     imgData = imgDataTmp;
194                 } else {
195                     imgData = new byte[length];
196                     System.arraycopy(buf, 0, imgData, 0, length);
197                 }
198             }
199             if (imgData != null) {
200                 byte [] imgDataTmp = new byte[imgData.length + length];
201                 System.arraycopy
202                     (imgData, 0, imgDataTmp, 0, imgData.length);
203                 System.arraycopy
204                     (buf, 0, imgDataTmp, imgData.length, length);
205                 imgData = imgDataTmp;
206             } else {
207                 imgData = new byte[length];
208                 System.arraycopy(buf, 0, imgData, 0, length);
209             }
210             istream.close();
211             return imgData;
212         } catch (IOException JavaDoc ex) {
213             return null;
214         }
215     }
216
217     /**
218      * A custom ImageTranscoder for testing.
219      */

220     protected class DiffImageTranscoder extends ImageTranscoder {
221
222     /** The result of the image comparaison. */
223     protected boolean state;
224
225     /** The reference image. */
226     protected byte [] refImgData;
227
228     /**
229      * Constructs a new <tt>DiffImageTranscoder</tt>.
230      *
231      * @param refImg the reference image
232      * @param report the test report into which errors have been sent
233      */

234     public DiffImageTranscoder(byte [] refImgData) {
235         this.refImgData = refImgData;
236     }
237
238     /**
239      * Creates a new image with the specified dimension.
240      * @param w the image width in pixels
241      * @param h the image height in pixels
242      */

243     public BufferedImage JavaDoc createImage(int w, int h) {
244         return new BufferedImage JavaDoc(w, h, BufferedImage.TYPE_INT_ARGB);
245     }
246
247     /**
248      * Compares the specified image with the reference image and set the
249      * state flag.
250      *
251      * @param img the image to write
252      * @param output the output (ignored)
253      * @param TranscoderException if an error occured while storing the
254      * image
255      */

256     public void writeImage(BufferedImage JavaDoc img, TranscoderOutput output)
257         throws TranscoderException {
258
259         compareImage(img);
260     }
261
262         protected void writeCandidateReference(byte [] imgData) {
263             try {
264                 String JavaDoc s = new File JavaDoc(filename).getName();
265                 s = "test-references/org/apache/batik/transcoder/image/candidate-reference/"+s;
266                 System.out.println(s);
267                 FileOutputStream JavaDoc ostream = new FileOutputStream JavaDoc(s);
268                 ostream.write(imgData, 0, imgData.length);
269                 ostream.flush();
270                 ostream.close();
271             } catch (Exception JavaDoc ex) { }
272             return;
273         }
274
275         protected void writeCandidateVariation(byte [] imgData, byte [] refData)
276         {
277             writeCandidateReference(imgData);
278             try {
279                 BufferedImage JavaDoc ref = getImage(new ByteArrayInputStream JavaDoc(refData));
280                 BufferedImage JavaDoc img = getImage(new ByteArrayInputStream JavaDoc(imgData));
281                 BufferedImage JavaDoc diff =
282                     SVGRenderingAccuracyTest.buildDiffImage(ref, img);
283                 String JavaDoc s = new File JavaDoc(filename).getName();
284                 s = ("test-references/org/apache/batik/transcoder/image/"+
285                      "candidate-variation/"+s);
286                 PNGImageEncoder encoder
287                     = new PNGImageEncoder
288                     (new FileOutputStream JavaDoc(s),
289                      PNGEncodeParam.getDefaultEncodeParam(diff));
290                 encoder.encode(diff);
291                 report.addDescriptionEntry(DIFFERENCE_IMAGE,new File JavaDoc(s));
292             } catch (Exception JavaDoc e) { }
293         }
294
295     /**
296      * Compares both source and result images and set the state flag.
297      */

298     protected void compareImage(BufferedImage JavaDoc img)
299             throws TranscoderException {
300         // compare the resulting image with the reference image
301
// state = true if refImg is the same than img
302

303             ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
304             TranscoderOutput output = new TranscoderOutput(out);
305             PNGTranscoder t = new PNGTranscoder();
306             t.writeImage(img, output);
307             byte [] imgData = out.toByteArray();
308
309             if (refImgData == null) {
310                 report.setErrorCode(ERROR_IMAGE_DIFFER);
311                 report.addDescriptionEntry(ERROR_IMAGE_DIFFER, "");
312                 report.setPassed(false);
313                 writeCandidateReference(imgData);
314                 state = false;
315                 return;
316             }
317             
318             if (refImgData.length != imgData.length) {
319                 report.setErrorCode(ERROR_IMAGE_DIFFER);
320                 report.addDescriptionEntry(ERROR_IMAGE_DIFFER, "");
321                 report.setPassed(false);
322                 writeCandidateVariation(imgData, refImgData);
323                 return;
324             }
325
326             for (int i = 0; i < refImgData.length; ++i) {
327                 if (refImgData[i] != imgData[i]) {
328                     report.setErrorCode(ERROR_IMAGE_DIFFER);
329                     report.addDescriptionEntry(ERROR_IMAGE_DIFFER, "");
330                     report.setPassed(false);
331                     writeCandidateVariation(imgData, refImgData);
332                     return;
333                 }
334             }
335             
336         state = true;
337     }
338
339     /**
340      * Returns true if the reference image is the same than the generated
341      * image, false otherwise.
342      */

343     public boolean isIdentical() {
344         return state;
345     }
346     }
347
348     protected BufferedImage JavaDoc getImage(InputStream JavaDoc is)
349         throws IOException JavaDoc {
350         ImageTagRegistry reg = ImageTagRegistry.getRegistry();
351         Filter filt = reg.readStream(is);
352         if(filt == null)
353             throw new IOException JavaDoc("Couldn't read Stream");
354
355         RenderedImage JavaDoc red = filt.createDefaultRendering();
356         if(red == null)
357             throw new IOException JavaDoc("Couldn't render Stream");
358         
359         BufferedImage JavaDoc img = new BufferedImage JavaDoc(red.getWidth(),
360                                               red.getHeight(),
361                                               BufferedImage.TYPE_INT_ARGB);
362         red.copyData(img.getRaster());
363         return img;
364     }
365 }
366
Popular Tags