帮我用java写一个hutool等比例缩放
时间: 2023-05-31 13:07:25 浏览: 64
好的,我可以帮你使用Java编写一个hutool等比例缩放的程序。你可以使用Hutool工具类的ImageUtil类来实现等比例缩放。下面是代码示例:
```java
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.img.ImgUtil;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ResizeImage {
public static void main(String[] args) throws Exception {
// 原始图片路径
String sourceFilePath = "source.jpg";
// 缩放后图片路径
String targetFilePath = "target.jpg";
// 缩放比例
double scale = 0.5;
// 读取原始图片
BufferedImage sourceImage = ImageIO.read(FileUtil.file(sourceFilePath));
// 计算缩放后图片的宽度和高度
int width = (int) (sourceImage.getWidth() * scale);
int height = (int) (sourceImage.getHeight() * scale);
// 使用Hutool工具类的ImageUtil类进行缩放
BufferedImage targetImage = ImgUtil.scale(sourceImage, width, height, null);
// 将缩放后的图片保存到目标文件
ImageIO.write(targetImage, FileUtil.extName(targetFilePath), FileUtil.file(targetFilePath));
}
}
```
以上示例代码中,我们使用Hutool的ImgUtil类的scale方法实现了等比例缩放。你只需要将原始图片路径、缩放后图片路径、缩放比例替换成你自己的数据即可。如果需要对其他格式的图片进行缩放,只需要将代码中的扩展名改为相应格式即可。