How To Convert Image Files Into GIF or WebP Format Using Java
Learn how you can convert dozens of common image file types - including, but not limited to, PNG and JPG - into GIF and WebP format respectively.
Join the DZone community and get the full member experience.
Join For FreeIf we’re preparing to reformat an image for a specific purpose online, the new format we choose needs to accurately reflect the use case we envision. Otherwise, we’ll inadvertently stifle our own efficiency and, most importantly, run the risk of slowing down our web page loading speeds. The same can be said for most file format selections: we wouldn't use Microsoft Word to create a spreadsheet, and we wouldn't use Excel to write an essay (even though both technically can be done).
Choosing which image format to use requires us to think about the exact purpose we expect that file to serve. While the most ubiquitous formats we encounter online – namely JPG and PNG – provide well-known benefits for their respective use cases, they also come up short in certain key areas. For example, while the JPG format is widely used on website pages due to its high degree of compression (allowing web pages to run faster), this degree of compression sacrifices a meaningful amount of image quality, which we may not always be willing to lose. While PNG is a lossless format with built-in transparency features – perfect for displaying things like graphs, logos, and illustrations on a solid background – it notably lacks the ability to fit common online use cases such as image animation when the need arises.
For our more specialized formatting requirements, we can turn to other common image formats – both old and new – to accomplish our goals. GIF format is more than 30 years old – so old that it predates the original World Wide Web – but it uniquely allows for the creation of basic frame-by-frame animations, and it also enables web pages to load these animations at a much higher speed than comparable methods (e.g., traditional video plugins) can. WebP format – created just over 10 years ago by Google – is new enough that it still lacks upload compatibility with many websites, but its advantages are undeniable: not only does it afford more than 20% better compression than JPG and PNG, but it allows for both lossy and lossless compressions, ensuring we don’t always need to choose between image quality and web page loading speeds.
Given the differing use cases of these common image formats, converting between formats is a day-to-day requirement for many content professionals, and this need encourages the procurement of services that can perform conversions efficiently at scale. Below, I’ll demonstrate how you can take advantage of two API solutions that will help convert dozens of common image file types - including, but not limited to, PNG and JPG - into GIF and WebP format respectively.
Demonstration
Below, I’ve provided Java code examples to help you structure your API call to both of the image format conversion API solutions mentioned above. In addition, I’ve included instructions to help you install the Image Conversion API client using either Maven or Gradle (depending on your preference).
To begin the API client installation stage with Maven, our first step is to add a reference to the repository in pom.xml:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
After that, we’ll need to add the following dependency reference, which will allow JitPack to dynamically compile the library:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>
To install with Gradle instead, we need to first add the below snippet to the root build.gradle (at the end of repositories):
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Then, to wrap up, we need to add the dependency in build.gradle:
dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v4.25'
}
With our installation step complete, we can now add the imports for each API solution and call their respective functions directly afterward. Before we do so, I’d like to quickly point out that within each function provided below, there is an authentication field (below the imports, indicated by the code comments) that captures an API key input. After registering for a free-tier API key on the Cloudmersive website, you can simply copy and paste your API key string in the appropriate field, and you’ll have finished the API key authentication step.
To convert images to GIF format, we will call the below function. All we need to do is include our image file path where indicated next within the imageFile
field, and we’re all done:
// 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.convertToGif(imageFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertApi#convertToGif");
e.printStackTrace();
}
To convert images to WebP format, we will call the below function instead. Just like before, simply include your file path in the imageFile
field, and you’re finished:
// 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();
}
Each API solution can convert from dozens of common image formats. For your convenience, I’ve provided a full list of compatible input formats here:
- AAI, ART, ARW, AVS, BPG, BMP, BMP2, BMP3, BRF, CALS, CGM, CIN, CMYK, CMYKA, CR2, CRW, CUR, CUT, DCM, DCR, DCX, DDS, DIB, DJVU, DNG, DOT, DPX, EMF, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EXR, FAX, FIG, FITS, FPX, GIF, GPLT, GRAY, HDR, HEIC, HPGL, HRZ, ICO, ISOBRL, ISBRL6, JBIG, JNG, JP2, JPT, J2C, J2K, JPEG/JPG, JXR, MAT, MONO, MNG, M2V, MRW, MTV, NEF, ORF, OTB, P7, PALM, PAM, PBM, PCD, PCDS, PCL, PCX, PDF, PEF, PES, PFA, PFB, PFM, PGM, PICON, PICT, PIX, PNG, PNG8, PNG00, PNG24, PNG32, PNG48, PNG64, PNM, PPM, PSB, PSD, PTIF, PWB, RAD, RAF, RGB, RGBA, RGF, RLA, RLE, SCT, SFW, SGI, SID, SUN, SVG, TGA, TIFF, TIM, UIL, VIFF, VICAR, VBMP, WDP, WEBP, WPG, X, XBM, XCF, XPM, XWD, X3F, YCbCr, YCbCrA, YUV
Opinions expressed by DZone contributors are their own.
Comments