画像ファイルの縮小 戻る
はじめに

画像ファイルの縦横比を維持しながら指定したサイズに縮小したいという欲求がありましたのでやってみました。

実装イメージ

AWTにあるアフィン変換を利用しました。

画像が指定したサイズより小さい場合は、結果的に拡大になってしまい色が抜ける?ようなので、期待する動作はしませんでした。

AwtReductionExample.java import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Files; import javax.imageio.ImageIO; public class AwtReductionExample { private static void example(int newHeight, int newWidth, File src, File dst) throws IOException { BufferedImage image = reduction(newHeight, newWidth, src); Files.deleteIfExists(dst.toPath()); String string = dst.toString(); String ext = string.substring(string.lastIndexOf(".") + ".".length()); try { ImageIO.write(image, ext, dst); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { int newHeight = 450; int newWidth = 360; File src = new File("src.jpg"); File dst = new File("dst.png"); example(newHeight, newWidth, src, dst); } private static BufferedImage reduction(int height, int width, BufferedImage src) { int imageH = src.getHeight(); int imageW = src.getWidth(); double keisu = (double) imageH / height; if (imageW / keisu > width) { keisu = imageW / width; height = Double.valueOf(imageH / keisu).intValue(); } else { width = Double.valueOf(imageW / keisu).intValue(); } double newH = (double) height / imageH; double newW = (double) width / imageW; AffineTransform scale = AffineTransform.getScaleInstance(newW, newH); int type = AffineTransformOp.TYPE_BILINEAR; AffineTransformOp a = new AffineTransformOp(scale, type); BufferedImage dst = new BufferedImage(width, height, src.getType()); a.filter(src, dst); return dst; } private static BufferedImage reduction(int height, int width, File src) throws IOException { BufferedImage image = ImageIO.read(src); return reduction(height, width, image); } }