Java 实现图片压缩、裁剪
1、引入依赖
<!--hutool 工具-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.11</version>
</dependency>
2、文件加工
注意:大部分的IO流是无法重复读取的,只能读取一次,再读取时,会抛出异常,我们这里使用ByteArrayOutputStream将流数据缓存到内存中,达到多次读取的目的
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
public class ImageUtil {
/**
* 图片加工方法
* <p>
* 支持的图片格式: BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif
*
* @param imgUrl 目标文件的地址
* @param outputStream 输出流
* @param width 图片裁剪后的宽度
* @param height 图片裁剪后的高度
* @throws IOException
*/
public static void imageProcess(String imgUrl, ByteArrayOutputStream outputStream,
int width, int height) throws IOException {
byte[] imgBytes = getImgBytes(imgUrl);
try (InputStream pojoInputStream = new ByteArrayInputStream(imgBytes);
InputStream readInputStream = new ByteArrayInputStream(imgBytes)) {
// 图片对象
BufferedImage bufferedImage = ImageIO.read(pojoInputStream);
// 高度
float imgHeight = Float.parseFloat(String.valueOf(bufferedImage.getHeight()));
// 缩放比例
float scale = 1 / (imgHeight / height);
// 矩形对象
Rectangle rectangle = new Rectangle(0, 0, width, height);
Img.from(readInputStream) // 读文件
.scale(scale) // 压缩
.cut(rectangle) // 裁剪
.write(outputStream);// 写文件
}
}
/**
* 获取文件二进制数据
*
* @param imgUrl 图片地址
* @return 二进制数据
* @throws IOException
*/
public static byte[] getImgBytes(String imgUrl) throws IOException {
try (InputStream inputStream = getImgInputStream(imgUrl);
ByteArrayOutputStream swapStream = new ByteArrayOutputStream()) {
int rc;
byte[] buff = new byte[100];
while ((rc = inputStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
return swapStream.toByteArray();
}
}
/**
* 获取文件输入流
*
* @param imgUrl 图片地址
* @return 输入流
* @throws IOException
*/
public static InputStream getImgInputStream(String imgUrl) throws IOException {
InputStream inputStream;
try {
// 网络图片
URL url = new URL(imgUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
inputStream = connection.getInputStream();
} catch (Exception urlException) {
// 本地图片
File file = FileUtil.file(imgUrl);
inputStream = Files.newInputStream(file.toPath());
}
return inputStream;
}
}
Img 方法详情 参考官网:官网
3、测试
public static void main(String[] args) {
try (ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
OutputStream outputStream = Files.newOutputStream(new File("D:/testImg.jpg").toPath())) {
String url = "https://cn.bing.com/th?id=OHR.SunriseCastle_ZH-CN6235928386_1920x1080.jpg";
ImageUtil.imageProcess(url, arrayOutputStream, 600, 1024);
arrayOutputStream.writeTo(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}