java 图片压缩变色问题

本文介绍了一种使用阿里巴巴SimpleImage库解决Java图片压缩过程中出现的颜色变化问题的方法。通过具体的测试代码示例,展示了如何避免压缩后图片颜色失真的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java图片压缩,有时由于图片自身的原因,如透明的PNG图、改alpha通道或四色图等。

压缩完了,会出现图片变色的情况。

如:

原图

 

压缩完:

 

尝试了很多方法,如JDK原生的方式及第三方组件java-image-scaling或thumbnailator都不解决问题。

后来采用阿里的SimpleImage解决。记录一下

SimpleImage github地址:https://github.com/alibaba/simpleimage
依赖jar:commons-io-2.4.jar
commons-lang.jar
commons-logging-1.1.1.jar
jai_codec-1.1.3.jar
jai_core-1.1.3.jar

测试代码:

    public static void main(String[] args) {
        // 原图
        File in = new File(
                "C:/Users/Administrator/Desktop/img/20170916/attachment_15055700026790.jpeg");
        // 目的图
        File out = new File(
                "C:/Users/Administrator/Desktop/img/20170916/attachment_15055700026790a.jpeg");
        FileInputStream input = null;
        FileOutputStream outStream = null;
        WriteRender wr = null;
        try {
            BufferedImage image = ImageIO.read(in);
            ScaleParameter scaleParam = new ScaleParameter(image.getWidth(),
                    image.getHeight()); // 将图像缩略到1024x1024以内,不足1024x1024则不做任何处理
            input = new FileInputStream(in);
            outStream = new FileOutputStream(out);
            ImageRender rr = new ReadRender(input);
            ImageRender sr = new ScaleRender(rr, scaleParam);
            wr = new WriteRender(sr, outStream);

            wr.render(); // 触发图像处理
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != input) {
                try {
                    input.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (null != outStream) {
                try {
                    outStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (wr != null) {
                try {
                    wr.dispose(); // 释放simpleImage的内部资源
                } catch (SimpleImageException ignore) {
                    // skip ...
                }
            }
        }
    }

引入的pom文件代码:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>simpleimage</artifactId>
    <version>1.2.3</version>
</dependency>

 

转载于:https://www.cnblogs.com/ncyhl/p/7554737.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值