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.InputStream;
24 import java.io.OutputStream;
25 import java.util.regex.Pattern;
26 import javax.imageio.ImageIO;
30 * @author Ing. František Kučera (frantovo.cz)
32 public class SingleImageResizer {
34 public void resize(InputStream input, OutputStream output, ImageFormat outputFormat) throws ResizeException {
36 BufferedImage image = ImageIO.read(input);
37 BufferedImage resized = resize(image, 64, 64, image.getType());
39 ImageIO.write(resized, outputFormat.getFormat(), output);
40 } catch (IOException e) {
41 throw new ResizeException("Error while resizing image", e);
45 private BufferedImage resize(BufferedImage original, int maxWidth, int maxHeight, int type) {
49 float aspectRatio = (float) original.getWidth() / (float) original.getHeight();
51 if (aspectRatio > 1) {
53 height = Math.max(Math.round(maxWidth / aspectRatio), 1);
55 width = Math.max(Math.round(maxHeight * aspectRatio), 1);
59 BufferedImage resized = new BufferedImage(width, height, type);
60 Graphics2D g = resized.createGraphics();
61 g.drawImage(original, 0, 0, width, height, null);
67 public static enum ImageFormat {
69 JPEG("jpg", Pattern.compile(".*\\.(jpg|jpeg)$", Pattern.CASE_INSENSITIVE)),
70 PNG("png", Pattern.compile(".*\\.png$", Pattern.CASE_INSENSITIVE)),
71 GIF("gif", Pattern.compile(".*\\.gif$", Pattern.CASE_INSENSITIVE));
73 private final String format;
74 private final Pattern regex;
76 private ImageFormat(String format, Pattern regex) {
81 public String getFormat() {
85 public static ImageFormat getMatching(String fileName) {
86 for (ImageFormat type : values()) {
87 if (type.regex.matcher(fileName).matches()) {