KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > batik > test > svg > AbstractRenderingAccuracyTest


1 /*
2
3    Copyright 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.test.svg;
19
20 import java.io.BufferedInputStream JavaDoc;
21 import java.io.File JavaDoc;
22 import java.io.FileInputStream JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.io.StringWriter JavaDoc;
29
30 import java.net.URL JavaDoc;
31 import java.net.MalformedURLException JavaDoc;
32
33 import java.util.Locale JavaDoc;
34 import java.util.ResourceBundle JavaDoc;
35
36 import java.awt.Color JavaDoc;
37 import java.awt.Graphics2D JavaDoc;
38 import java.awt.image.BufferedImage JavaDoc;
39 import java.awt.image.RenderedImage JavaDoc;
40 import java.awt.image.WritableRaster JavaDoc;
41 import java.awt.image.ColorModel JavaDoc;
42
43 import org.apache.batik.ext.awt.image.GraphicsUtil;
44
45 import org.apache.batik.ext.awt.image.spi.ImageTagRegistry;
46 import org.apache.batik.ext.awt.image.renderable.Filter;
47
48 import org.apache.batik.ext.awt.image.codec.PNGImageEncoder;
49 import org.apache.batik.ext.awt.image.codec.PNGEncodeParam;
50
51 import org.apache.batik.util.ParsedURL;
52
53 import org.apache.batik.test.AbstractTest;
54 import org.apache.batik.test.DefaultTestReport;
55 import org.apache.batik.test.TestReport;
56
57 /**
58  * Checks for regressions in rendering a specific SVG document.
59  * The <tt>Test</tt> will rasterize and SVG document and
60  * compare it to a reference image. The test passes if the
61  * rasterized SVG and the reference image match exactly (i.e.,
62  * all pixel values are the same).
63  *
64  * @author <a HREF="mailto:vhardy@apache.lorg">Vincent Hardy</a>
65  * @version $Id: AbstractRenderingAccuracyTest.java,v 1.5 2004/08/18 07:17:01 vhardy Exp $
66  */

