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

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

New features

  • When clicking on a category, the category is opened in a tab. When clicking on the same category again, no tab is opened but the previously opened tab is shown. The user can close the tabs (close current tab, close others, close all).
  • Ability to clip the images. There are still some bugs (unable to clip the images when zooming, and the rectangle stays when changing the image).
File size: 8.3 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     * Fonction de rotation d'une image
68     * @param image l'image à tourner
69     * @param angle l'angle de rotation
70     * @return l'image pivotée
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     * Ecriture d'une image dans un fichier png
97     * @param file le fichier
98     * @param bufferedImage l'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     * Mise à l'échelle d'une image
107     * @param filePath le chemin vers le fichier de l'image
108     * @param tempName le nom du fichier résultat
109     * @param width la largeur
110     * @param height la hauteur
111     * @return true si l'image a effectivement ete redimensionnee
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        //on n'agrandit pas l'image
123        if (imageWidth < width || imageHeight < height) {
124            return false;
125        }
126        double imageRatio = (double) imageWidth / (double) imageHeight;
127        if (thumbRatio < imageRatio) {
128            height = (int) (width / imageRatio);
129        } else {
130            width = (int) (height * imageRatio);
131        }
132        BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
133        Graphics2D graphics2D = thumbImage.createGraphics();
134        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
135        graphics2D.drawImage(image, 0, 0, width, height, null);
136
137        //      ImageIO.write(thumbImage, "jpg", new FileOutputStream(System.getProperty("java.io.tmpdir") + "/" + tempName));
138        saveImage(System.getProperty("java.io.tmpdir") + "/" + tempName, thumbImage);
139        return true;
140
141    }
142
143    private static void saveImage(String fileName, BufferedImage img) throws FileNotFoundException, IOException {
144        Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
145        ImageWriter writer = (ImageWriter) iter.next();
146        ImageWriteParam iwp = writer.getDefaultWriteParam();
147        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
148        iwp.setCompressionQuality(1);
149        File outputfile = new File(fileName);
150        FileImageOutputStream output = new FileImageOutputStream(outputfile);
151        writer.setOutput(output);
152        IIOImage outimage = new IIOImage(img, null, null);
153        writer.write(null, outimage, iwp);
154        writer.dispose();
155    }
156
157    // This method returns a buffered image with the contents of an image
158    public static BufferedImage toBufferedImage(Image image) {
159        if (image instanceof BufferedImage) {
160            return (BufferedImage) image;
161        }
162
163        // This code ensures that all the pixels in the image are loaded
164        image = new ImageIcon(image).getImage();
165
166        // Determine if the image has transparent pixels; for this method's
167        // implementation, see Determining If an Image Has Transparent Pixels
168        boolean hasAlpha = hasAlpha(image);
169
170        // Create a buffered image with a format that's compatible with the screen
171        BufferedImage bimage = null;
172        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
173        try {
174            // Determine the type of transparency of the new buffered image
175            int transparency = Transparency.OPAQUE;
176            if (hasAlpha) {
177                transparency = Transparency.BITMASK;
178            }
179
180            // Create the buffered image
181            GraphicsDevice gs = ge.getDefaultScreenDevice();
182            GraphicsConfiguration gc = gs.getDefaultConfiguration();
183            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
184        } catch (HeadlessException e) {
185            // The system does not have a screen
186        }
187
188        if (bimage == null) {
189            // Create a buffered image using the default color model
190            int type = BufferedImage.TYPE_INT_RGB;
191            if (hasAlpha) {
192                type = BufferedImage.TYPE_INT_ARGB;
193            }
194            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
195        }
196
197        // Copy image to buffered image
198        Graphics g = bimage.createGraphics();
199
200        // Paint the image onto the buffered image
201        g.drawImage(image, 0, 0, null);
202        g.dispose();
203
204        return bimage;
205    }
206
207    // This method returns true if the specified image has transparent pixels
208    public static boolean hasAlpha(Image image) {
209        // If buffered image, the color model is readily available
210        if (image instanceof BufferedImage) {
211            BufferedImage bimage = (BufferedImage) image;
212            return bimage.getColorModel().hasAlpha();
213        }
214
215        // Use a pixel grabber to retrieve the image's color model;
216        // grabbing a single pixel is usually sufficient
217        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
218        try {
219            pg.grabPixels();
220        } catch (InterruptedException e) {
221        }
222
223        // Get the image's color model
224        ColorModel cm = pg.getColorModel();
225        return cm.hasAlpha();
226    }
227
228}
Note: See TracBrowser for help on using the repository browser.