越来越多的网站采用了webp格式的图片,webp占用空间小,传送更快,画质不降低。经常会遇到图片格式转换的需求,我们可以借助第三方的包,通过Java实现来PG/PNG图片转换为WEBP格式,以及WEBP转换成JPG/PNG格式。
1.maven项目依赖
在pom.xml加入下面的内容
org.sejda.imageiowebp-imageio0.1.6
2.代码分享
package com.zx.tool.image.webp;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import javax.imageio.IIOImage;import javax.imageio.ImageIO;import javax.imageio.ImageReader;import javax.imageio.ImageWriter;import javax.imageio.stream.FileImageInputStream;import javax.imageio.stream.FileImageOutputStream;import com.luciad.imageio.webp.WebPReadParam;import com.luciad.imageio.webp.WebPWriteParam;public class Webp2Jpeg {public static void main(String[] args) {String oldfile = "D:\\手机遥遥领先.webp";String newfile = "D:\\十项黑科技.jpg";webp2jpg(oldfile,newfile);}/** * webp格式图片转成JPG格式 * @param oldfilec:/1.test.webp * @param newfilec:/1.test.jpg * @return */public static void webp2jpg(String oldfile, String newfile){// 创建WebP ImageReader实例ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();// 配置解码参数WebPReadParam readParam = new WebPReadParam();readParam.setBypassFiltering(true);// 在ImageReader设置读取的原文件try {reader.setInput(new FileImageInputStream(new File(oldfile)));// 解码图像BufferedImage image = reader.read(0, readParam);// 设置输入文件的格式和文件名ImageIO.write(image, "jpg", new File(newfile)); // 这里也可以使用其他图片格式,但是格式和文件名后缀要保持一致System.out.println("webp文件转成png格式成功");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/** * JPG格式图片转成webp格式(也可以是其他格式图片) * @param oldfilec:/1.test.jpg * @param newfilec:/1.test.webp * @return */public static void jpg2webp(String oldfile, String newfile){try {// 获取原始文件的编码BufferedImage image = ImageIO.read(new File(oldfile));// 创建WebP ImageWriter实例ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();// 配置编码参数WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());// 设置压缩模式writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);// 配置ImageWriter输出writer.setOutput(new FileImageOutputStream(new File(newfile)));// 进行编码,重新生成新图片writer.write(null, new IIOImage(image, null, null), writeParam);System.out.println("jpg文件转成webp格式成功");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}