67 public abstract class AbstractRenderingAccuracyTest extends AbstractTest {
68     /**
69      * Error when temp file cannot be created
70      * {0} = IOException message
71      */

72     public static final String JavaDoc ERROR_CANNOT_CREATE_TEMP_FILE
73         = "SVGRenderingAccuracyTest.error.cannot.create.temp.file";
74
75     /**
76      * Error when temp file stream cannot be created
77      * {0} = temp file's cannonical path
78      * {1} = IOException message
79      */

80     public static final String JavaDoc ERROR_CANNOT_CREATE_TEMP_FILE_STREAM
81         = "SVGRenderingAccuracyTest.error.cannot.create.temp.file.stream";
82
83     /**
84      * Error when the reference image cannot be opened
85      * {0} = URI of the reference image
86      * {1} = IOException message
87      */

88     public static final String JavaDoc ERROR_CANNOT_OPEN_REFERENCE_IMAGE
89         = "SVGRenderingAccuracyTest.error.cannot.open.reference.image";
90
91     /**
92      * Error when the generated image cannot be read
93      * {0} = Cannonical path of the temp generated image
94      * {1} = IOException message
95      */

96     public static final String JavaDoc ERROR_CANNOT_OPEN_GENERATED_IMAGE
97         = "SVGRenderingAccuracyTest.error.cannot.open.genereted.image";
98
99     /**
100      * Error when there is an IOException while comparing the
101      * two reference raster image with the new raster image built
102      * from the SVG.
103      * {0} = URI of the reference image
104      * {1} = Connical path for the temp generated image
105      * {2} = IOException message.
106      */

107     public static final String JavaDoc ERROR_ERROR_WHILE_COMPARING_FILES
108         = "SVGRenderingAccuracyTest.error.while.comparing.files";
109
110     /**
111      * Error when the generated image from the SVG file differs from
112      * the reference image.
113      */

114     public static final String JavaDoc ERROR_SVG_RENDERING_NOT_ACCURATE
115         = "SVGRenderingAccuracyTest.error.svg.rendering.not.accurate";
116
117     /**
118      * Entry describing the error
119      */

120     public static final String JavaDoc ENTRY_KEY_ERROR_DESCRIPTION
121         = "SVGRenderingAccuracyTest.entry.key.error.description";
122
123     /**
124      * Entry describing the reference/generated image file
125      */

126     public static final String JavaDoc ENTRY_KEY_REFERENCE_GENERATED_IMAGE_URI
127         = "SVGRenderingAccuracyTest.entry.key.reference.generated.image.file";
128
129     /**
130      * Entry describing the generated difference image
131      */

132     public static final String JavaDoc ENTRY_KEY_DIFFERENCE_IMAGE
133         = "SVGRenderingAccuracyTest.entry.key.difference.image";
134
135     /**
136      * Entry describing that an internal error occured while
137      * generating the test failure description
138      */

139     public static final String JavaDoc ENTRY_KEY_INTERNAL_ERROR
140         = "SVGRenderingAccuracyTest.entry.key.internal.error";
141
142     /**
143      * Messages expressing that comparison images could not be
144      * created:
145      * {0} : exception class
146      * {1} : exception message
147      * {2} : exception stack trace.
148      */

149     public static final String JavaDoc COULD_NOT_GENERATE_COMPARISON_IMAGES
150         = "SVGRenderingAccuracyTest.message.error.could.not.generate.comparison.images";
151
152     /**
153      * Messages expressing that an image could not be loaded.
154      * {0} : URL for the reference image.
155      */

156     public static final String JavaDoc COULD_NOT_LOAD_IMAGE
157         = "SVGRenderingAccuracyTest.message.error.could.not.load.image";
158
159     /**
160      * Message expressing that the variation URL could not be open
161      * {0} : URL
162      */

163     public static final String JavaDoc COULD_NOT_OPEN_VARIATION_URL
164         = "SVGRenderingAccuracyTest.message.warning.could.not.open.variation.url";
165
166     /**
167      * The gui resources file name
168      */

169     public final static String JavaDoc CONFIGURATION_RESOURCES =
170         "org.apache.batik.test.svg.resources.Configuration";
171
172     /**
173      * Suffix used for comparison images
174      */

175     public final static String JavaDoc IMAGE_TYPE_COMPARISON = "_cmp";
176
177     /**
178      * Suffix used for diff images
179      */

180     public final static String JavaDoc IMAGE_TYPE_DIFF = "_diff";
181
182     /**
183      * Suffix used for saved images (e.g., comparison and diff images)
184      */

185     public final static String JavaDoc IMAGE_FILE_EXTENSION = ".png";
186
187     /**
188      * The configuration resource bundle
189      */

190     protected static ResourceBundle JavaDoc configuration;
191     static {
192         configuration = ResourceBundle.getBundle(CONFIGURATION_RESOURCES,
193                                                  Locale.getDefault());
194     }
195
196     /**
197      * Prefix for the temporary files created by Tests
198      * of this class
199      */

200     public static final String JavaDoc TEMP_FILE_PREFIX
201         = configuration.getString("temp.file.prefix");
202
203     /**
204      * Suffix for the temporary files created by
205      * Tests of this class
206      */

207     public static final String JavaDoc TEMP_FILE_SUFFIX
208         = configuration.getString("temp.file.suffix");
209
210     /**
211      * The URL where the SVG can be found.
212      */

213     protected URL JavaDoc svgURL;
214
215     /**
216      * The URL for the reference image
217      */

218     protected URL JavaDoc refImgURL;
219
220     /**
221      * The URL of a file containing an 'accepted'
222      * variation from the reference image.
223      */

224     protected URL JavaDoc variationURL;
225
226     /**
227      * The File where the newly computed variation
228      * should be saved if different from the
229      * variationURL
230      */

231     protected File JavaDoc saveVariation;
232
233     /**
234      * The File where the candidate reference
235      * should be saved if there is not candidate reference
236      * or if it cannot be opened.
237      */

238     protected File JavaDoc candidateReference;
239
240     /**
241      * Temporary directory
242      */

243     protected static File JavaDoc tempDirectory;
244
245     /**
246      * Returns the temporary directory
247      */

248     public static File JavaDoc getTempDirectory(){
249         if(tempDirectory == null){
250             String JavaDoc tmpDir = System.getProperty("java.io.tmpdir");
251             if(tmpDir == null){
252                 throw new Error JavaDoc();
253             }
254
255             tempDirectory = new File JavaDoc(tmpDir);
256             if(!tempDirectory.exists()){
257                 throw new Error JavaDoc();
258             }
259         }
260         return tempDirectory;
261     }
262
263     /**
264      * Constructor.
265      * @param svgURL the URL String for the SVG document being tested.
266      * @param refImgURL the URL for the reference image.
267      */

268     public AbstractRenderingAccuracyTest(String JavaDoc svgURL,
269                                     String JavaDoc refImgURL){
270         setConfig(svgURL, refImgURL);
271     }
272
273     /**
274      * For subclasses
275      */

276     protected AbstractRenderingAccuracyTest(){
277     }
278
279     /**
280      * Sets this test's config.
281      */

282     public void setConfig(String JavaDoc svgURL,
283                           String JavaDoc refImgURL){
284         if(svgURL == null){
285             throw new IllegalArgumentException JavaDoc();
286         }
287
288         if(refImgURL == null){
289             throw new IllegalArgumentException JavaDoc();
290         }
291
292         this.svgURL = resolveURL(svgURL);
293         this.refImgURL = resolveURL(refImgURL);
294     }
295     
296     /**
297      * Resolves the input string as follows.
298      * + First, the string is interpreted as a file description.
299      * If the file exists, then the file name is turned into
300      * a URL.
301      * + Otherwise, the string is supposed to be a URL. If it
302      * is an invalid URL, an IllegalArgumentException is thrown.
303      */

304     protected URL JavaDoc resolveURL(String JavaDoc url){
305         // Is url a file?
306
File JavaDoc f = (new File JavaDoc(url)).getAbsoluteFile();
307         if(f.getParentFile().exists()){
308             try{
309                 return f.toURL();
310             }catch(MalformedURLException JavaDoc e){
311                 throw new IllegalArgumentException JavaDoc();
312             }
313         }
314         
315         // url is not a file. It must be a regular URL...
316
try{
317             return new URL JavaDoc(url);
318         }catch(MalformedURLException JavaDoc e){
319             throw new IllegalArgumentException JavaDoc(url);
320         }
321     }
322
323     /**
324      * Sets the File where the variation from the reference image should be
325      * stored
326      */

327     public void setSaveVariation(File JavaDoc saveVariation){
328         this.saveVariation = saveVariation;
329     }
330
331     public File JavaDoc getSaveVariation(){
332         return saveVariation;
333     }
334
335     public String JavaDoc getVariationURL(){
336         return variationURL.toString();
337     }
338
339     /**
340      * Sets the URL where an acceptable variation fron the reference
341      * image can be found.
342      */

343     public void setVariationURL(String JavaDoc variationURL){
344         this.variationURL = resolveURL(variationURL);
345     }
346
347     /**
348      * See {@link #candidateReference}
349      */

350     public void setCandidateReference(File JavaDoc candidateReference){
351         this.candidateReference = candidateReference;
352     }
353
354     public File JavaDoc getCandidateReference(){
355         return candidateReference;
356     }
357
358     /**
359      * Returns this <tt>Test</tt>'s name. The name is the
360      * URL of the SVG being rendered.
361      */

362     public String JavaDoc getName(){
363         if(this.name == null){
364             return svgURL.toString();
365         }
366         return name;
367     }
368
369     /**
370      * Requests this <tt>Test</tt> to run and produce a
371      * report.
372      *
373      */

374     public TestReport run() {
375         DefaultTestReport report = new DefaultTestReport(this);
376
377         //
378
// First, do clean-up
379
//
380
if (candidateReference != null){
381             if (candidateReference.exists()){
382                 candidateReference.delete();
383             }
384         }
385                     
386
387         //
388
// Render the SVG image into a raster. We call an
389
// abstract method to convert the src into a raster in
390
// a temporary file.
391
File JavaDoc tmpFile = null;
392
393         try{
394             if (candidateReference != null)
395                 tmpFile = candidateReference;
396             else
397                 tmpFile = File.createTempFile(TEMP_FILE_PREFIX,
398                                               TEMP_FILE_SUFFIX,
399                                               null);
400         }catch(IOException JavaDoc e){
401             report.setErrorCode(ERROR_CANNOT_CREATE_TEMP_FILE);
402             report.setDescription(new TestReport.Entry[] {
403                 new TestReport.Entry
404                 (Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
405                  Messages.formatMessage(ERROR_CANNOT_CREATE_TEMP_FILE,
406                                         new Object JavaDoc[]{e.getMessage()}))
407             });
408             report.setPassed(false);
409             return report;
410         }
411
412
413         FileOutputStream JavaDoc tmpFileOS = null;
414
415         try{
416             tmpFileOS = new FileOutputStream JavaDoc(tmpFile);
417         }catch(IOException JavaDoc e){
418             report.setErrorCode(ERROR_CANNOT_CREATE_TEMP_FILE_STREAM);
419             report.setDescription(new TestReport.Entry[] {
420                 new TestReport.Entry
421                 (Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
422                  Messages.formatMessage(ERROR_CANNOT_CREATE_TEMP_FILE_STREAM,
423                                         new String JavaDoc[]{tmpFile.getAbsolutePath(),
424                                                      e.getMessage()})) });
425             report.setPassed(false);
426             tmpFile.deleteOnExit();
427             return report;
428         }
429
430         // Call abstract method to encode svgURL to tmpFileOS as a
431
// raster. If this returns a non-null test report then the
432
// encoding failed and we should return that report.
433
{
434             TestReport encodeTR = encode(svgURL, tmpFileOS);
435             if ((encodeTR != null) &&
436                 (encodeTR.hasPassed() == false)) {
437                 tmpFile.deleteOnExit();
438                 return encodeTR;
439             }
440         }
441
442         //
443
// Do a binary comparison of the encoded images.
444
//
445
InputStream JavaDoc refStream = null;
446         InputStream JavaDoc newStream = null;
447         try {
448             refStream = new BufferedInputStream JavaDoc(refImgURL.openStream());
449         }catch(IOException JavaDoc e){
450             report.setErrorCode(ERROR_CANNOT_OPEN_REFERENCE_IMAGE);
451             report.setDescription(new TestReport.Entry[]{
452                 new TestReport.Entry
453                 (Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
454                  Messages.formatMessage(ERROR_CANNOT_OPEN_REFERENCE_IMAGE,
455                                         new Object JavaDoc[]{refImgURL.toString(),
456                                                      e.getMessage()}))
457                 });
458             report.setPassed(false);
459             // Try and save tmp file as a candidate variation
460
if (candidateReference == null){
461                 tmpFile.delete();
462             }
463             return report;
464         }
465
466         try{
467             newStream = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(tmpFile));
468         }catch(IOException JavaDoc e){
469             report.setErrorCode(ERROR_CANNOT_OPEN_GENERATED_IMAGE);
470             report.setDescription(new TestReport.Entry[]{
471                 new TestReport.Entry
472                 (Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
473                  Messages.formatMessage(ERROR_CANNOT_OPEN_GENERATED_IMAGE,
474                                         new Object JavaDoc[]{tmpFile.getAbsolutePath(),
475                                                      e.getMessage()}))});
476             report.setPassed(false);
477             tmpFile.delete();
478             return report;
479         }
480
481         boolean accurate = false;
482         try{
483             accurate = compare(refStream, newStream);
484         } catch(IOException JavaDoc e) {
485             report.setErrorCode(ERROR_ERROR_WHILE_COMPARING_FILES);
486             report.setDescription(new TestReport.Entry[]{
487                 new TestReport.Entry
488                 (Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
489                  Messages.formatMessage(ERROR_ERROR_WHILE_COMPARING_FILES,
490                                         new Object JavaDoc[]{refImgURL.toString(),
491                                                      tmpFile.getAbsolutePath(),
492                                                      e.getMessage()}))});
493             report.setPassed(false);
494             if (candidateReference == null){
495                 tmpFile.delete();
496             }
497             return report;
498         }
499
500
501         if(accurate){
502             //
503
// Yahooooooo! everything worked out well.
504
//
505
report.setPassed(true);
506             tmpFile.delete();
507             return report;
508         }
509
510         //
511
// If the files still differ here, it means that even the
512
// variation does not account for the difference return an
513
// error
514
//
515
try {
516             BufferedImage JavaDoc ref = getImage(refImgURL);
517             BufferedImage JavaDoc gen = getImage(tmpFile);
518             BufferedImage JavaDoc diff = buildDiffImage(ref, gen);
519
520             //
521
// If there is an accepted variation, check if it equals the
522
// computed difference.
523
//
524
if(variationURL != null) {
525                 File JavaDoc tmpDiff = imageToFile(diff, IMAGE_TYPE_DIFF);
526                 
527                 InputStream JavaDoc variationURLStream = null;
528                 try{
529                     variationURLStream = variationURL.openStream();
530                 }catch(IOException JavaDoc e){
531                     // Could not open variationURL stream. Just trace that
532
System.err.println(Messages.formatMessage(COULD_NOT_OPEN_VARIATION_URL,
533                                                               new Object JavaDoc[]{variationURL.toString()}));
534                 }
535                 
536                 if(variationURLStream != null){
537                     InputStream JavaDoc refDiffStream =
538                         new BufferedInputStream JavaDoc(variationURLStream);
539                     
540                     InputStream JavaDoc tmpDiffStream =
541                         new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(tmpDiff));
542                     
543                     if(compare(refDiffStream, tmpDiffStream)){
544                         // We accept the generated result.
545
accurate = true;
546                     }
547                 }
548             }
549             
550             if (accurate) {
551                 //
552
// Yahooooooo! everything worked out well, at least
553
// with variation.
554
report.setPassed(true);
555                 tmpFile.delete();
556                 return report;
557             }
558
559             System.err.println(">>>>>>>>>>>>>>>>>>>>>> "+
560                                "Rendering is not accurate");
561             if(saveVariation != null){
562                 // There is a computed variation different from the
563
// referenced variation and there is a place where the new
564
// variation should be saved.
565
saveImage(diff, saveVariation);
566             }
567                 
568             // Build two images:
569
// a. One with the reference image and the newly generated image
570
// b. One with the difference between the two images and the set
571
// of different pixels.
572
BufferedImage JavaDoc cmp = makeCompareImage(ref, gen);
573             File JavaDoc cmpFile = imageToFile(cmp, IMAGE_TYPE_COMPARISON);
574             File JavaDoc diffFile = imageToFile(diff, IMAGE_TYPE_DIFF);
575             
576             report.setErrorCode(ERROR_SVG_RENDERING_NOT_ACCURATE);
577             report.setDescription(new TestReport.Entry[]{
578                 new TestReport.Entry
579                 (Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
580                  Messages.formatMessage(ERROR_SVG_RENDERING_NOT_ACCURATE, null)),
581                 new TestReport.Entry
582                 (Messages.formatMessage(ENTRY_KEY_REFERENCE_GENERATED_IMAGE_URI,
583                                         null), cmpFile),
584                 new TestReport.Entry
585                 (Messages.formatMessage(ENTRY_KEY_DIFFERENCE_IMAGE, null),
586                  diffFile) });
587         }catch(Exception JavaDoc e){
588             report.setErrorCode(ERROR_SVG_RENDERING_NOT_ACCURATE);
589             StringWriter JavaDoc trace = new StringWriter JavaDoc();
590             e.printStackTrace(new PrintWriter JavaDoc(trace));
591             
592             report.setDescription(new TestReport.Entry[]{
593                 new TestReport.Entry
594                 (Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
595                  Messages.formatMessage(ERROR_SVG_RENDERING_NOT_ACCURATE, null)),
596                 new TestReport.Entry
597                 (Messages.formatMessage(ENTRY_KEY_INTERNAL_ERROR, null),
598                  Messages.formatMessage(COULD_NOT_GENERATE_COMPARISON_IMAGES,
599                                         new Object JavaDoc[]{e.getClass().getName(),
600                                                      e.getMessage(),
601                                                      trace.toString()})) });
602         }
603         
604         if (candidateReference == null){
605             tmpFile.delete();
606         }
607             
608         report.setPassed(false);
609         return report;
610     }
611
612     public abstract TestReport encode(URL JavaDoc srcURL, FileOutputStream JavaDoc fos);
613
614     /**
615      * Compare the two input streams
616      */

