意外にもメジャーなライブラリはないっぽい。
JDKのImageIOを使う。
import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; public class ImageReducer { private int width; private int height; public ImageReducer() { // nop } public ImageReducer(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public InputStream reduce(InputStream original) { BufferedImage image = null; try { image = ImageIO.read(original); } catch (IOException e) { // handle exception } BufferedImage shrinkImage = new BufferedImage(this.width, this.height, image.getType()); Graphics2D g2d = shrinkImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2d.drawImage(image, 0, 0, this.width, this.height, null); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { ImageIO.write(shrinkImage, "jpeg", outputStream); outputStream.flush(); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); outputStream.close(); return inputStream; } catch (IOException e) { // handle exception } } }
サムネイル作成のクオリティ向上 - 侍ズム #samuraismを参考にさせていただきました。