java 图片质量压缩

 1 /**
 2      * 图片质量压缩
 3      * @param file 要压缩的图片文件
 4      * @param input 文件输入流
 5      * @param quality 压缩质量(0-1)
 6      * @author ouyangyaxiong
 7      * 2016年2月23日 上午9:10:54
 8      * @throws IOException 
 9      *
10      */
11     public static void imgCompress(File file, InputStream input, float quality ) throws IOException{
12         Iterator<ImageWriter> imgWriters = ImageIO.getImageWritersByFormatName("jpg");
13         ImageWriter imgWriter = imgWriters.next();
14         ImageWriteParam param = imgWriter.getDefaultWriteParam();
15         param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
16         param.setCompressionQuality(quality);
17         OutputStream output = new FileOutputStream(file);//创建输出流
18         ImageOutputStream imgOutput = ImageIO.createImageOutputStream(output);
19         imgWriter.setOutput(imgOutput);
20         BufferedImage bufferedImg = ImageIO.read(input);
21         IIOImage iioimg = new IIOImage(bufferedImg, null, null);
22         imgWriter.write(null, iioimg, param);
23         output.close();
24         imgOutput.close();
25         imgWriter.dispose();
26         
27     }

注意:这里如果压缩透明背景的png图片会出现背景变黑的情况

参考:http://www.tutorialspoint.com/java_dip/image_compression_technique.htm,http://stackoverflow.com/questions/22812325/java-image-compression

posted @ 2016-02-23 09:57  until-u  阅读(578)  评论(0编辑  收藏  举报