通过 Thumbnails 压缩图片后转 base64
BASE64Encoder base64Encoder =new BASE64Encoder(); //存放图片转码后的数据 String base64EncoderImg = ""; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); Thumbnails.of(img.getInputStream()).scale(0.8F).toOutputStream(out); base64EncoderImg = base64Encoder.encode(out.toByteArray()); } catch (Exception e) { e.printStackTrace(); }
import org.springframework.util.Base64Utils;
base64EncoderImg = Base64Utils.encodeToString(out.toByteArray());
Thumbnails依赖
<dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>