导入依赖
<dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency>
代码
package com.asx.hyd.non.trs;import net.coobird.thumbnailator.Thumbnails;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;public class Test {public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {File file = new File("/Users/4paradigm/Desktop/11112.jpeg");compressImage(file);}public static InputStream compressImage(File file) {InputStream inputStream = null;try {FileInputStream fileInputStream = new FileInputStream(file);inputStream = fileInputStream;BufferedImage image = ImageIO.read(file);int width = image.getWidth();int height = image.getHeight();int newHeight = 0;int newWidth = 0;if (width > 900) {newWidth = 1360;newHeight = height * 1360 / width;//按指定大小把图片进行缩和放(会遵循原图高宽比例)ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ImageIO.write(image, "jpg", outputStream);byte[] bytes = outputStream.toByteArray();ByteArrayOutputStream out = new ByteArrayOutputStream(bytes.length);Thumbnails.of(inputStream).size(newWidth, newHeight).toOutputStream(out);//变为1360 * 对应比例,遵循原图比例缩放byte[] b = out.toByteArray();//将图片写到本地BufferedOutputStream stream=null;Random random = new Random(25);int i = random.nextInt(1000);String randomNum= String.valueOf(i);String tagFileName="/Users/4paradigm/Desktop/"+File.separator+"压缩后的照片"+randomNum+"22.jpeg";File fileout = new File(tagFileName);FileOutputStream fileOutputStream = new FileOutputStream(fileout);stream = new BufferedOutputStream(fileOutputStream);stream.write(b);stream.close();System.out.println("----------------压缩图片尺寸后大小-------------: " + b.length/1024+"K");inputStream = new ByteArrayInputStream(out.toByteArray());}} catch (IOException e) {e.printStackTrace();}return inputStream;}
}
Thumbnailator的简介和使用范例
https://www.jianshu.com/p/ad8af8214e60
https://blog.csdn.net/qq_34839150/article/details/109903432