使用java来压缩图片
使用java来压缩图片,简单几句,清清爽爽
使用0.3的压缩比得到的结果如下(从2.8M压缩到268K,且图片的清晰度看不出明显差别):
package carlspringtest; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; /** * Compress JPEG File Example * * @author Krishna * */ public class CompressJPEGFileExample { public static void main(String[] args) throws FileNotFoundException, IOException{ File imageFile = new File("f:\\IMG_20151219_172146.jpg");//source File compressedImageFile = new File("f:\\compressed_file5.jpg");//result InputStream inputStream = new FileInputStream(imageFile); OutputStream outputStream = new FileOutputStream(compressedImageFile); float imageQuality = 0.3f; //Create the buffered image BufferedImage bufferedImage = ImageIO.read(inputStream); //Get image writers Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("jpg"); if (!imageWriters.hasNext()) throw new IllegalStateException("Writers Not Found!!"); ImageWriter imageWriter = (ImageWriter) imageWriters.next(); ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); //Set the compress quality metrics imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality(imageQuality); //Created image imageWriter.write(null, new IIOImage(bufferedImage, null, null), imageWriteParam); // close all streams inputStream.close(); outputStream.close(); imageOutputStream.close(); imageWriter.dispose(); } }
你要坚强,坚强的足以认识自己的弱点;你要勇敢,勇敢的足以面对自己的恐惧;你要堂堂正正。在遇到挫折时能够昂首而不背躬屈膝;你要能够面对掌声,在胜利时能够谦逊而不趾高气扬。真正的伟大直率真诚,真正的贤人虚怀若谷,真正的强者温文尔雅。——萨利·布什(林肯的继母教育林肯)