如何在Windows上使用Java将Webp转换为PNG或JPG?

4
我成功地在Ubuntu中使用了 bitbucket.org/luciad/webp-imageio,但是我无法在Windows上使用它。
以下是我在Ubuntu中的操作步骤:
1. 下载webp-imageio和libwebp源代码(其他版本可以在google webp下载存储库中找到)。 2. 使用cmake编译libwebp和webp-imageio,在webp-imageio中有一个CMakefile.txt文件。可能需要修改它。然后你将得到webp-imageio.jarlibwebp-imageio.so(在windows中将是.dll)。 3. 将libwebp-imageio.so放在Java项目本地库位置,并将webp-imageio.jar放在Java构建路径中。 4. 然后运行下面的代码:
File file1= new File("/home/rtm/Desktop/xixi.webp");  
File file2= new File("/home/rtm/Desktop/haha.png");  

System.loadLibrary("webp-imageio");
try {  
    BufferedImage im = ImageIO.read(file1);   
    ImageIO.write(im, "png", file2);  
} catch (IOException e) {  
    e.printStackTrace();  
}  
  1. 然后,我使用cmake和mingw-w64在Windows上编译(webp-imageio.jarlibwebp-imageio.dll)。 但是,ImageIO.read(file1);返回null。为什么?

这是我在Windows上的代码:

File file1 = new File("D://workspace//demo//Test//unnamed.webp");
File file2 = new File("D://workspace//demo//Test//xixi.png");

System.loadLibrary("webp-imageio");
try {
    //FileUtils.copyFile(file1, file2);
    BufferedImage im = ImageIO.read(file1);
    ImageIO.write(im, "png", file2);
} catch (Exception e) {
    e.printStackTrace();
}

以下是异常堆栈信息:

java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(Unknown Source)
at javax.imageio.ImageIO.getWriter(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)

你尝试使用双斜杠了吗?看起来像是路径问题...Java通常需要双斜杠。//home//rtm//Desktop//xixi.webp - Petro
如果它抛出了空指针异常,那么xixi.webp的位置可能是错误的。尝试使用反斜杠,我在Windows文件中使用反斜杠。"/home" 是Linux目录,你的Windows目录是否命名为 /home 或者是 C:/home,或者嵌套在它自己的目录中? - Petro
"image == null" 是因为 ImageIO.read(file1) 返回了 null,我说过 "imageio 无法解析 .webp",可能是编译 webp-imageio.jar 和 libwebp-imageio.dll 的问题。 - RTM
我注意到的第一件奇怪的事情是:你应该使用一个斜杠或双反斜杠,而不是双斜杠:\。 - Daniel
好的,我尝试过“\”,它也无法工作。显然问题不在那里。 - RTM
显示剩余3条评论
2个回答

9

嗯,我通过使用谷歌预编译的WebP工具和库解决了这个问题。我们只需要libWebp,你可以在http://downloads.webmproject.org/releases/webp/index.html中找到与你的系统匹配的其他版本。 然后在Java中执行它,这就是代码:

    //the "dwebp.exe"'s path
    String str1 = "D:/workspace/demo/Test/libwebp-1.3.0-windows-x64/bin/dwebp.exe";
    //the webp picture's path
    String str2 = "D:/workspace/demo/Test/unnamed.webp";
    //the converted picture's path
    String str3 = "D:/workspace/demo/Test/xixi.png";
    args = new String[]{str1, str2, "-o", str3};

    try {
        Runtime.getRuntime().exec(args);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

它可以将webp转换为PNG、JPEG、TIFF、WebP或原始的Y'CbCr样本。


0
你也可以将PNG转换为WebP,按照@RMT提供的示例更改'dwebp.exe'为'cwebp.exe',这对我有效。
//the "cwebp.exe"'s path
     String str1 = "C:\\test\\bin\\cwebp.exe";
//the png picture's path
     String str2 = "C:\\test\\xixi.png";
//the converted picture's path
    String str3 = "C:\\test\\xixie.webp";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接