617     protected boolean compare(InputStream JavaDoc refStream,
618                               InputStream JavaDoc newStream)
619         throws IOException JavaDoc{
620         int b, nb;
621         do {
622             b = refStream.read();
623             nb = newStream.read();
624         } while (b != -1 && nb != -1 && b == nb);
625         refStream.close();
626         newStream.close();
627         return (b == nb);
628     }
629
630     /**
631      * Saves an image in a given File
632      */

633     protected void saveImage(BufferedImage JavaDoc img, File JavaDoc imgFile)
634         throws IOException JavaDoc {
635         if(!imgFile.exists()){
636             imgFile.createNewFile();
637         }
638         saveImage(img, new FileOutputStream JavaDoc(imgFile));
639     }
640
641     /**
642      * Saves an image in a given File
643      */

644     protected void saveImage(BufferedImage JavaDoc img, OutputStream JavaDoc os)
645         throws IOException JavaDoc {
646         PNGImageEncoder encoder = new PNGImageEncoder
647             (os, PNGEncodeParam.getDefaultEncodeParam(img));
648         
649         encoder.encode(img);
650     }
651
652     /**
653      * Builds a new BufferedImage that is the difference between the
654      * two input images
655      */

656     public static BufferedImage JavaDoc buildDiffImage(BufferedImage JavaDoc ref,
657                                                BufferedImage JavaDoc gen) {
658         BufferedImage JavaDoc diff = new BufferedImage JavaDoc(ref.getWidth(),
659                                                ref.getHeight(),
660                                                BufferedImage.TYPE_INT_ARGB);
661         WritableRaster JavaDoc refWR = ref.getRaster();
662         WritableRaster JavaDoc genWR = gen.getRaster();
663         WritableRaster JavaDoc dstWR = diff.getRaster();
664
665         boolean refPre = ref.isAlphaPremultiplied();
666         if (!refPre) {
667             ColorModel JavaDoc cm = ref.getColorModel();
668             cm = GraphicsUtil.coerceData(refWR, cm, true);
669             ref = new BufferedImage JavaDoc(cm, refWR, true, null);
670         }
671         boolean genPre = gen.isAlphaPremultiplied();
672         if (!genPre) {
673             ColorModel JavaDoc cm = gen.getColorModel();
674             cm = GraphicsUtil.coerceData(genWR, cm, true);
675             gen = new BufferedImage JavaDoc(cm, genWR, true, null);
676         }
677
678
679         int w=ref.getWidth();
680         int h=ref.getHeight();
681         int y, i,val;
682         int [] refPix = null;
683         int [] genPix = null;
684         for (y=0; y<h; y++) {
685             refPix = refWR.getPixels (0, y, w, 1, refPix);
686             genPix = genWR.getPixels (0, y, w, 1, genPix);
687             for (i=0; i<refPix.length; i++) {
688                 val = ((genPix[i]-refPix[i])*10)+128;
689                 if ((val & 0xFFFFFF00) != 0)
690                     if ((val & 0x80000000) != 0) val = 0;
691                     else val = 255;
692                 genPix[i] = val;
693             }
694             dstWR.setPixels(0, y, w, 1, genPix);
695         }
696
697         if (!genPre) {
698             ColorModel JavaDoc cm = gen.getColorModel();
699             cm = GraphicsUtil.coerceData(genWR, cm, false);
700         }
701         
702         if (!refPre) {
703             ColorModel JavaDoc cm = ref.getColorModel();
704             cm = GraphicsUtil.coerceData(refWR, cm, false);
705         }
706
707         return diff;
708     }
709
710     /**
711      * Loads an image from a File
712      */

