网上有很多压缩图片的方法,但是要么就是不能压缩到指定的大小以内,要么就是要引用第三方的插件,都不太符合我的要求,所以就想着自己写一个方法来实现。这种方法有点不好就是如果图片特别大则要进行多次判断和读取,可能时间会有点长,这要看实际情况,用的时候要自己注意。

      实现的思路:读取图片大小→判断是否符合要求大小→不符合就宽和高同时缩减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);
	}
}