KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > image > Image


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. 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.tools.ant.taskdefs.optional.image;
19
20 import com.sun.media.jai.codec.FileSeekableStream;
21 import org.apache.tools.ant.BuildException;
22 import org.apache.tools.ant.DirectoryScanner;
23 import org.apache.tools.ant.taskdefs.MatchingTask;
24 import org.apache.tools.ant.types.FileSet;
25 import org.apache.tools.ant.types.optional.image.Draw;
26 import org.apache.tools.ant.types.optional.image.ImageOperation;
27 import org.apache.tools.ant.types.optional.image.Rotate;
28 import org.apache.tools.ant.types.optional.image.Scale;
29 import org.apache.tools.ant.types.optional.image.TransformOperation;
30
31 import javax.media.jai.JAI;
32 import javax.media.jai.PlanarImage;
33 import java.io.File JavaDoc;
34 import java.io.FileOutputStream JavaDoc;
35 import java.io.IOException JavaDoc;
36 import java.util.ArrayList JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.Vector JavaDoc;
39
40 /**
41  * A MatchingTask which relies on <a
42  * HREF="http://java.sun.com/products/java-media/jai">JAI (Java
43  * Advanced Imaging)</a> to perform image manipulation operations on
44  * existing images. The operations are represented as ImageOperation
45  * DataType objects. The operations are arranged to conform to the
46  * Chaining Model of JAI. Check out the <a
47  * HREF="http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/">
48  * JAI Programming Guide</a>.
49  *
50  * @see org.apache.tools.ant.types.optional.image.ImageOperation
51  * @see org.apache.tools.ant.types.DataType
52  */