713     protected BufferedImage JavaDoc getImage(File JavaDoc file)
714         throws Exception JavaDoc {
715         return getImage(file.toURL());
716     }
717
718     /**
719      * Loads an image from a URL
720      */

721     protected BufferedImage JavaDoc getImage(URL JavaDoc url)
722         throws IOException JavaDoc {
723         ImageTagRegistry reg = ImageTagRegistry.getRegistry();
724         Filter filt = reg.readURL(new ParsedURL(url));
725         if(filt == null)
726             throw new IOException JavaDoc(Messages.formatMessage
727                                   (COULD_NOT_LOAD_IMAGE,
728                                    new Object JavaDoc[]{url.toString()}));
729
730         RenderedImage JavaDoc red = filt.createDefaultRendering();
731         if(red == null)
732             throw new IOException JavaDoc(Messages.formatMessage
733                                   (COULD_NOT_LOAD_IMAGE,
734                                    new Object JavaDoc[]{url.toString()}));
735         
736         BufferedImage JavaDoc img = new BufferedImage JavaDoc(red.getWidth(),
737                                               red.getHeight(),
738                                               BufferedImage.TYPE_INT_ARGB);
739         red.copyData(img.getRaster());
740
741         return img;
742     }
743
744     /**
745      *
746      */

747     protected BufferedImage JavaDoc makeCompareImage(BufferedImage JavaDoc ref,
748                                              BufferedImage JavaDoc gen){
749         BufferedImage JavaDoc cmp = new BufferedImage JavaDoc(ref.getWidth()*2,
750                                               ref.getHeight(),
751                                               BufferedImage.TYPE_INT_ARGB);
752
753         Graphics2D JavaDoc g = cmp.createGraphics();
754         g.setPaint(Color.white);
755         g.fillRect(0, 0, cmp.getWidth(), cmp.getHeight());
756         g.drawImage(ref, 0, 0, null);
757         g.translate(ref.getWidth(), 0);
758         g.drawImage(gen, 0, 0, null);
759         g.dispose();
760
761         return cmp;
762     }
763
764     /**
765      * Creates a File into which the input image is
766      * saved.
767      * If there is a "file" component in the SVG url,
768      * then a temporary file is created with that
769      * name and the imageType suffix in the temp
770      * directory of the test-reports directory.
771      */

