用Java如何把图片处理到指定大小?
项目开发中,经常遇到图片上传功能,发现如果图片比较大时,在查看、预览、下载速度会特别慢,考虑到浪费流量以及文件服务器的存储空间,决定在后端优化处理完再上传,以减少存储空间与优化传输速率。这里使用Java自带的ImageIO进行处理分享给大家。
1、Java常见的图像处理插件
- Java自带的
ImageIO
- Google的Thumbnails(实现也相对于比较简单,功能也更加丰富)-- 可自行了解
本文将使用两种工具实现图片的压缩,在保持清晰度的前提下,去减少图片的大小,以达到减少存储空间与提高文件传输速率的目的。
2、图片压缩优化实战
以压缩JPG文件为例,详见下图现有接近40MB的jpg文件。
Google的Thumbnails
1.先引入依赖
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.20</version>
</dependency>
代码实现
@Test
public void test4() {
String filePath = "/static/dist.jpg"; // 文件路径
ClassPathResource resource = new ClassPathResource(filePath);
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
int i = 0;
for (float quality = 0.9f; quality > 0.0f; quality -= 0.1f) {
String path = StrUtil.format("src/main/resources/static/compression_dist_{}.jpg", ++i);
File distFile = new File(path);
Thumbnails.of(inputStream)
.scale(quality)
.outputQuality(1) // 输出的图片质量
.toFile(distFile);
long length = distFile.length();
if (length / 1024 <= 5120) { // 压缩至5MB左右
System.out.println(length / (1024 * 1024) + "MB");
break;
}
if (ObjectUtil.isNull(inputStream) || inputStream.available() == 0) {
inputStream = new FileInputStream(distFile);
}
distFile.delete();
}
} catch (IOException ex) {
log.error(ex.getMessage());
ex.printStackTrace();
} finally {
IoUtil.close(inputStream);
}
}
Java自带的ImageIO
@Test
public void test() {
// 1.准备jpg图像编写器
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = writers.next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // 设置压缩模式
// 2.准备源文件(要压缩的文件)
String filePath = "/static/dist.jpg"; // 文件路径
ClassPathResource resource = new ClassPathResource(filePath);
// 3.指定目标压缩文件大小(这里按KB计算)
int targetSize = 5120; // 5MB
try (InputStream inputStream = resource.getInputStream()) {
int available = inputStream.available();
// 4.判断源文件大小是否小于目标压缩大小
if ((available / 1000) <= targetSize) {
log.error(StrUtil.format("[{}] 文件小于 {}KB 无需压缩!", resource.getFilename(), targetSize));
return;
}
BufferedImage inputImage = ImageIO.read(inputStream);
// 设定压缩比例(接近目标文件大小)
for (float quality = 0.95f; quality > 0.0f; quality -= 0.05f) {
String path = StrUtil.format("src/main/resources/static/compression_dist_{}.jpg", quality);
File distFile = new File(path);
// 输出参数
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(distFile);
writer.setOutput(imageOutputStream);
writeParam.setCompressionQuality(quality); // 设置压缩比例(0-1之间)
writer.write(null, new IIOImage(inputImage, null, null), writeParam);
// 是否接近于目标大小
if (distFile.length() / 1024 <= targetSize) {
IoUtil.close(imageOutputStream);
break;
}
distFile.delete();
}
} catch (IOException ex) {
log.error(ex.getMessage());
ex.printStackTrace();
}
// IoUtil.close(imageOutputStream);
writer.dispose();
}
再来看压缩效果(dist.jpg为原文件),可以打开文件进行对比(清晰度基本没啥变化)