DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Convert a PDF to Text (TXT) Using Java
  • How To Validate Names Using Java
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Trending

  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • Why Good Models Fail After Deployment
  • Can Claude Skills Replace Playwright Agents? A Practical View for QA Engineers
  1. DZone
  2. Data Engineering
  3. Databases
  4. How To Convert Image Files Into GIF or WebP Format Using Java

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.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Oct. 31, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
9.8K Views

Join the DZone community and get the full member experience.

Join For Free

If 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:

Java
 
// 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:

Java
 
// 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
API Apache Maven Illustration Use case authentication Convert (command) Dependency Java (programming language) Repository (version control) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert a PDF to Text (TXT) Using Java
  • How To Validate Names Using Java
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook