webp转成png、jpg、jpeg(亲测可用 ,无需安装动态链接库)

Webp是Google推出的一种新型图片格式,相比于 传统的PNG/JPG图片有着更小体积的优势,在Web中有着广泛的应用。由于Webp格式推出比较晚, Jdk 内置的图片编解码库对此并不支持。

网上给出的Java环境解决方案往往需要手动在java.library.path中安装对应的动态链接库,windows是dll文件,linux是so文件。这对于开发部署非常不方便。

本文提供一种无需手动安装动态链接库,同时可以方便处理Webp的解决方案

项目git链接https://github.com/nintha/webp-imageio-core

webp-imageio-core.jar包
链接:https://pan.baidu.com/s/1xfB2OrbvAFnEk_FNWE36rw
提取码:akzp

在项目中导入webp-imageio-core.jar包

webp编码

public static void main(String args[]) throws IOException {
    String inputPngPath = "test_pic/test.png";
    String inputJpgPath = "test_pic/test.jpg";
    String outputWebpPath = "test_pic/test_.webp";

    // Obtain an image to encode from somewhere
    BufferedImage image = ImageIO.read(new File(inputJpgPath));

    // Obtain a WebP ImageWriter instance
    ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();

    // Configure encoding parameters
    WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
    writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);

    // Configure the output on the ImageWriter
    writer.setOutput(new FileImageOutputStream(new File(outputWebpPath)));

    // Encode
    writer.write(null, new IIOImage(image, null, null), writeParam);
}

webp解码

public static void main(String args[]) throws IOException {
    String inputWebpPath = "test_pic/test.webp";
    String outputJpgPath = "test_pic/test_.jpg";
    String outputJpegPath = "test_pic/test_.jpeg";
    String outputPngPath = "test_pic/test_.png";

    // Obtain a WebP ImageReader instance
    ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

    // Configure decoding parameters
    WebPReadParam readParam = new WebPReadParam();
    readParam.setBypassFiltering(true);

    // Configure the input on the ImageReader
    reader.setInput(new FileImageInputStream(new File(inputWebpPath)));

    // Decode the image
    BufferedImage image = reader.read(0, readParam);

    ImageIO.write(image, "png", new File(outputPngPath));
    ImageIO.write(image, "jpg", new File(outputJpgPath));
    ImageIO.write(image, "jpeg", new File(outputJpegPath));

}

原文章:https://segmentfault.com/a/1190000016324137

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值