KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > util > image > ImageUtils


1 /*
2  * Copyright (c) Rafael Steil
3  * All rights reserved.
4
5  * Redistribution and use in source and binary forms,
6  * with or without modification, are permitted provided
7  * that the following conditions are met:
8
9  * 1) Redistributions of source code must retain the above
10  * copyright notice, this list of conditions and the
11  * following disclaimer.
12  * 2) Redistributions in binary form must reproduce the
13  * above copyright notice, this list of conditions and
14  * the following disclaimer in the documentation and/or
15  * other materials provided with the distribution.
16  * 3) Neither the name of "Rafael Steil" nor
17  * the names of its contributors may be used to endorse
18  * or promote products derived from this software without
19  * specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
22  * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
23  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
27  * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
32  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
34  * IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
36  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
37  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
38  *
39  * This file creation date: 21/04/2004 - 19:54:16
40  * The JForum Project
41  * http://www.jforum.net
42  */

43 package net.jforum.util.image;
44
45 import java.awt.Dimension JavaDoc;
46 import java.awt.Graphics JavaDoc;
47 import java.awt.Image JavaDoc;
48 import java.awt.image.BufferedImage JavaDoc;
49 import java.awt.image.PixelGrabber JavaDoc;
50 import java.io.File JavaDoc;
51 import java.io.IOException JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.Locale JavaDoc;
54
55 import javax.imageio.IIOImage JavaDoc;
56 import javax.imageio.ImageIO JavaDoc;
57 import javax.imageio.ImageWriteParam JavaDoc;
58 import javax.imageio.ImageWriter JavaDoc;
59 import javax.imageio.plugins.jpeg.JPEGImageWriteParam JavaDoc;
60 import javax.imageio.stream.ImageOutputStream JavaDoc;
61
62 /**
63  * Utilities methods for image manipulation.
64  * It does not support writting of GIF images, but it
65  * can read from. GIF images will be saved as PNG.
66  *
67  * @author Rafael Steil
68  * @version $Id: ImageUtils.java,v 1.16 2006/02/12 17:25:58 rafaelsteil Exp $
69  */

70 public class ImageUtils
71 {
72     public static final int IMAGE_UNKNOWN = -1;
73     public static final int IMAGE_JPEG = 0;
74     public static final int IMAGE_PNG = 1;
75     public static final int IMAGE_GIF = 2;
76     
77     /**
78      * Resizes an image
79      *
80      * @param imgName The image name to resize. Must be the complet path to the file
81      * @param maxWidth The image's max width
82      * @param maxHeight The image's max height
83      * @return A resized <code>BufferedImage</code>
84      * @throws IOException If the file is not found
85      */

86     public static BufferedImage JavaDoc resizeImage(String JavaDoc imgName, int type, int maxWidth, int maxHeight) throws IOException JavaDoc
87     {
88         return resizeImage(ImageIO.read(new File JavaDoc(imgName)), type, maxWidth, maxHeight);
89     }
90     
91     /**
92      * Resizes an image.
93      *
94      * @param image The image to resize
95      * @param maxWidth The image's max width
96      * @param maxHeight The image's max height
97      * @return A resized <code>BufferedImage</code>
98      */

99     public static BufferedImage JavaDoc resizeImage(Image JavaDoc image, int type, int maxWidth, int maxHeight)
100     {
101         Dimension JavaDoc largestDimension = new Dimension JavaDoc(maxWidth, maxHeight);
102
103         // Original size
104
int imageWidth = image.getWidth(null);
105         int imageHeight = image.getHeight(null);
106         
107         float aspectRation = (float)imageWidth / imageHeight;
108         
109         if (imageWidth > maxWidth || imageHeight > maxHeight) {
110             if ((float)largestDimension.width / largestDimension.height > aspectRation) {
111                 largestDimension.width = (int)Math.ceil(largestDimension.height * aspectRation);
112             }
113             else {
114                 largestDimension.height = (int)Math.ceil(largestDimension.width / aspectRation);
115             }
116             
117             imageWidth = largestDimension.width;
118             imageHeight = largestDimension.height;
119         }
120         
121         return createBufferedImage(image, type, imageWidth, imageHeight);
122     }
123     
124     /**
125      * Saves an image to the disk.
126      *
127      * @param image The image to save
128      * @param toFileName The filename to use
129      * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG
130      * images, or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
131      * @return <code>false</code> if no appropriate writer is found
132      * @throws IOException
133      */

134     public static boolean saveImage(BufferedImage JavaDoc image, String JavaDoc toFileName, int type) throws IOException JavaDoc
135     {
136         return ImageIO.write(image, type == IMAGE_JPEG ? "jpg" : "png", new File JavaDoc(toFileName));
137     }
138     
139     /**
140      * Compress and save an image to the disk.
141      * Currently this method only supports JPEG images.
142      *
143      * @param image The image to save
144      * @param toFileName The filename to use
145      * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG
146      * images, or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
147      * @param compress Set to <code>true</code> if you want to compress the image.
148      * @return <code>false</code> if no appropriate writer is found
149      * @throws IOException
150      */

151     public static void saveCompressedImage(BufferedImage JavaDoc image, String JavaDoc toFileName, int type) throws IOException JavaDoc
152     {
153         if (type == IMAGE_PNG) {
154             throw new UnsupportedOperationException JavaDoc("PNG compression not implemented");
155         }
156         
157         ImageWriter JavaDoc writer = null;
158         
159         Iterator JavaDoc iter = ImageIO.getImageWritersByFormatName("jpg");
160         writer = (ImageWriter JavaDoc)iter.next();
161         
162         ImageOutputStream JavaDoc ios = ImageIO.createImageOutputStream(new File JavaDoc(toFileName));
163         writer.setOutput(ios);
164         
165         ImageWriteParam JavaDoc iwparam = new JPEGImageWriteParam JavaDoc(Locale.getDefault());
166         
167         iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
168         iwparam.setCompressionQuality(0.7F);
169         
170         writer.write(null, new IIOImage JavaDoc(image, null, null), iwparam);
171         
172         ios.flush();
173         writer.dispose();
174         ios.close();
175     }
176     
177     /**
178      * Creates a <code>BufferedImage</code> from an <code>Image</code>.
179      *
180      * @param image The image to convert
181      * @param w The desired image width
182      * @param h The desired image height
183      * @return The converted image
184      */

185     public static BufferedImage JavaDoc createBufferedImage(Image JavaDoc image, int type, int w, int h)
186     {
187         if (type == ImageUtils.IMAGE_PNG && hasAlpha(image)) {
188             type = BufferedImage.TYPE_INT_ARGB;
189         }
190         else {
191             type = BufferedImage.TYPE_INT_RGB;
192         }
193
194         BufferedImage JavaDoc bi = new BufferedImage JavaDoc(w, h, type);
195
196         Graphics JavaDoc g = bi.createGraphics();
197         g.drawImage(image, 0, 0, w, h, null);
198         g.dispose();
199         
200         return bi;
201     }
202     
203     /**
204      * Determines if the image has transparent pixels.
205      *
206      * @param image The image to check for transparent pixel.s
207      * @return <code>true</code> of <code>false</code>, according to the result
208      * @throws InterruptedException
209      */

210     public static boolean hasAlpha(Image JavaDoc image)
211     {
212         try {
213             PixelGrabber JavaDoc pg = new PixelGrabber JavaDoc(image, 0, 0, 1, 1, false);
214             pg.grabPixels();
215             
216             return pg.getColorModel().hasAlpha();
217         }
218         catch (InterruptedException JavaDoc e) {
219             return false;
220         }
221     }
222 }
223
Popular Tags