700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java根据指定大小kb压缩图片

java根据指定大小kb压缩图片

时间:2020-10-20 14:25:36

相关推荐

java根据指定大小kb压缩图片

/*** 根据指定大小压缩图片** @param sourceFilePath 源图片路径 + 文件名* @param outFilePath 生成之后的图片路径 + 文件名* @param desFileSize 指定图片大小,单位kb* @return 压缩质量后的图片字节数组*/public static byte[] compressPicForScale(String sourceFilePath, String outFilePath, long desFileSize) {if (StringUtils.isEmpty(sourceFilePath)) {return null;}byte[] imageBytes = null;try {imageBytes = FileUtils.readFileToByteArray(new File(sourceFilePath));if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {FileUtils.writeByteArrayToFile(new File(outFilePath), imageBytes);log.info("pressPicForScale 图片无需压缩,原始大小为:{}kb, sourceFilePath:{}", imageBytes.length / 1024, sourceFilePath);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) {log.info("pressPicForScale 图片压缩后大小:{}kb, sourceFilePath:{}", imageBytes.length / 1024, sourceFilePath);FileUtils.writeByteArrayToFile(new File(outFilePath), imageBytes);}} catch (Exception e) {log.error("图片压缩发生异常。sourceFilePath:{}, errorMessage:{}", sourceFilePath, e.getMessage(), e);}return imageBytes;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。