user3603284 user3603284 - 5 years ago 479
Java Question

How to change the DPI from 96 to 300 of an image in java after resizing?

I have a JPEG image, after resizing it, I want to change the DPI from 96 to 300 of same image in Java. My code:

public BufferedImage resizeImageWithHint(BufferedImage originalImage, int type) {
BufferedImage resizedImage = new BufferedImage(177, 177, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, 177, 177, null);
g.dispose();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g.translate(4, 4); return resizedImage; }

Answer Source
BufferedImage image = ImageIO.read(new File(path));
JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(new File(path)));
JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
jpegEncoder.setJPEGEncodeParam(jpegEncodeParam); jpegEncodeParam.setQuality(0.75f, false);
jpegEncodeParam.setXDensity(300); jpegEncodeParam.setYDensity(300);
jpegEncoder.encode(image, jpegEncodeParam);
image.flush();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download