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

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

Modifications to try to have a better image quality on resizing

File size: 8.1 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    private static final GraphicsConfiguration CONFIGURATION = GraphicsEnvironment.getLocalGraphicsEnvironment()
54            .getDefaultScreenDevice().getDefaultConfiguration();
55
56    public static void main(String[] args) throws IOException {
57        scale("/home/mael/Bureau/test.png", "test4.jpg", 1999, 1999);
58    }
59
60    /**
61     * rotates an image
62     * @param image the image to rotate
63     * @param angle the angle of rotation
64     * @return the rotated image
65     */
66    public static BufferedImage rotate(BufferedImage image, double angle) {
67        GraphicsConfiguration gc = getDefaultConfiguration();
68        double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
69        int w = image.getWidth(), h = image.getHeight();
70        int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
71        int transparency = image.getColorModel().getTransparency();
72        BufferedImage result = gc.createCompatibleImage(neww, newh, transparency);
73        Graphics2D g = result.createGraphics();
74        g.translate((neww - w) / 2, (newh - h) / 2);
75        g.rotate(angle, w / 2, h / 2);
76        g.drawRenderedImage(image, null);
77        return result;
78    }
79
80    /**
81     * @return the graphics configuration
82     */
83    public static GraphicsConfiguration getDefaultConfiguration() {
84        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
85        GraphicsDevice gd = ge.getDefaultScreenDevice();
86        return gd.getDefaultConfiguration();
87    }
88
89    /**
90     * Writes an image in a file
91     * @param file the file
92     * @param bufferedImage the image
93     * @throws IOException
94     */
95    public static void writeImageToPNG(File file, BufferedImage bufferedImage) throws IOException {
96        ImageIO.write(bufferedImage, "png", file);
97    }
98
99    /**
100     * scales an image
101     * @param filePath the path to the file of the image
102     * @param tempName the name of the resulting file
103     * @param width the width
104     * @param height the height
105     * @return true if successful
106     * @throws IOException
107     * @throws Exception
108     */
109    public static boolean scale(String filePath, String tempName, int width, int height) throws IOException {
110        InputStream imageStream = new BufferedInputStream(new FileInputStream(filePath));
111        Image image = (Image) ImageIO.read(imageStream);
112
113        double thumbRatio = (double) width / (double) height;
114        int imageWidth = image.getWidth(null);
115        int imageHeight = image.getHeight(null);
116        if (imageWidth < width || imageHeight < height) {
117            return false;
118        }
119        double imageRatio = (double) imageWidth / (double) imageHeight;
120        if (thumbRatio < imageRatio) {
121            height = (int) (width / imageRatio);
122        } else {
123            width = (int) (height * imageRatio);
124        }
125        //      BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
126        BufferedImage thumbImage = createCompatibleImage(ImageIO.read(new File(filePath)), width, height);
127        Graphics2D graphics2D = thumbImage.createGraphics();
128        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
129        graphics2D.drawImage(image, 0, 0, width, height, null);
130        graphics2D.dispose();
131        //      ImageIO.write(thumbImage, "jpg", new FileOutputStream(System.getProperty("java.io.tmpdir") + "/" + tempName));
132        saveImage(System.getProperty("java.io.tmpdir") + "/" + tempName, thumbImage);
133        return true;
134
135    }
136
137    public static BufferedImage createCompatibleImage(BufferedImage image, int width, int height) {
138        return CONFIGURATION.createCompatibleImage(width, height, image.getTransparency());
139    }
140
141    /**
142     * Save an image
143     * @param fileName the name of the file
144     * @param img the img
145     * @throws FileNotFoundException
146     * @throws IOException
147     */
148    private static void saveImage(String fileName, BufferedImage img) throws FileNotFoundException, IOException {
149        Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
150        ImageWriter writer = (ImageWriter) iter.next();
151        ImageWriteParam iwp = writer.getDefaultWriteParam();
152        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
153        iwp.setCompressionQuality(1);
154        File outputfile = new File(fileName);
155        FileImageOutputStream output = new FileImageOutputStream(outputfile);
156        writer.setOutput(output);
157        IIOImage outimage = new IIOImage(img, null, null);
158        writer.write(null, outimage, iwp);
159        writer.dispose();
160    }
161
162    // This method returns a buffered image with the contents of an image
163    public static BufferedImage toBufferedImage(Image image) {
164        if (image instanceof BufferedImage) {
165            return (BufferedImage) image;
166        }
167
168        // This code ensures that all the pixels in the image are loaded
169        image = new ImageIcon(image).getImage();
170
171        // Determine if the image has transparent pixels; for this method's
172        // implementation, see Determining If an Image Has Transparent Pixels
173        boolean hasAlpha = hasAlpha(image);
174
175        // Create a buffered image with a format that's compatible with the screen
176        BufferedImage bimage = null;
177        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
178        try {
179            // Determine the type of transparency of the new buffered image
180            int transparency = Transparency.OPAQUE;
181            if (hasAlpha) {
182                transparency = Transparency.BITMASK;
183            }
184
185            // Create the buffered image
186            GraphicsDevice gs = ge.getDefaultScreenDevice();
187            GraphicsConfiguration gc = gs.getDefaultConfiguration();
188            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
189        } catch (HeadlessException e) {
190            // The system does not have a screen
191        }
192
193        if (bimage == null) {
194            // Create a buffered image using the default color model
195            int type = BufferedImage.TYPE_INT_RGB;
196            if (hasAlpha) {
197                type = BufferedImage.TYPE_INT_ARGB;
198            }
199            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
200        }
201
202        // Copy image to buffered image
203        Graphics g = bimage.createGraphics();
204
205        // Paint the image onto the buffered image
206        g.drawImage(image, 0, 0, null);
207        g.dispose();
208
209        return bimage;
210    }
211
212    /**
213     *  This method returns true if the specified image has transparent pixels
214     * @param image the image to check
215     * @return true or false
216     */
217    public static boolean hasAlpha(Image image) {
218        // If buffered image, the color model is readily available
219        if (image instanceof BufferedImage) {
220            BufferedImage bimage = (BufferedImage) image;
221            return bimage.getColorModel().hasAlpha();
222        }
223
224        // Use a pixel grabber to retrieve the image's color model;
225        // grabbing a single pixel is usually sufficient
226        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
227        try {
228            pg.grabPixels();
229        } catch (InterruptedException e) {
230        }
231
232        // Get the image's color model
233        ColorModel cm = pg.getColorModel();
234        return cm.hasAlpha();
235    }
236
237}
Note: See TracBrowser for help on using the repository browser.