public static void jpgCompress(String filePath) {
String filePath= "需要压缩的图片路径";
File file = new File(filePath);
float qality = (float)0.4;
try {
compressPictureByQality(file,qality);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 压缩图片
*
* @param file
* @param qality 参数qality是取值0~1范围内 代表压缩的程度
* @return
* @throws IOException
*/
public static File compressPictureByQality(File file, float qality) throws IOException {
BufferedImage src = null;
FileOutputStream out = null;
ImageWriter imgWrier;
ImageWriteParam imgWriteParams;
System.out.println("开始设定压缩图片参数");
// 指定写图片的方式为 jpg
imgWrier = ImageIO.getImageWritersByFormatName("png").next();
imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
// 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// 这里指定压缩的程度,参数qality是取值0~1范围内,
imgWriteParams.setCompressionQuality(qality);
imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
// ColorModel.getRGBdefault();
ColorModel colorModel = ImageIO.read(file).getColorModel();
imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(32, 32)));
logger.info("结束设定压缩图片参数");
if (!file.exists()) {
logger.error("Not Found Img File,文件不存在");
return null;
} else {
logger.info("图片转换前大小:{}", file.length() / 1024 + "kb");
src = ImageIO.read(file);
out = new FileOutputStream(file);
imgWrier.reset();
// 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何
// OutputStream构造
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
// 调用write方法,就可以向输入流写图片
imgWrier.write(null, new IIOImage(src, null, null),
imgWriteParams);
out.flush();
out.close();
logger.info("图片转换后大小", file.length() / 1024 + "kb");
return file;
}
}
以上供参!
网友评论