packagecom.hzxc.groupactivity.server.util;importjava.awt.image.BufferedImage;import java.io.*;importjava.math.BigDecimal;importjavax.imageio.ImageIO;importnet.coobird.thumbnailator.Thumbnails;importorg.apache.commons.lang3.StringUtils;/*** Created by hdwang on 2018/12/13.*/
public classPicUtils {public static voidmain(String[] args) {
PicUtils.commpressPicForScale("/Users/hdwang/Downloads/1.jpg","/Users/hdwang/Downloads/1_s.jpg", 1000, 0.8,750,1334); //图片小于1000kb
}/*** 根据指定大小和指定精度压缩图片
*
*@paramsrcPath
* 源图片地址
*@paramdesPath
* 目标图片地址
*@paramdesFileSize
* 指定图片大小,单位kb
*@paramaccuracy
* 精度,递归压缩的比率,建议小于0.9
*@paramdesMaxWidth
* 目标最大宽度
*@paramdesMaxHeight
* 目标最大高度
*@return目标文件路径*/
public staticString commpressPicForScale(String srcPath, String desPath,long desFileSize, double accuracy,int desMaxWidth,intdesMaxHeight) {if (StringUtils.isEmpty(srcPath) ||StringUtils.isEmpty(srcPath)) {return null;
}if (!newFile(srcPath).exists()) {return null;
}try{
File srcFile= newFile(srcPath);long srcFileSize =srcFile.length();
System.out.println("源图片:" + srcPath + ",大小:" + srcFileSize / 1024
+ "kb");//获取图片信息
BufferedImage bim =ImageIO.read(srcFile);int srcWidth =bim.getWidth();int srcHeight =bim.getHeight();//先转换成jpg
Thumbnails.Builder builder = Thumbnails.of(srcFile).outputFormat("jpg");//指定大小(宽或高超出会才会被缩放)
if(srcWidth > desMaxWidth || srcHeight >desMaxHeight) {
builder.size(desMaxWidth, desMaxHeight);
}else{//宽高均小,指定原大小
builder.size(srcWidth,srcHeight);
}//写入到内存
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流(写入到内存)
builder.toOutputStream(baos);//递归压缩,直到目标文件大小小于desFileSize
byte[] bytes =commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);//输出到文件
File desFile = newFile(desPath);
FileOutputStream fos= newFileOutputStream(desFile);
fos.write(bytes);
fos.close();
System.out.println("目标图片:" + desPath + ",大小" + desFile.length() / 1024 + "kb");
System.out.println("图片压缩完成!");
}catch(Exception e) {
e.printStackTrace();return null;
}returndesPath;
}private static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throwsIOException {//File srcFileJPG = new File(desPath);
long srcFileSizeJPG =bytes.length;//2、判断大小,如果小于500kb,不压缩;如果大于等于500kb,压缩
if (srcFileSizeJPG <= desFileSize * 1024) {returnbytes;
}//计算宽高
BufferedImage bim = ImageIO.read(newByteArrayInputStream(bytes));int srcWdith =bim.getWidth();int srcHeigth =bim.getHeight();int desWidth = newBigDecimal(srcWdith).multiply(newBigDecimal(accuracy)).intValue();int desHeight = newBigDecimal(srcHeigth).multiply(newBigDecimal(accuracy)).intValue();
ByteArrayOutputStream baos= new ByteArrayOutputStream(); //字节输出流(写入到内存)
Thumbnails.of(newByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);returncommpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
}
}