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

时间:2014-12-11 02:17:05

标签: java webp

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

以下是我在Ubuntu中所做的事情:

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

  2. 使用cmake编译libwebp和webp-imageio,webp-imageio中有一个CMakefile.txt文件。也许你需要修改它?然后,您将获得webp-imageio.jarlibwebp-imageio.so(在Windows中为.dll

  3. libwebp-imageio.so放入java项目本机库位置,并在java构建路径中放置webp-imageio.jar

  4. 然后,运行以下代码:

  5. 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。为什么?
    2. 以下是我的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)
      

1 个答案:

答案 0 :(得分:3)

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

    //the "dwebp.exe"'s path
    String str1 = "D:/workspace/demo/Test/libwebp-0.4.2-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样本。