Jan 30, 2013

Imgscalr and DPI

Posted Jan 30, 2013
In my previous post, I practically hailed imgscalr as, arguably, the best native Java library for resizing images or creating thumbnails.

This entry is a follow-up for setting the DPI of jpeg output of a Java image. Note that this only works if your output is in jpeg format:

BufferedImage img = ImageIO.read(new File("c:/img/test.jpg"));

BufferedImage scaledImg = Scalr.resize(img, Mode.AUTOMATIC, 640, 480);

File destFile = new File("c:/img/resized.jpg");

JPEGEncodeParam jpegEncodeParam = JPEGCodec.getDefaultJPEGEncodeParam(scaledImg);
final int dpi = 300;
jpegEncodeParam.setXDensity(dpi);
jpegEncodeParam.setYDensity(dpi);
jpegEncodeParam.setDensityUnit(JPEGDecodeParam.DENSITY_UNIT_DOTS_INCH);
jpegEncodeParam.setQuality(0.85f, false);

FileOutputStream fis = new FileOutputStream(destFile);
try {
  JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(fis);
  jpegEncoder.encode(scaledImg, jpegEncodeParam);
  fis.flush();
} finally {
  fis.close();
}

System.out.println("Done resizing");

No comments:

Post a Comment