source: extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/transverse/util/ImagesUtil.java @ 9893

Last change on this file since 9893 was 9893, checked in by mlg, 13 years ago

Adds a better Exception management
new Exception : FileAlreadyExistsException.

File size: 7.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 *  jiwigo-ws-api Piwigo webservice access Api
32 *  Copyright (c) 2010-2011 Mael mael@le-guevel.com
33 *                All Rights Reserved
34 *
35 *  This library is free software. It comes without any warranty, to
36 *  the extent permitted by applicable law. You can redistribute it
37 *  and/or modify it under the terms of the Do What The Fuck You Want
38 *  To Public License, Version 2, as published by Sam Hocevar. See
39 *  http://sam.zoy.org/wtfpl/COPYING for more details.
40 */
41/**
42
43 * @author mael
44 *
45 */
46public class ImagesUtil {
47    /**
48     * Logger
49     */
50    public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
51            .getLog(ImagesUtil.class);
52
53    /**
54     * rotates an image
55     * @param image the image to rotate
56     * @param angle the angle of rotation
57     * @return the rotated image
58     */
59    public static BufferedImage rotate(BufferedImage image, double angle) {
60        GraphicsConfiguration gc = getDefaultConfiguration();
61        double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
62        int w = image.getWidth(), h = image.getHeight();
63        int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
64        int transparency = image.getColorModel().getTransparency();
65        BufferedImage result = gc.createCompatibleImage(neww, newh, transparency);
66        Graphics2D g = result.createGraphics();
67        g.translate((neww - w) / 2, (newh - h) / 2);
68        g.rotate(angle, w / 2, h / 2);
69        g.drawRenderedImage(image, null);
70        return result;
71    }
72
73    /**
74     * @return the graphics configuration
75     */
76    public static GraphicsConfiguration getDefaultConfiguration() {
77        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
78        GraphicsDevice gd = ge.getDefaultScreenDevice();
79        return gd.getDefaultConfiguration();
80    }
81
82    /**
83     * Writes an image in a file
84     * @param file the file
85     * @param bufferedImage the image
86     * @throws IOException
87     */
88    public static void writeImageToPNG(File file, BufferedImage bufferedImage) throws IOException {
89        ImageIO.write(bufferedImage, "png", file);
90    }
91
92    /**
93     * scales an image
94     * @param filePath the path to the file of the image
95     * @param tempName the name of the resulting file
96     * @param width the width
97     * @param height the height
98     * @return true if successful
99     * @throws IOException
100     * @throws Exception
101     */
102    public static boolean scale(String filePath, String tempName, int width, int height) throws IOException {
103        File file = new File(filePath);
104        InputStream imageStream = new BufferedInputStream(new FileInputStream(filePath));
105        Image image = (Image) ImageIO.read(imageStream);
106
107        double thumbRatio = (double) width / (double) height;
108        int imageWidth = image.getWidth(null);
109        int imageHeight = image.getHeight(null);
110        if (imageWidth < width || imageHeight < height) {
111            return false;
112        }
113        double imageRatio = (double) imageWidth / (double) imageHeight;
114        if (thumbRatio < imageRatio) {
115            height = (int) (width / imageRatio);
116        } else {
117            width = (int) (height * imageRatio);
118        }
119        BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
120        Graphics2D graphics2D = thumbImage.createGraphics();
121        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
122        graphics2D.drawImage(image, 0, 0, width, height, null);
123
124        //      ImageIO.write(thumbImage, "jpg", new FileOutputStream(System.getProperty("java.io.tmpdir") + "/" + tempName));
125        saveImage(System.getProperty("java.io.tmpdir") + "/" + tempName, thumbImage);
126        return true;
127
128    }
129
130    /**
131     * Save an image
132     * @param fileName the name of the file
133     * @param img the img
134     * @throws FileNotFoundException
135     * @throws IOException
136     */
137    private static void saveImage(String fileName, BufferedImage img) throws FileNotFoundException, IOException {
138        Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
139        ImageWriter writer = (ImageWriter) iter.next();
140        ImageWriteParam iwp = writer.getDefaultWriteParam();
141        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
142        iwp.setCompressionQuality(1);
143        File outputfile = new File(fileName);
144        FileImageOutputStream output = new FileImageOutputStream(outputfile);
145        writer.setOutput(output);
146        IIOImage outimage = new IIOImage(img, null, null);
147        writer.write(null, outimage, iwp);
148        writer.dispose();
149    }
150
151    // This method returns a buffered image with the contents of an image
152    public static BufferedImage toBufferedImage(Image image) {
153        if (image instanceof BufferedImage) {
154            return (BufferedImage) image;
155        }
156
157        // This code ensures that all the pixels in the image are loaded
158        image = new ImageIcon(image).getImage();
159
160        // Determine if the image has transparent pixels; for this method's
161        // implementation, see Determining If an Image Has Transparent Pixels
162        boolean hasAlpha = hasAlpha(image);
163
164        // Create a buffered image with a format that's compatible with the screen
165        BufferedImage bimage = null;
166        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
167        try {
168            // Determine the type of transparency of the new buffered image
169            int transparency = Transparency.OPAQUE;
170            if (hasAlpha) {
171                transparency = Transparency.BITMASK;
172            }
173
174            // Create the buffered image
175            GraphicsDevice gs = ge.getDefaultScreenDevice();
176            GraphicsConfiguration gc = gs.getDefaultConfiguration();
177            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
178        } catch (HeadlessException e) {
179            // The system does not have a screen
180        }
181
182        if (bimage == null) {
183            // Create a buffered image using the default color model
184            int type = BufferedImage.TYPE_INT_RGB;
185            if (hasAlpha) {
186                type = BufferedImage.TYPE_INT_ARGB;
187            }
188            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
189        }
190
191        // Copy image to buffered image
192        Graphics g = bimage.createGraphics();
193
194        // Paint the image onto the buffered image
195        g.drawImage(image, 0, 0, null);
196        g.dispose();
197
198        return bimage;
199    }
200
201    /**
202     *  This method returns true if the specified image has transparent pixels
203     * @param image the image to check
204     * @return true or false
205     */
206    public static boolean hasAlpha(Image image) {
207        // If buffered image, the color model is readily available
208        if (image instanceof BufferedImage) {
209            BufferedImage bimage = (BufferedImage) image;
210            return bimage.getColorModel().hasAlpha();
211        }
212
213        // Use a pixel grabber to retrieve the image's color model;
214        // grabbing a single pixel is usually sufficient
215        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
216        try {
217            pg.grabPixels();
218        } catch (InterruptedException e) {
219        }
220
221        // Get the image's color model
222        ColorModel cm = pg.getColorModel();
223        return cm.hasAlpha();
224    }
225
226}
Note: See TracBrowser for help on using the repository browser.