Slide 26
Slide 26 text
public byte[] scaleImage(InputStream is, int maxWidth, int maxHeight, ImageType type) throws IOException {
if (is == null) throw new IOException(String.format("Input stream is unavailable for image type %s",
type.getMime()));
BufferedImage source = ImageIO.read(is);
int width = source.getWidth();
int height = source.getHeight();
int scaledWidth = width;
int scaledHeight = height;
if (width > maxWidth) {
scaledWidth = maxWidth;
scaledHeight = (int) Math.ceil((scaledWidth * height * 1.0) / width);
}
if (scaledHeight > maxHeight) {
scaledHeight = maxHeight;
scaledWidth = (int) Math.ceil((scaledHeight * width * 1.0) / height);
}
source = (width < maxWidth || height < maxHeight)
? subImage(source, width, height, maxWidth, maxHeight)
: scale(source, width, height, scaledWidth, scaledHeight);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(source, type.getMime(), stream);
return stream.toByteArray();
}