772     protected File JavaDoc imageToFile(BufferedImage JavaDoc img,
773                                String JavaDoc imageType)
774         throws IOException JavaDoc {
775         String JavaDoc file = getURLFile(svgURL);
776
777         File JavaDoc imageFile = null;
778         if( !"".equals(file) ){
779             imageFile = makeTempFileName(file, imageType);
780         }
781         else{
782             imageFile = makeRandomFileName(imageType);
783         }
784         
785         imageFile.deleteOnExit();
786
787         PNGImageEncoder encoder = new PNGImageEncoder
788             (new FileOutputStream JavaDoc(imageFile),
789              PNGEncodeParam.getDefaultEncodeParam(img));
790         
791         encoder.encode(img);
792         
793         return imageFile;
794     }
795
796     /**
797      * Extracts the file portion of the URL
798      */

799     protected String JavaDoc getURLFile(URL JavaDoc url){
800         String JavaDoc path = url.getPath();
801         int n = path.lastIndexOf('/');
802         if(n == -1){
803             return path;
804         }
805         else{
806             if(n<path.length()){
807                 return path.substring(n+1, path.length());
808             }
809             else{
810                 return "";
811             }
812         }
813     }
814
815     protected File JavaDoc makeTempFileName(String JavaDoc svgFileName,
816                                     String JavaDoc imageType){
817         int dotIndex = svgFileName.lastIndexOf('.');
818         if( dotIndex == -1){
819             return getNextTempFileName(svgFileName + imageType);
820         }
821         else{
822             return getNextTempFileName
823                 (svgFileName.substring(0, dotIndex) +
824                  imageType + IMAGE_FILE_EXTENSION);
825         }
826     }
827     
828     protected File JavaDoc getNextTempFileName(String JavaDoc fileName){
829         File JavaDoc f = new File JavaDoc(getTempDirectory(), fileName);
830         if(!f.exists()){
831             return f;
832         }
833         else{
834             return getNextTempFileName(fileName,
835                                        1);
836         }
837     }
838     
839     protected File JavaDoc getNextTempFileName(String JavaDoc fileName,
840                                        int instance){
841         // First, create a 'versioned' file name
842
int n = fileName.lastIndexOf('.');
843         String JavaDoc iFileName = fileName + instance;
844         if(n != -1){
845             iFileName = fileName.substring(0, n) + instance
846                 + fileName.substring(n, fileName.length());
847         }
848         
849         File JavaDoc r = new File JavaDoc(getTempDirectory(), iFileName);
850         if(!r.exists()){
851             return r;
852         }
853         else{
854             return getNextTempFileName(fileName,
855                                        instance + 1);
856         }
857     }
858     
859     /**
860      * Creates a temporary File into which the input image is
861      * saved.
862      */

863     protected File JavaDoc makeRandomFileName(String JavaDoc imageType)
864         throws IOException JavaDoc {
865         
866         return File.createTempFile(TEMP_FILE_PREFIX,
867                                    TEMP_FILE_SUFFIX + imageType,
868                                    null);
869     }
870 }
871
Popular Tags