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