如何在Windows中使用java将webp转换为png或jpg



我让 bitbucket.org/luciad/webp-imageio 在Ubuntu中工作,但我无法让它在Windows中工作。

以下是我在 Ubuntu 中所做的:

  1. 下载 webp-imageio 和 libwebp 源代码(其他版本可以在 google webp 下载存储库中找到)。

  2. 使用 cmake 编译 libwebp 和 webp-imageio,webp-imageio 中有一个CMakefile.txt文件。也许您需要修改它?然后你会得到webp-imageio.jarlibwebp-imageio.so(它将在窗口中.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)

好吧,我通过使用谷歌预编译的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样本。

您也可以将

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";

最新更新