53 public class Image extends MatchingTask {
54     // CheckStyle:VisibilityModifier OFF - bc
55
protected Vector JavaDoc instructions = new Vector JavaDoc();
56     protected boolean overwrite = false;
57     protected Vector JavaDoc filesets = new Vector JavaDoc();
58     protected File JavaDoc srcDir = null;
59     protected File JavaDoc destDir = null;
60
61     // CheckStyle:MemberNameCheck OFF - bc
62

63     //cannot remove underscores due to protected visibility >:(
64
protected String JavaDoc str_encoding = "JPEG";
65     protected boolean garbage_collect = false;
66
67     private boolean failonerror = true;
68
69     // CheckStyle:MemberNameCheck ON
70

71     // CheckStyle:VisibilityModifier ON
72

73     /**
74      * Add a set of files to be deleted.
75      * @param set the FileSet to add.
76      */

77     public void addFileset(FileSet set) {
78         filesets.addElement(set);
79     }
80
81     /**
82      * Set whether to fail on error.
83      * If false, note errors to the output but keep going.
84      * @param failonerror true or false.
85      */

86     public void setFailOnError(boolean failonerror) {
87         this.failonerror = failonerror;
88     }
89
90     /**
91      * Set the source dir to find the image files.
92      * @param srcDir the directory in which the image files reside.
93      */

94     public void setSrcdir(File JavaDoc srcDir) {
95         this.srcDir = srcDir;
96     }
97
98     /**
99      * Set the image encoding type. <a
100      * HREF="http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/Encode.doc.html#56610">
101      * See this table in the JAI Programming Guide</a>.
102      * @param encoding the String image encoding.
103      */

104     public void setEncoding(String JavaDoc encoding) {
105         str_encoding = encoding;
106     }
107
108     /**
109      * Set whether to overwrite a file if there is a naming conflict.
110      * @param overwrite whether to overwrite.
111      */

112     public void setOverwrite(boolean overwrite) {
113         this.overwrite = overwrite;
114     }
115
116     /**
117      * Set whether to invoke Garbage Collection after each image processed.
118      * Defaults to false.
119      * @param gc whether to invoke the garbage collector.
120      */

121     public void setGc(boolean gc) {
122         garbage_collect = gc;
123     }
124
125     /**
126      * Set the destination directory for manipulated images.
127      * @param destDir The destination directory.
128      */

129     public void setDestDir(File JavaDoc destDir) {
130         this.destDir = destDir;
131     }
132
133     /**
134      * Add an ImageOperation to chain.
135      * @param instr The ImageOperation to append to the chain.
136      */

137     public void addImageOperation(ImageOperation instr) {
138         instructions.add(instr);
139     }
140
141     /**
142      * Add a Rotate ImageOperation to the chain.
143      * @param instr The Rotate operation to add to the chain.
144      * @see org.apache.tools.ant.types.optional.image.Rotate
145      */

146     public void addRotate(Rotate instr) {
147         instructions.add(instr);
148     }
149
150     /**
151      * Add a Scale ImageOperation to the chain.
152      * @param instr The Scale operation to add to the chain.
153      * @see org.apache.tools.ant.types.optional.image.Scale
154      */

155     public void addScale(Scale instr) {
156         instructions.add(instr);
157     }
158
159     /**
160      * Add a Draw ImageOperation to the chain. DrawOperation
161      * DataType objects can be nested inside the Draw object.
162      * @param instr The Draw operation to add to the chain.
163      * @see org.apache.tools.ant.types.optional.image.Draw
164      * @see org.apache.tools.ant.types.optional.image.DrawOperation
165      */

166     public void addDraw(Draw instr) {
167         instructions.add(instr);
168     }
169
170     /**
171     * Add an ImageOperation to chain.
172     * @param instr The ImageOperation to append to the chain.
173     * @since Ant 1.7
174     */

175     public void add(ImageOperation instr) {
176         addImageOperation(instr);
177     }
178
179     /**
180      * Executes all the chained ImageOperations on the file
181      * specified.
182      * @param file The file to be processed.
183      */

184     public void processFile(File JavaDoc file) {
185         try {
186             log("Processing File: " + file.getAbsolutePath());
187             FileSeekableStream input = new FileSeekableStream(file);
188             PlanarImage image = JAI.create("stream", input);
189             for (int i = 0; i < instructions.size(); i++) {
190                 Object JavaDoc instr = instructions.elementAt(i);
191                 if (instr instanceof TransformOperation) {
192                     image = ((TransformOperation) instr)
193                         .executeTransformOperation(image);
194                 } else {
195                     log("Not a TransformOperation: " + instr);
196                 }
197             }
198             input.close();
199
200             if (str_encoding.toLowerCase().equals("jpg")) {
201                 str_encoding = "JPEG";
202             } else if (str_encoding.toLowerCase().equals("tif")) {
203                 str_encoding = "TIFF";
204             }
205             if (destDir == null) {
206                 destDir = srcDir;
207             }
208             File JavaDoc newFile = new File JavaDoc(destDir, file.getName());
209
210             if ((overwrite && newFile.exists()) && (!newFile.equals(file))) {
211                 newFile.delete();
212             }
213             FileOutputStream JavaDoc stream = new FileOutputStream JavaDoc(newFile);
214
215             JAI.create("encode", image, stream, str_encoding.toUpperCase(),
216                        null);
217             stream.flush();
218             stream.close();
219         } catch (IOException JavaDoc err) {
220             if (!failonerror) {
221                 log("Error processing file: " + err);
222             } else {
223                 throw new BuildException(err);
224             }
225         } catch (java.lang.RuntimeException JavaDoc rerr) {
226             if (!failonerror) {
227                 log("Error processing file: " + rerr);
228             } else {
229                 throw new BuildException(rerr);
230             }
231         }
232     }
233
234     /**
235      * Executes the Task.
236      * @throws BuildException on error.
237      */

238     public void execute() throws BuildException {
239
240         validateAttributes();
241
242         try {
243             DirectoryScanner ds = null;
244             String JavaDoc[] files = null;
245             ArrayList JavaDoc filesList = new ArrayList JavaDoc();
246
247             // deal with specified srcDir
248
if (srcDir != null) {
249                 ds = super.getDirectoryScanner(srcDir);
250
251                 files = ds.getIncludedFiles();
252                 for (int i = 0; i < files.length; i++) {
253                     filesList.add(new File JavaDoc(srcDir, files[i]));
254                 }
255             }
256             // deal with the filesets
257
for (int i = 0; i < filesets.size(); i++) {
258                 FileSet fs = (FileSet) filesets.elementAt(i);
259                 ds = fs.getDirectoryScanner(getProject());
260                 files = ds.getIncludedFiles();
261                 File JavaDoc fromDir = fs.getDir(getProject());
262                 for (int j = 0; j < files.length; j++) {
263                     filesList.add(new File JavaDoc(fromDir, files[j]));
264                 }
265             }
266             if (!overwrite) {
267                 // remove any files that shouldn't be overwritten.
268
ArrayList JavaDoc filesToRemove = new ArrayList JavaDoc();
269                 for (Iterator JavaDoc i = filesList.iterator(); i.hasNext();) {
270                     File JavaDoc f = (File JavaDoc) i.next();
271                     File JavaDoc newFile = new File JavaDoc(destDir, f.getName());
272                     if (newFile.exists()) {
273                         filesToRemove.add(f);
274                     }
275                 }
276                 filesList.removeAll(filesToRemove);
277             }
278             // iterator through all the files and process them.
279
for (Iterator JavaDoc i = filesList.iterator(); i.hasNext();) {
280                 File JavaDoc file = (File JavaDoc) i.next();
281
282                 processFile(file);
283                 if (garbage_collect) {
284                     System.gc();
285                 }
286             }
287         } catch (Exception JavaDoc err) {
288             err.printStackTrace();
289             throw new BuildException(err.getMessage());
290         }
291     }
292
293     /**
294      * Ensure we have a consistent and legal set of attributes, and set
295      * any internal flags necessary based on different combinations
296      * of attributes.
297      * @throws BuildException on error.
298      */

299     protected void validateAttributes() throws BuildException {
300         if (srcDir == null && filesets.size() == 0) {
301             throw new BuildException("Specify at least one source"
302                                      + "--a srcDir or a fileset.");
303         }
304         if (srcDir == null && destDir == null) {
305             throw new BuildException("Specify the destDir, or the srcDir.");
306         }
307     }
308 }
309
310
Popular Tags