代码如下:
public class test01 { private static int DPI = 300; public static void main(String[] args) { String path = "E:\002.jpg"; File file = new File(path); handleDpi(file, DPI, DPI); } /** * 改变图片DPI * @param file * @param xDensity 水平分辨率 * @param yDensity 垂直分辨率 */ public static void handleDpi(File file, int xDensity, int yDensity) { FileOutputStream fileOutputStream = null; try { BufferedImage image = ImageIO.read(file); fileOutputStream = new FileOutputStream(file); JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(fileOutputStream); JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image); jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH); jpegEncoder.setJPEGEncodeParam(jpegEncodeParam); jpegEncodeParam.setQuality(0.75f, false); jpegEncodeParam.setXDensity(xDensity); jpegEncodeParam.setYDensity(yDensity); jpegEncoder.encode(image, jpegEncodeParam); image.flush(); } catch (Exception e) { e.printStackTrace(); } finally { //关流 try { if(fileOutputStream!=null) { fileOutputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } } }