@Slf4j
public class CompressImageUtil {
public static byte[] commpressPicForScale(byte[] src,long desFileSize, double accuracy,int desMaxWidth,int desMaxHeight) {
byte[] des=null;
if (src==null) {
return null;
}
try {
long srcFileSize = src.length;
log.info("源图片:大小:" + srcFileSize / 1024 + "kb");
ByteArrayInputStream in = new ByteArrayInputStream(src);
BufferedImage bim = ImageIO.read(in);
int srcWidth = bim.getWidth();
int srcHeight = bim.getHeight();
Thumbnails.Builder builder = Thumbnails.of(bim).outputFormat("jpg");
if(srcWidth > desMaxWidth || srcHeight > desMaxHeight) {
builder.size(desMaxWidth, desMaxHeight);
}else{
builder.size(srcWidth,srcHeight);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
builder.toOutputStream(baos);
des = commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
log.info("目标图片:大小" + des.length / 1024 + "kb");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return des;
}
private static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException {
long srcFileSizeJPG = bytes.length;
if (srcFileSizeJPG <= desFileSize * 1024) {
return bytes;
}
BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
int srcWdith = bim.getWidth();
int srcHeigth = bim.getHeight();
int desWidth = new BigDecimal(srcWdith).multiply(
new BigDecimal(accuracy)).intValue();
int desHeight = new BigDecimal(srcHeigth).multiply(
new BigDecimal(accuracy)).intValue();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
}
public static void main(String[] arg) throws IOException {
byte[] imgBytes = ImageUtil.image2byte("https://a.jpg");
commpressPicForScale(imgBytes,1000,(long)0.8,700,1000);
}
public static String getChinese(String content){
String txtcontent = content.replaceAll("</?[^>]+>", "");
txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");
txtcontent = txtcontent.replaceAll(" ", "");
txtcontent = txtcontent.replaceAll("&", "");
return txtcontent;
}