source: extensions/jiwigo/trunk/src/main/java/fr/mael/jiwigo/transverse/util/ImagesUtil.java @ 6980

Last change on this file since 6980 was 6980, checked in by mlg, 14 years ago

Translation of the comments
French -> English

File size: 8.5 KB
Line 
1package fr.mael.jiwigo.transverse.util;
2
3import java.awt.Graphics;
4import java.awt.Graphics2D;
5import java.awt.GraphicsConfiguration;
6import java.awt.GraphicsDevice;
7import java.awt.GraphicsEnvironment;
8import java.awt.HeadlessException;
9import java.awt.Image;
10import java.awt.RenderingHints;
11import java.awt.Transparency;
12import java.awt.image.BufferedImage;
13import java.awt.image.ColorModel;
14import java.awt.image.PixelGrabber;
15import java.io.BufferedInputStream;
16import java.io.File;
17import java.io.FileInputStream;
18import java.io.FileNotFoundException;
19import java.io.IOException;
20import java.io.InputStream;
21import java.util.Iterator;
22
23import javax.imageio.IIOImage;
24import javax.imageio.ImageIO;
25import javax.imageio.ImageWriteParam;
26import javax.imageio.ImageWriter;
27import javax.imageio.stream.FileImageOutputStream;
28import javax.swing.ImageIcon;
29
30/**
31   Copyright (c) 2010, Mael
32   All rights reserved.
33
34   Redistribution and use in source and binary forms, with or without
35   modification, are permitted provided that the following conditions are met:
36    * Redistributions of source code must retain the above copyright
37      notice, this list of conditions and the following disclaimer.
38    * Redistributions in binary form must reproduce the above copyright
39      notice, this list of conditions and the following disclaimer in the
40      documentation and/or other materials provided with the distribution.
41    * Neither the name of jiwigo nor the
42      names of its contributors may be used to endorse or promote products
43      derived from this software without specific prior written permission.
44
45   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
46   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
47   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
48   DISCLAIMED. IN NO EVENT SHALL Mael BE LIABLE FOR ANY
49   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
50   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
52   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
53   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
54   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
55   
56 * @author mael
57 *
58 */
59public class ImagesUtil {
60    /**
61     * Logger
62     */
63    public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
64            .getLog(ImagesUtil.class);
65
66    /**
67     * rotates an image
68     * @param image the image to rotate
69     * @param angle the angle of rotation
70     * @return the rotated image
71     */
72    public static BufferedImage rotate(BufferedImage image, double angle) {
73        GraphicsConfiguration gc = getDefaultConfiguration();
74        double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
75        int w = image.getWidth(), h = image.getHeight();
76        int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
77        int transparency = image.getColorModel().getTransparency();
78        BufferedImage result = gc.createCompatibleImage(neww, newh, transparency);
79        Graphics2D g = result.createGraphics();
80        g.translate((neww - w) / 2, (newh - h) / 2);
81        g.rotate(angle, w / 2, h / 2);
82        g.drawRenderedImage(image, null);
83        return result;
84    }
85
86    /**
87     * @return
88     */
89    public static GraphicsConfiguration getDefaultConfiguration() {
90        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
91        GraphicsDevice gd = ge.getDefaultScreenDevice();
92        return gd.getDefaultConfiguration();
93    }
94
95    /**
96     * Writes an image in a file
97     * @param file the file
98     * @param bufferedImage the image
99     * @throws IOException
100     */
101    public static void writeImageToPNG(File file, BufferedImage bufferedImage) throws IOException {
102        ImageIO.write(bufferedImage, "png", file);
103    }
104
105    /**
106     * scales an image
107     * @param filePath the path to the file of the image
108     * @param tempName the name of the resulting file
109     * @param width the width
110     * @param height the height
111     * @return true if successful
112     * @throws Exception
113     */
114    public static boolean scale(String filePath, String tempName, int width, int height) throws Exception {
115        File file = new File(filePath);
116        InputStream imageStream = new BufferedInputStream(new FileInputStream(filePath));
117        Image image = (Image) ImageIO.read(imageStream);
118
119        double thumbRatio = (double) width / (double) height;
120        int imageWidth = image.getWidth(null);
121        int imageHeight = image.getHeight(null);
122        if (imageWidth < width || imageHeight < height) {
123            return false;
124        }
125        double imageRatio = (double) imageWidth / (double) imageHeight;
126        if (thumbRatio < imageRatio) {
127            height = (int) (width / imageRatio);
128        } else {
129            width = (int) (height * imageRatio);
130        }
131        BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
132        Graphics2D graphics2D = thumbImage.createGraphics();
133        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
134        graphics2D.drawImage(image, 0, 0, width, height, null);
135
136        //      ImageIO.write(thumbImage, "jpg", new FileOutputStream(System.getProperty("java.io.tmpdir") + "/" + tempName));
137        saveImage(System.getProperty("java.io.tmpdir") + "/" + tempName, thumbImage);
138        return true;
139
140    }
141
142    /**
143     * Save an image
144     * @param fileName the name of the file
145     * @param img the img
146     * @throws FileNotFoundException
147     * @throws IOException
148     */
149    private static void saveImage(String fileName, BufferedImage img) throws FileNotFoundException, IOException {
150        Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
151        ImageWriter writer = (ImageWriter) iter.next();
152        ImageWriteParam iwp = writer.getDefaultWriteParam();
153        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
154        iwp.setCompressionQuality(1);
155        File outputfile = new File(fileName);
156        FileImageOutputStream output = new FileImageOutputStream(outputfile);
157        writer.setOutput(output);
158        IIOImage outimage = new IIOImage(img, null, null);
159        writer.write(null, outimage, iwp);
160        writer.dispose();
161    }
162
163    // This method returns a buffered image with the contents of an image
164    public static BufferedImage toBufferedImage(Image image) {
165        if (image instanceof BufferedImage) {
166            return (BufferedImage) image;
167        }
168
169        // This code ensures that all the pixels in the image are loaded
170        image = new ImageIcon(image).getImage();
171
172        // Determine if the image has transparent pixels; for this method's
173        // implementation, see Determining If an Image Has Transparent Pixels
174        boolean hasAlpha = hasAlpha(image);
175
176        // Create a buffered image with a format that's compatible with the screen
177        BufferedImage bimage = null;
178        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
179        try {
180            // Determine the type of transparency of the new buffered image
181            int transparency = Transparency.OPAQUE;
182            if (hasAlpha) {
183                transparency = Transparency.BITMASK;
184            }
185
186            // Create the buffered image
187            GraphicsDevice gs = ge.getDefaultScreenDevice();
188            GraphicsConfiguration gc = gs.getDefaultConfiguration();
189            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
190        } catch (HeadlessException e) {
191            // The system does not have a screen
192        }
193
194        if (bimage == null) {
195            // Create a buffered image using the default color model
196            int type = BufferedImage.TYPE_INT_RGB;
197            if (hasAlpha) {
198                type = BufferedImage.TYPE_INT_ARGB;
199            }
200            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
201        }
202
203        // Copy image to buffered image
204        Graphics g = bimage.createGraphics();
205
206        // Paint the image onto the buffered image
207        g.drawImage(image, 0, 0, null);
208        g.dispose();
209
210        return bimage;
211    }
212
213    /**
214     *  This method returns true if the specified image has transparent pixels
215     * @param image the image to check
216     * @return true or false
217     */
218    public static boolean hasAlpha(Image image) {
219        // If buffered image, the color model is readily available
220        if (image instanceof BufferedImage) {
221            BufferedImage bimage = (BufferedImage) image;
222            return bimage.getColorModel().hasAlpha();
223        }
224
225        // Use a pixel grabber to retrieve the image's color model;
226        // grabbing a single pixel is usually sufficient
227        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
228        try {
229            pg.grabPixels();
230        } catch (InterruptedException e) {
231        }
232
233        // Get the image's color model
234        ColorModel cm = pg.getColorModel();
235        return cm.hasAlpha();
236    }
237
238}
Note: See TracBrowser for help on using the repository browser.