springboot压缩图片
时间: 2024-05-23 10:08:57 浏览: 138
Spring Boot提供了许多压缩图片的库,其中常用的有Thumbnails和imgscalr。这里以Thumbnails为例进行介绍。
Thumbnails是一个Java图片处理库,它可以压缩、剪切、旋转、缩放等操作。以下是使用Thumbnails压缩图片的步骤:
1. 添加依赖:在pom.xml中添加以下依赖:
```
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
```
2. 编写代码:在Java代码中使用Thumbnails压缩图片,示例代码如下:
```
import net.coobird.thumbnailator.Thumbnails;
import java.io.File;
import java.io.IOException;
public class ImageCompress {
public static void main(String[] args) throws IOException {
File sourceFile = new File("source.jpg");
File targetFile = new File("target.jpg");
Thumbnails.of(sourceFile).scale(0.5f).toFile(targetFile);
}
}
```
以上代码中,我们使用`Thumbnails.of()`方法加载源文件,然后使用`scale()`方法指定压缩比例,最后使用`toFile()`方法将压缩后的图片保存到目标文件中。
阅读全文
相关推荐
















