Java 压缩PNG JPG GIF 图片为webp格式

webp 做一种压缩体积更小的图片,如今在大部分浏览器中已经可以使用。

谷歌提供了sdk以及一些工具方便 我们使用webp格式,具体参考:官网

sejda-pdf/webp-imageio

在Java中,可以使用这个库:sejda-pdf/webp-imageio: Java ImageIO WebP support
其封装了多个系统的libwebp库版本,可以在Linux、Mac、Windows中使用,同时还发布在了Maven中。
但有一个问题,就是这个库,不能将GIF图片转为动态的webp文件。只会将GIF图片第一帧转为webp文件,也就是一张静态的图片。

简单使用:

public class ImageUtils {
    @Test
    public void test() throws IOException {
        compress("encoder.jpeg", "jpeg");
        compress("encoder.jpg", "jpg");
        compress("encoder.png", "png");
        // 不会转换动图,只会生成一张静态图片
        compress("encoder.gif", "gif");
    }
    public void compress(String input, String output) throws IOException {
        // Obtain an image to encode from somewhere
        File file = new File("src/test/resources/image/" + input);
        BufferedImage image = ImageIO.read(file);

        // Encode it as webp using default settings
        ImageIO.write(image, "webp", new File("target/" + output + ".webp"));
    }
}

我暂时没有找到提供GIF转webP动画的Java库。

阿里OSS图片处理

阿里oss支持将图片处理后保存到oss:[文档]
相比较上一种方式,支持图片格式更多,GIF图片也能很好的处理。
虽然,这样不会产生图片流量费用,但根据次数,可能产生数据处理费用。参见:[图片处理费用]

低规格(800×600以下):0.025元/千次
中规格(1600×1200以下):0.1元/千次

所以,可以在将图片上传到oss后,进行处理得到新图片,然后删除旧的图片。

        StringBuilder processBuildStr = new StringBuilder();
        Formatter styleFormatter = new Formatter(processBuildStr);
        String styleType = "image/format,webp";
        String targetImage = "result.webp";
        String sourceImage = "encoder.gif";
        styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                BinaryUtil.toBase64String(targetImage.getBytes()),
                BinaryUtil.toBase64String(bucketName.getBytes()));
        System.out.println(processBuildStr.toString());
        ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceImage, processBuildStr.toString());
        GenericResult processResult = ossClient.processObject(request);
        String json = null;
        try {
            json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
            processResult.getResponse().getContent().close();
            System.out.println(json);
        } catch (IOException e) {
            e.printStackTrace();
        }

调用 gif2webp

gif2webp 是Google提供的sdk中的一个可执行工具,使用起来也很简单。

gif2webp.exe .\gif.gif -o gif.webp

webp 压缩效率

我发现在无损压缩模式下,GIF格式转为webp,压缩效果并不是很好。

posted @ 2021-03-05 22:45  夕雨714  阅读(2337)  评论(0编辑  收藏  举报