Thumbnails图片截图上传压缩

png:png(便携式网络图形)是一种无损压缩的位图片形格式。
jpg,jpge:是有损压缩的图片形式,会产生迭代有损,在重复压缩和解码的过程中会不断丢失信息使图像质量下降。

使用Thumbnails压缩图片的话,输出png格式图片建议调整scale的值压缩图片分辨率,输出jpg图片建议调整outputFormat的值压缩图片质量。

下面进行一个简单测试:
找一个测试图片,下图大小为7.41MB

请添加图片描述请添加图片描述

Maven引入压缩jar包

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

以下是Java代码

public static void main(String[] args) {

    File file = new File("C:/Users/Administrator/Desktop/test/test.jpg");

    try {
        BigDecimal bigDecimal = new BigDecimal("1");

        for (int i = 0; i <= 9; i++) {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Thumbnails.of(file).scale(1f).outputFormat("jpg")
                .outputQuality(bigDecimal.doubleValue()).toOutputStream(baos);
            byte[] byteArray = baos.toByteArray();

            OutputStream os = new FileOutputStream("C:/Users/Administrator/Desktop/test/test"+                                           bigDecimal +".jpg");
            os.write(byteArray, 0, byteArray.length);
            os.flush();
            os.close();

            bigDecimal = bigDecimal.subtract(new BigDecimal("0.1"));
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

执行以后,生成以下图片:
随着outputQuality的值减小,生成的图片大小也越来越小

能日赚30的APP试玩平台推荐,亲测有效

请添加图片描述

但是我们查看test0.1.jpg的属性,只是大小改变,分辨率并未改变

请添加图片描述

请添加图片描述

posted @ 2022-09-11 10:43  田间稻草人  阅读(232)  评论(0编辑  收藏  举报