spring boot 图片压缩
时间: 2023-08-27 21:07:00 浏览: 44
可以使用Java的ImageIO类来实现图片压缩,下面是一个使用ImageIO实现图片压缩的示例代码:
```java
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageCompressor {
public static void main(String[] args) throws IOException {
String filePath = "path/to/image.jpg"; // 图片路径
double quality = 0.8; // 压缩质量,取值范围为0到1
compressImage(filePath, quality);
}
private static void compressImage(String filePath, double quality) throws IOException {
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
// 创建一个压缩后的图片缓冲区
BufferedImage compressedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = compressedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
// 写入到文件中
String compressedFilePath = "path/to/compressedImage.jpg"; // 压缩后的图片路径
ImageIO.write(compressedImage, "jpg", new File(compressedFilePath));
}
}
```
在上面的示例中,我们通过ImageIO读取了原始图片,并创建了一个压缩后的图片缓冲区。然后,我们使用Graphics2D将原始图片绘制到压缩后的图片缓冲区中,并使用ImageIO将压缩后的图片写入到文件中。
需要注意的是,压缩质量越高,压缩后的图片文件大小越大。另外,在实际使用中,我们还需要根据实际需求来决定压缩后的图片尺寸。