/**
* 根据指定大小压缩图片
*
* @param sourceFilePath 源图片路径 + 文件名(例 “D:\\image\\aa.jpg”)
* @param outFilePath 生成之后的图片路径 + 文件名(例 “D:\\image\\bb.jpg”)
* @return 压缩质量后的图片字节数组
*/
public static byte[] compressPicForScale(String sourceFilePath, String outFilePath) {
if (StringUtils.isEmpty(sourceFilePath)) {
return null;
}
// 指定图片大小,单位kb
long desFileSize = 512;
byte[] imageBytes = null;
try {
imageBytes = FileUtils.readFileToByteArray(new File(sourceFilePath));
if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
return imageBytes;
}
long srcSize = imageBytes.length;
long size = srcSize / 1024;
// 自动调节精度(经验数值)
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;
}
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();
}
if (outFilePath != null) {
FileUtils.writeByteArrayToFile(new File(outFilePath), imageBytes);
}
} catch (Exception e) {
e.printStackTrace();
}
return imageBytes;
}