The bitbucket link of the original answer is not available anymore, but forks from the original repository can be found, in example: https://github.com/sejda-pdf/webp-imageio
I tried using the webp-imageio implementation from the mentioned github, but after 2 days of using it in production, I got a segmentation fault coming from the native library that crashed the whole server.
I resorted to using the compiled tools provided by google here: https://developers.google.com/speed/webp/download and do a small wrapper class to call the binaries.
In my case, I needed to convert from other images formats to webp, so I needed the "cwebp" binary. The wrapper I wrote is:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.concurrent.TimeUnit;
public class ImageWebpLibraryWrapper {
private static final String CWEBP_BIN_PATH = "somepath/libwebp-1.1.0-linux-x86-64/bin/cwebp";
public static boolean isWebPAvailable() {
if ( CWEBP_BIN_PATH == null ) {
return false;
}
return new File( CWEBP_BIN_PATH ).exists();
}
public static boolean convertToWebP( File imageFile, File targetFile, int quality ) {
Process process;
try {
process = new ProcessBuilder( CWEBP_BIN_PATH, "-q", "" + quality, imageFile.getAbsolutePath(), "-o",
targetFile.getAbsolutePath() ).start();
process.waitFor( 10, TimeUnit.SECONDS );
if ( process.exitValue() == 0 ) {
// Success
printProcessOutput( process.getInputStream(), System.out );
return true;
} else {
printProcessOutput( process.getErrorStream(), System.err );
return false;
}
} catch ( Exception e ) {
e.printStackTrace();
return false;
}
}
private static void printProcessOutput( InputStream inputStream, PrintStream output ) throws IOException {
try ( InputStreamReader isr = new InputStreamReader( inputStream );
BufferedReader bufferedReader = new BufferedReader( isr ) ) {
String line;
while ( ( line = bufferedReader.readLine() ) != null ) {
output.println( line );
}
}
}
An implementation around ImageIO is nicer, but I couldn't have a segmentation fault crashing the production server.
Sample usage:
public static void main( String args[] ) {
if ( !isWebPAvailable() ) {
System.err.println( "cwebp binary not found!" );
return;
}
File file = new File( "/home/xxx/Downloads/image_11.jpg" );
File outputFile = new File( "/home/xxx/Downloads/image_11-test.webp" );
int quality = 80;
if ( convertToWebP( file, outputFile, quality ) ) {
System.out.println( "SUCCESS" );
} else {
System.err.println( "FAIL" );
}
}