以下是java压缩图片至指定大小的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import net.coobird.thumbnailator.Thumbnails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; /** * 图片压缩Utils * * @author 791202.com */ public class PicUtils { private static Logger logger = LoggerFactory.getLogger(PicUtils.class); // public static void main(String[] args) throws IOException { // byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\1.jpg")); // long l = System.currentTimeMillis(); // bytes = PicUtils.compressPicForScale(bytes, 300, "x");// 图片小于300kb // System.out.println(System.currentTimeMillis() - l); // FileUtils.writeByteArrayToFile(new File("D:\\dd1.jpg"), bytes); // } /** * 根据指定大小压缩图片 * * @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(); } logger.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb", imageId, srcSize / 1024, imageBytes.length / 1024); } catch (Exception e) { logger.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; } } |
代码里的imageId仅做日志输出用途,getAccuracy()方法是本人测试了几张图片后得出的经验数值(为了减少循环次数),也可以不用,直接传入压缩质量比即可。
0