java 等比缩小、放大图片尺寸

1.情景展示

在实际生活中,随着图片的质量和尺寸越来越大,我们在用图片进行网络传输的时候,往往受制于网速或者网站的影响,导致图片加载不出来;

没有办法的办法,就是:通过压缩图片的质量(清晰度)或者图片的尺寸(大小、像素),在java中,如何实现?

2.准备工作

我参考了网上通过java来实现的缩小图片尺寸的方法,不好使;

最终选择了Thumbnailator已经封装好的方法来调用,虽然已经是5前的代码了,但是,相较于java自身硬编码实现而言,依旧有很大优势。

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

3.解决方案

代码实现:

/*
 * 对图片进行等比缩小或放大
 * @attention:
 * Thumbnails可以将修改后的图片转换成OutputStream、BufferedImage或者File
 * @date: 2022/2/16 18:37
 * @param: imgInputPath 原图片路径
 * @param: imgOutputPath 图片输出路径
 * 可以更改原图片的格式(比如:原图片是png格式,我们可以在让其生成的时候变成非png格式)
 * @param: scale 图片比例
 * @return: boolean 成功、失败
 */
public static boolean compressPicBySize(String imgInputPath, String imgOutputPath, float scale) {
    boolean flag = false;
    String imgStatus = (scale > 1) ? "放大" : "缩小";
    try {
        Thumbnails.of(imgInputPath).scale(scale).toFile(imgOutputPath);
        // 成功
        flag = true;
        log.info("图片{}成功", imgStatus);
    } catch (IOException e) {
        e.printStackTrace();
        log.error("图片{}失败:{}", imgStatus, e.getMessage());
    }
    return flag;
}

测试:

public static void main(String[] args) {
    compressPicBySize("C:\\Users\\Marydon\\Desktop\\wxd.png", "C:\\Users\\Marydon\\Desktop\\wxd.bmp", 0.1F);// 缩小到原来的10%
}

我们可以看到:图片的尺寸相较于之前减少了90%。

 

如果想要,指定修改后的图片大小,可以使用下面这种方式:

查看代码

/*
 * 改变原图片尺寸
 * @attention:
 * @date: 2022/2/16 18:17
 * @param: imgPath 原图片路径
 * @param: width 改变后的图片宽度
 * @param: height 改变后的图片高度
 * @param: format 输出图片格式
 * @return: byte[] 改变后的图片流
 */
public static byte[] changeImgSize(String imgPath, int width, int height, String format) {
    byte[] changedImage = null;
    ByteArrayOutputStream out = null;
    format = StringUtils.isNotEmpty(format) ? format : "png";
    try {
        out = new ByteArrayOutputStream();
        Thumbnails.of(imgPath).size(width, height).outputFormat(format).toOutputStream(out);
        changedImage = out.toByteArray();
    } catch (IOException e) {
        log.error(e.getMessage());
    } finally {
        // 关闭流
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return changedImage;
}

最后,如果想要压缩图片体积,不想更改原图片尺寸的话,见文末推荐。 

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

 相关推荐:

posted @ 2022-02-16 18:56  Marydon  阅读(3356)  评论(0编辑  收藏  举报