diff -r dec0dd934a64 -r 93fa6ce675e5 java/copy-image-resizer/src/cz/frantovo/copyImageResizer/SingleImageResizer.java --- a/java/copy-image-resizer/src/cz/frantovo/copyImageResizer/SingleImageResizer.java Mon Nov 17 20:23:58 2014 +0100 +++ b/java/copy-image-resizer/src/cz/frantovo/copyImageResizer/SingleImageResizer.java Mon Nov 17 20:38:38 2014 +0100 @@ -20,6 +20,7 @@ import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import java.util.logging.Logger; @@ -34,11 +35,27 @@ private static final Logger log = Logger.getLogger(SingleImageResizer.class.getName()); - public void resize(BufferedImage input, OutputStream output, SizeSpecification size, ImageFormat outputFormat) throws ResizeException { + /** + * + * @param input + * @param output + * @param size + * @param outputFormat + * @return whether image was resized → if false, you should just copy the image after calling + * this method. Image is resized if larger than requested size or if {@linkplain SizeSpecification#isResizeSmaller() + * }. + * @throws ResizeException + */ + public boolean resize(InputStream input, OutputStream output, SizeSpecification size, ImageFormat outputFormat) throws ResizeException { try { - BufferedImage resized = resize(input, size.getWidth(), size.getHeight(), input.getType()); - - ImageIO.write(resized, outputFormat.getFormat(), output); + BufferedImage image = readImage(input); + if (shouldResize(image, size)) { + BufferedImage resized = resize(image, size.getWidth(), size.getHeight(), image.getType()); + ImageIO.write(resized, outputFormat.getFormat(), output); + return true; + } else { + return false; + } } catch (IOException e) { throw new ResizeException("Error while resizing image", e); } @@ -71,6 +88,22 @@ return resized; } + private static BufferedImage readImage(InputStream input) throws ResizeException { + try { + return ImageIO.read(input); + } catch (IOException e) { + throw new ResizeException("Unable to read image from stream", e); + } + } + + private static boolean shouldResize(BufferedImage input, SizeSpecification requested) { + if (requested.isResizeSmaller()) { + return input.getHeight() != requested.getHeight() || input.getWidth() != requested.getWidth(); + } else { + return input.getHeight() > requested.getHeight() || input.getWidth() > requested.getWidth(); + } + } + public static enum ImageFormat { JPEG("jpg", Pattern.compile(".*\\.(jpg|jpeg)$", Pattern.CASE_INSENSITIVE)),