Thumbnailator是一款不可多得的处理图片的第三方工具包,它写法非常简单
问题描述:对接系统时需要向第三方系统传图片 但奈何第三方系统只接受200KB一下的图片,遂用到了thumbnailator
将使用主要方法记录一下 thumbnailator当然并不只是 剪裁、压缩他还可以旋转图片添加水印等图片操作 这里就不做研究
导入依赖
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.14</version>
</dependency>
上代码:
/**
* 根据指定大小压缩图片
*
* @param imageBytes 源图片字节数组
* @param desFileSize 指定图片大小,单位kb
* @param imageId 影像编号
* @return 压缩质量后的图片字节数组
*/
public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {
if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
return imageBytes;
}
//获取图片大小
long srcSize = imageBytes.length;
//设置压缩比例
double accuracy = getAccuracy(srcSize / 1024);
try {
//循环压缩 直到大小达到预定大小
while (imageBytes.length > desFileSize * 1024) {
//获取图片输入流
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
//设置图片输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream)
//设置缩略图缩放的大小
.scale(accuracy)
//缩略图输出质量
.outputQuality(accuracy)
//写入缩略图
.toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
}
log.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
imageId, srcSize, imageBytes.length / 1024);
} catch (Exception e) {
log.error("【图片压缩】msg=图片压缩失败!", e);
}
return imageBytes;
}
/**
* 根据指定大小剪裁图片 只是剪裁大小并不减少输出质量
* @param imageBytes 源图片字节数组
* @param wide 目标宽
* @param high 目标高
* @param imageId 影像编号
* @return 剪裁后的图片字节数组
*/
public static byte[] prunePic(byte[] imageBytes, int wide, int high, String imageId) {
try {
//获取图片的宽 高
BufferedImage read = ImageIO.read(new ByteArrayInputStream(imageBytes));
int width = read.getWidth();
int height = read.getHeight();
if (wide == 0 || high == 0 || (width <= wide && height <= high)) {
return imageBytes;
}
//获取图片输入流
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
//设置图片输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream)
//设置缩略图缩放的大小
.size(wide, high)
//缩略图输出质量
.outputQuality(1)
//安装指定的尺寸不遵循原图的大小
.keepAspectRatio(false)
//写入缩略图
.toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
log.info("【图片剪裁】imageId={} | 图片原宽={},高={} | 压缩后图片原宽={},高={}",
imageId, width, height, wide, high);
} catch (Exception e) {
log.error("【图片压缩】msg=图片压缩失败!", e);
}
return imageBytes;
}
/**
* 自动调节精度(经验数值)
*
* @param size 源图片大小
* @return 图片压缩质量比
*/
private static double getAccuracy(long size) {
double accuracy;
if (size < 900) {
accuracy = 0.85;
} else if (size < 2047) {
accuracy = 0.6;
} else if (size < 3275) {
accuracy = 0.44;
} else {
accuracy = 0.4;
}
return accuracy;
}
非常好用,你学废了吗