准备工作
其实将图片转换为webp并不难,只需要调用google提供的转换器即可.转换器可以从这里下载.
转换器bin目录中包括以下工具
- cwebp:将图片转换为webp格式
- dwebp:解码webp
- gif2webp:gif动图转换为webp格式
代码
public class ImageFormatConverter {
/**
*
* @param inputFile
* 原图片路径
* @param outputFile
* webp路径
* @param quality
* 图片质量1-100
* @return
*/
private static boolean executeCWebp(String inputFile, String outputFile, Integer quality) {
boolean result = false;
ClassLoader cl = ImageFormatConverter.class.getClassLoader();
// 换成相应的路径
String cwebpPath = cl.getResource("com/test/cwebp.exe").getPath();
System.out.println("cwebpPath=" + cwebpPath);
try {
StringBuilder command = new StringBuilder(cwebpPath);
command.append(" -q " + (quality == 0 ? 75 : quality));
command.append(" " + inputFile);
command.append(" -o " + outputFile);
Runtime.getRuntime().exec(command.toString());
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
String inputFile = "H:\\image\\新建文件夹\\test.jpg";
String outputFile = "H:\\image\\新建文件夹\\test.webp";
if (executeCWebp(inputFile, outputFile, 75)) {
System.out.println("convert ok~");
} else {
System.out.println("sth wrong happened");
}
}
}
本文是参考的https://blog.csdn.net/lx542657544/article/details/77871524