3 * Copyright © 2014 František Kučera (frantovo.cz)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package cz.frantovo.copyImageResizer;
20 import java.awt.Graphics2D;
21 import java.awt.image.BufferedImage;
22 import java.io.IOException;
23 import java.io.OutputStream;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26 import java.util.regex.Pattern;
27 import javax.imageio.ImageIO;
31 * @author Ing. František Kučera (frantovo.cz)
33 public class SingleImageResizer {
35 private static final Logger log = Logger.getLogger(SingleImageResizer.class.getName());
37 public void resize(BufferedImage input, OutputStream output, SizeSpecification size, ImageFormat outputFormat) throws ResizeException {
39 BufferedImage resized = resize(input, size.getWidth(), size.getHeight(), input.getType());
41 ImageIO.write(resized, outputFormat.getFormat(), output);
42 } catch (IOException e) {
43 throw new ResizeException("Error while resizing image", e);
47 private BufferedImage resize(BufferedImage original, int maxWidth, int maxHeight, int type) {
51 float aspectRatio = (float) original.getWidth() / (float) original.getHeight();
53 if (aspectRatio > 1) {
55 height = Math.max(Math.round(maxWidth / aspectRatio), 1);
57 width = Math.max(Math.round(maxHeight * aspectRatio), 1);
61 if (type == BufferedImage.TYPE_CUSTOM) {
62 log.log(Level.FINE, "Setting default image type: from TYPE_CUSTOM to TYPE_INT_ARGB");
63 type = BufferedImage.TYPE_INT_ARGB;
66 BufferedImage resized = new BufferedImage(width, height, type);
67 Graphics2D g = resized.createGraphics();
68 g.drawImage(original, 0, 0, width, height, null);
74 public static enum ImageFormat {
76 JPEG("jpg", Pattern.compile(".*\\.(jpg|jpeg)$", Pattern.CASE_INSENSITIVE)),
77 PNG("png", Pattern.compile(".*\\.png$", Pattern.CASE_INSENSITIVE)),
78 GIF("gif", Pattern.compile(".*\\.gif$", Pattern.CASE_INSENSITIVE));
80 private final String format;
81 private final Pattern regex;
83 private ImageFormat(String format, Pattern regex) {
89 * @return format name for {@linkplain ImageIO#write(java.awt.image.RenderedImage, java.lang.String, java.io.File)
91 public String getFormat() {
95 public static ImageFormat getMatching(String fileName) {
96 for (ImageFormat type : values()) {
97 if (type.regex.matcher(fileName).matches()) {