java按比例壓縮圖片到指定的大小(kb、mb)
阿新 • • 發佈:2019-01-08
網上有很多壓縮圖片的方法,但是要麼就是不能壓縮到指定的大小以內,要麼就是要引用第三方的外掛,都不太符合我的要求,所以就想著自己寫一個方法來實現。這種方法有點不好就是如果圖片特別大則要進行多次判斷和讀取,可能時間會有點長,這要看實際情況,用的時候要自己注意。
實現的思路:讀取圖片大小→判斷是否符合要求大小→不符合就寬和高同時縮減10%→再進行判斷以此迴圈。
package com.goldgrid.compresspic; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class CompressPic3 { public static String CompressPic(String srcPath,String targetPath) throws Exception { double cutPercent=0.1; File file=new File(srcPath); BufferedImage bufferedImage=ImageIO.read(new FileInputStream(file)); int width=bufferedImage.getWidth(null); int height=bufferedImage.getHeight(null); long fileLength=file.length(); while((fileLength/1024)>=300) { width=(int)(width*(1-cutPercent)); height=(int)(height*(1-cutPercent)); BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height, null); // 繪製縮小後的圖 FileOutputStream deskImage = new FileOutputStream(targetPath); // 輸出到檔案流 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(deskImage); encoder.encode(tag); // 近JPEG編碼 deskImage.close(); File file1=new File(targetPath); BufferedImage bufferedImage1=ImageIO.read(new FileInputStream(file1)); width=bufferedImage1.getWidth(null); height=bufferedImage1.getHeight(null); fileLength=file1.length(); } return targetPath; } public static void main(String[] args) throws Exception { File file3=new File("d:/ZTestForWork/g.jpg"); BufferedImage bufferedImage3=ImageIO.read(new FileInputStream(file3)); System.out.println(file3.length()); int width3=bufferedImage3.getWidth(null); int height3=bufferedImage3.getHeight(null); System.out.println("壓縮前圖片的寬為:"+width3); System.out.println("壓縮前圖片的高為:"+height3); CompressPic3.CompressPic("d:/ZTestForWork/g.jpg", "d:/ZTestForWork/zipg.jpg"); /* String imgdist=reduceImg("d:/ZTestForWork/d.jpg", "d:/ZTestForWork/zipd.jpg", 1600, 1920, null);*/ File file4=new File("d:/ZTestForWork/zipg.jpg"); BufferedImage bufferedImage4=ImageIO.read(new FileInputStream(file4)); System.out.println(file4.length()); int width4=bufferedImage4.getWidth(null); int height4=bufferedImage4.getHeight(null); System.out.println("壓縮後圖片的寬為:"+width4); System.out.println("壓縮後圖片的高為:"+height4); } }