JAVA压缩apng动图并保留动画效果

作者:丘杨(如需转载请注明出处)

背景:

网页中图片和视频资源较多且文件较大,导致网页加载非常慢。图片和视频均存储于minio中,前端会直接访问minio链接

故尝试后端通过压缩图片,前端只展示压缩后的图片来优化加载速度过慢的问题。

其中遇到的一大难题是png动图经过压缩后失去了动图效果。

失败案例总结:

优化图片文件过大导致网页加载慢问题中对于压缩png动图失败案例总结icon-default.png?t=N7T8http://t.csdnimg.cn/HC5Gd

成功案例:

maven:

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-imaging</artifactId>
    <version>23.9</version>
    <classifier>jdk16</classifier>
</dependency>

代码:

import com.aspose.imaging.ColorPaletteHelper;
import com.aspose.imaging.Image;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.fileformats.png.PngColorType;
import com.aspose.imaging.imageoptions.ApngOptions;

    public void addCompression(String fileName) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream = readService.getFileInputStream(bucketName, fileName);
        String compressName = "compress_" + fileName;
        try (Image image = Image.load(inputStream)) {
            ApngOptions options = new ApngOptions();
            options.setCompressionLevel(9);
            options.setProgressive(true);
            options.setColorType(PngColorType.IndexedColor);
            options.setPalette(ColorPaletteHelper.getCloseImagePalette((RasterImage) image, 1 << 8));
            image.save(byteArrayOutputStream, options);
            byte[] imgBytes = byteArrayOutputStream.toByteArray();
            writeService.upload(imgBytes, compressName);
        } catch (Exception e) {
            throw e;
        }    
    }

结果:

png文件由1.6mb压缩至389.3kb,并且保留动画效果

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

樱曦何归

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值