java/copy-image-resizer/src/cz/frantovo/copyImageResizer/SingleImageResizer.java
author František Kučera <franta-hg@frantovo.cz>
Mon, 17 Nov 2014 20:38:38 +0100
changeset 15 93fa6ce675e5
parent 10 a5a723467a39
child 17 505031965440
permissions -rw-r--r--
wasResized is decided in SingleImageResizer
     1 /**
     2  * copy-image-resizer
     3  * Copyright © 2014 František Kučera (frantovo.cz)
     4  *
     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.
     9  *
    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.
    14  *
    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/>.
    17  */
    18 package cz.frantovo.copyImageResizer;
    19 
    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.logging.Level;
    26 import java.util.logging.Logger;
    27 import java.util.regex.Pattern;
    28 import javax.imageio.ImageIO;
    29 
    30 /**
    31  *
    32  * @author Ing. František Kučera (frantovo.cz)
    33  */
    34 public class SingleImageResizer {
    35 
    36 	private static final Logger log = Logger.getLogger(SingleImageResizer.class.getName());
    37 
    38 	/**
    39 	 *
    40 	 * @param input
    41 	 * @param output
    42 	 * @param size
    43 	 * @param outputFormat
    44 	 * @return whether image was resized → if false, you should just copy the image after calling
    45 	 * this method. Image is resized if larger than requested size or if {@linkplain SizeSpecification#isResizeSmaller()
    46 	 * }.
    47 	 * @throws ResizeException
    48 	 */
    49 	public boolean resize(InputStream input, OutputStream output, SizeSpecification size, ImageFormat outputFormat) throws ResizeException {
    50 		try {
    51 			BufferedImage image = readImage(input);
    52 			if (shouldResize(image, size)) {
    53 				BufferedImage resized = resize(image, size.getWidth(), size.getHeight(), image.getType());
    54 				ImageIO.write(resized, outputFormat.getFormat(), output);
    55 				return true;
    56 			} else {
    57 				return false;
    58 			}
    59 		} catch (IOException e) {
    60 			throw new ResizeException("Error while resizing image", e);
    61 		}
    62 	}
    63 
    64 	private BufferedImage resize(BufferedImage original, int maxWidth, int maxHeight, int type) {
    65 
    66 		int width;
    67 		int height;
    68 		float aspectRatio = (float) original.getWidth() / (float) original.getHeight();
    69 
    70 		if (aspectRatio > 1) {
    71 			width = maxWidth;
    72 			height = Math.max(Math.round(maxWidth / aspectRatio), 1);
    73 		} else {
    74 			width = Math.max(Math.round(maxHeight * aspectRatio), 1);
    75 			height = maxHeight;
    76 		}
    77 
    78 		if (type == BufferedImage.TYPE_CUSTOM) {
    79 			log.log(Level.FINER, "Setting default image type: from TYPE_CUSTOM to TYPE_INT_ARGB");
    80 			type = BufferedImage.TYPE_INT_ARGB;
    81 		}
    82 
    83 		BufferedImage resized = new BufferedImage(width, height, type);
    84 		Graphics2D g = resized.createGraphics();
    85 		g.drawImage(original, 0, 0, width, height, null);
    86 		g.dispose();
    87 
    88 		return resized;
    89 	}
    90 
    91 	private static BufferedImage readImage(InputStream input) throws ResizeException {
    92 		try {
    93 			return ImageIO.read(input);
    94 		} catch (IOException e) {
    95 			throw new ResizeException("Unable to read image from stream", e);
    96 		}
    97 	}
    98 
    99 	private static boolean shouldResize(BufferedImage input, SizeSpecification requested) {
   100 		if (requested.isResizeSmaller()) {
   101 			return input.getHeight() != requested.getHeight() || input.getWidth() != requested.getWidth();
   102 		} else {
   103 			return input.getHeight() > requested.getHeight() || input.getWidth() > requested.getWidth();
   104 		}
   105 	}
   106 
   107 	public static enum ImageFormat {
   108 
   109 		JPEG("jpg", Pattern.compile(".*\\.(jpg|jpeg)$", Pattern.CASE_INSENSITIVE)),
   110 		PNG("png", Pattern.compile(".*\\.png$", Pattern.CASE_INSENSITIVE)),
   111 		GIF("gif", Pattern.compile(".*\\.gif$", Pattern.CASE_INSENSITIVE));
   112 
   113 		private final String format;
   114 		private final Pattern regex;
   115 
   116 		private ImageFormat(String format, Pattern regex) {
   117 			this.format = format;
   118 			this.regex = regex;
   119 		}
   120 
   121 		/**
   122 		 * @return format name for {@linkplain ImageIO#write(java.awt.image.RenderedImage, java.lang.String, java.io.File)
   123 		 */
   124 		public String getFormat() {
   125 			return format;
   126 		}
   127 
   128 		public static ImageFormat getMatching(String fileName) {
   129 			for (ImageFormat type : values()) {
   130 				if (type.regex.matcher(fileName).matches()) {
   131 					return type;
   132 				}
   133 			}
   134 			return null;
   135 		}
   136 	}
   137 }