前言
最近在做图片上传的功能,图片大小需满足小于100K。
环境准备
需要引入依赖
<dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>
代码
public class LssTest {
public static void main(String[] args) throws Exception {
//加载本地测试图片
byte[] bytes = FileUtils.readFileToByteArray(new File("C:\\Users\\Administrator\\Desktop\\111.jpeg"));
byte[] compImg = compress(bytes, 100);
//byte[] compImg = commpressCycle(bytes, 100);
//输出压缩后的图片
try (OutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\222.jpeg")) {
out.write(compImg);
out.flush();
}
}
//方式一
public static byte[] compress(byte[] imgBytes, long fixedSize) throws Exception {
//大小判断
if (imgBytes == null || imgBytes.length <= 0 || imgBytes.length < fixedSize * 1024) {
return imgBytes;
}
long imgSize = imgBytes.length;
//获取压缩程度,取值0~1范围内
double quality = getQuality(imgSize / 1024);
try {
//循环压缩直到满足要求
while (imgBytes.length > fixedSize * 1024) {
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imgBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imgBytes.length)) {
Thumbnails.of(inputStream)
.scale(quality)
.outputQuality(quality)
.toOutputStream(outputStream);
imgBytes = outputStream.toByteArray();
}
}
System.out.println("图片压缩,原大小:" + imgSize / 1024 + "kb,压缩后大小:" +imgBytes.length / 1024 + "kb");
} catch (Exception e) {
System.out.println("图片压缩失败:" + e);
}
//返回结果
return imgBytes;
}
//方式二
public static byte[] commpressCycle(byte[] imgBytes, long fixedSize) throws IOException {
System.out.println("图片压缩,压缩前大小=" + imgBytes.length / 1024 + "kb");
if (imgBytes == null || imgBytes.length <= 0 || imgBytes.length < fixedSize * 1024) {
return imgBytes;
}
double quality = getQuality(imgBytes.length / 1024);
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imgBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imgBytes.length)) {
Thumbnails.of(inputStream)
.scale(quality)
.outputQuality(quality)
.toOutputStream(outputStream);
imgBytes = outputStream.toByteArray();
}
System.out.println("图片压缩,压缩后大小=" +imgBytes.length / 1024 + "kb");
return commpressCycle(imgBytes, fixedSize);
}
private static double getQuality(long size) {
if (size < 900) {
return 0.85;
} else if (size < 2047) {
return 0.6;
} else if (size < 3275) {
return 0.44;
}
return 0.4;
}
}