KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > modules > image > ImageResizer


1 /*
2  * Created on Dec 8, 2004
3  */

4 package com.openedit.modules.image;
5
6 import java.awt.Dimension JavaDoc;
7 import java.awt.Graphics2D JavaDoc;
8 import java.awt.RenderingHints JavaDoc;
9 import java.awt.image.BufferedImage JavaDoc;
10 import java.io.File JavaDoc;
11 import java.io.FileNotFoundException JavaDoc;
12 import java.io.IOException JavaDoc;
13
14 import javax.imageio.ImageIO JavaDoc;
15
16 import org.apache.commons.logging.Log;
17 import org.apache.commons.logging.LogFactory;
18
19 /**
20  * Resizes JPEG images.
21  *
22  * @author dbrown
23  *
24  */

25 public class ImageResizer
26 {
27     private static final Log log = LogFactory.getLog(ImageResizer.class);
28
29     protected Dimension JavaDoc fieldMaxScaledSize = new Dimension JavaDoc( 150, Integer.MAX_VALUE );
30
31     /**
32      * TODO - This main method is just for testing
33      * @param args
34      */

35     public static void main(String JavaDoc[] args)
36     {
37         try
38         {
39             if ( args.length < 2)
40             {
41                 log.error("Usage: dir|file in out");
42                 return;
43             }
44             ImageResizer resizer = new ImageResizer();
45 /* int numImages = resizer.resizeImagesInDirectory(
46                 new File("/home/dbrown/workspace/openedit-cart/webapp/photos"),
47                 new File("/home/dbrown/workspace/openedit-cart/webapp/photos-scaled"),
48                 true );
49                 
50 */

51             if ( "dir".equals( args[0] ) )
52             {
53                 int numImages = resizer.resizeImagesInDirectory(
54                     new File JavaDoc( args[1] ),
55                     new File JavaDoc( args[2] ),
56                     true );
57                 log.info( numImages + " image(s) scaled" );
58                 
59             }
60             else
61             {
62                 File JavaDoc in = new File JavaDoc( args[1]);
63                 File JavaDoc out = new File JavaDoc( args[2]);
64                 log.info("Converting " + in.getAbsolutePath() + " to " + out.getPath() );
65                 
66                 resizer.resizeImage(in, out);
67             }
68             
69         }
70         catch ( Exception JavaDoc e )
71         {
72             System.err.println( "Fatal exception: " + e );
73             e.printStackTrace();
74         }
75     }
76
77     public ImageResizer()
78     {
79     }
80
81     /**
82      * Resizes all JPEG images (files with .jpg or .jpeg extension) in
83      * the specified directory, unless they already exist in the target
84      * directory.
85      *
86      * @param inInDirectory input directory
87      * @param inOutDirectory output directory, will be created if it does not exist
88      * @param inRecurse true if this is to recurse through directories
89      * @return number of files resized
90      * @throws IOException
91      */

92     public int resizeImagesInDirectory( File JavaDoc inInDirectory, File JavaDoc inOutDirectory,
93         boolean inRecurse ) throws Exception JavaDoc
94     {
95         // validate input arguments
96
if ( !inInDirectory.exists() )
97         {
98             throw new FileNotFoundException JavaDoc( inInDirectory + " does not exist" );
99         }
100         if ( !inOutDirectory.exists() && !inOutDirectory.mkdirs() )
101         {
102             throw new FileNotFoundException JavaDoc( inOutDirectory + " does not exist and cannot be created" );
103         }
104         if ( !inInDirectory.isDirectory() )
105         {
106             throw new IllegalArgumentException JavaDoc( inInDirectory + " is not a directory" );
107         }
108         if ( !inOutDirectory.isDirectory() )
109         {
110             throw new IllegalArgumentException JavaDoc( inOutDirectory + " is not a directory" );
111         }
112         if ( inInDirectory.equals( inOutDirectory ) )
113         {
114             throw new IllegalArgumentException JavaDoc( "directory arguments are the same" );
115         }
116
117         // resize all images with a .jpg or .jpeg extension
118
int numImagesResized = 0;
119         File JavaDoc[] inputFiles = inInDirectory.listFiles();
120         for ( int n = 0; n < inputFiles.length; n++ )
121         {
122             File JavaDoc inputFile = inputFiles[ n ];
123             String JavaDoc filename = inputFile.getName();
124             if ( inputFile.isDirectory() )
125             {
126                 if ( inRecurse )
127                 {
128                     File JavaDoc outputDir = new File JavaDoc( inOutDirectory, filename );
129                     outputDir.mkdir();
130                     numImagesResized += resizeImagesInDirectory(
131                         inputFile, outputDir, inRecurse );
132                 }
133             }
134             else
135             {
136                 if ( filename.toLowerCase().endsWith( "jpg" ) ||
137                     filename.toLowerCase().endsWith( "jpeg" ) )
138                 {
139                     File JavaDoc outputFile = new File JavaDoc( inOutDirectory, filename );
140                     if ( outputFile.exists() )
141                     {
142                         log.info( "Skipping resizing " + filename );
143                     }
144                     else
145                     {
146                         try
147                         {
148                             resizeImage( inputFile, outputFile );
149                             numImagesResized++;
150                         }
151                         catch ( IOException JavaDoc e )
152                         {
153                             log.error( "Image " + inputFile + " could not be resized" );
154                             log.error( e );
155                         }
156                     }
157                 }
158             }
159         }
160
161         return numImagesResized;
162     }
163
164     /**
165      * Resizes a single image file.
166      *
167      * @param inInImageFile input file
168      * @param inOutImageFile output file
169      * @throws IOException
170      */

171     public void resizeImage( File JavaDoc inInImageFile, File JavaDoc inOutImageFile )
172         throws Exception JavaDoc
173     {
174         BufferedImage JavaDoc origImage = ImageIO.read( inInImageFile );
175         if ( origImage == null )
176         {
177             throw new IllegalArgumentException JavaDoc("Input file is not valid " + inInImageFile.getPath());
178         }
179         Dimension JavaDoc scaledSize = getScaledSize( origImage );
180         BufferedImage JavaDoc scaledImage = new BufferedImage JavaDoc( scaledSize.width,
181             scaledSize.height, BufferedImage.TYPE_INT_RGB );
182         Graphics2D JavaDoc scaledGraphics = scaledImage.createGraphics();
183         scaledGraphics.setRenderingHint( RenderingHints.KEY_INTERPOLATION,
184             RenderingHints.VALUE_INTERPOLATION_BICUBIC);
185         scaledGraphics.drawImage( origImage, 0, 0, scaledSize.width,
186             scaledSize.height, null );
187         inOutImageFile.getParentFile().mkdirs();
188         ImageIO.write( scaledImage, "jpeg", inOutImageFile );
189         log.info("Resize complete " + inInImageFile.getPath());
190     }
191
192     protected Dimension JavaDoc getScaledSize( BufferedImage JavaDoc inOrigImage )
193     {
194         Dimension JavaDoc maxSize = getMaxScaledSize();
195         double heightScale = (double)maxSize.height / (double)inOrigImage.getHeight();
196         heightScale = Math.min( heightScale, 1.0 );
197         double widthScale = (double)maxSize.width / (double)inOrigImage.getWidth();
198         widthScale = Math.min( widthScale, 1.0 );
199         double scale = Math.min( heightScale, widthScale );
200         return new Dimension JavaDoc(
201             (int)Math.round( scale * inOrigImage.getWidth() ),
202             (int)Math.round( scale * inOrigImage.getHeight() ) );
203     }
204
205     public Dimension JavaDoc getMaxScaledSize()
206     {
207         if ( fieldMaxScaledSize == null )
208         {
209             fieldMaxScaledSize = new Dimension JavaDoc();
210         }
211         return fieldMaxScaledSize;
212     }
213
214     public void setMaxScaledSize(Dimension JavaDoc inMaxScaledSize)
215     {
216         fieldMaxScaledSize = inMaxScaledSize;
217     }
218 }
Popular Tags