How to Convert an Image to WebP Format with Java
A great way to improve the performance of a web page is to reduce the size of the image files it contains. WebP is an excellent next-gen format to use that doesn’t compromise quality, and you can easily convert dozens of common Image file formats to WebP using our WebP Format Conversion API.
Just follow instructions below to implement this API with ready-to-run Java code, or visit our website to find code available in several other common programming languages.
Let’s kick things off by installing the Java SDK with Maven. Add a reference to the pom.xml repository:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Then add a reference to the dependency in pom.xml:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>
To wrap things up, add in the import classes below, and include the callback function:
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.ConvertApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");ConvertApi apiInstance = new ConvertApi();
File imageFile = new File("/path/to/inputfile"); // File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try {
byte[] result = apiInstance.convertToWebP(imageFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertApi#convertToWebP");
e.printStackTrace();
}
And you’re all done — it’s just that easy. If you’re new to using Cloudmersive APIs, head to our website Home — Cloudmersive APIs to create a free account (with a limit of 800 API calls per month).