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 Common Documents to PNG Image Arrays in Java
  • How To Convert ODF Files to PDF in Java
  • How to Convert Excel and CSV Documents to HTML in Java
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Trending

  • Chaos Engineering Has a Blind Spot. Agentic AI Lives in It.
  • Every Cache Miss Is a Tiny Tax on Your Performance
  • Pragmatica Aether: Let Java Be Java
  • Event-Driven Pipelines With Apache Pulsar and Go
  1. DZone
  2. Data Engineering
  3. Databases
  4. Convert an MP4 Video to GIF in Java

Convert an MP4 Video to GIF in Java

Learn how to transform an MP4 video file into an easily digestible GIF with Java.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Feb. 08, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
5.3K Views

Join the DZone community and get the full member experience.

Join For Free

Between social media, ads, push notifications, and more, it has become increasingly difficult to capture and hold an individual’s attention. In the marketing world, if you want to cut through the noise and engage a customer, you must get creative. A strong storytelling strategy containing both relevant information and visual components has become a necessity. However, it is important to also be conscious of the duration of the content since attention spans drop significantly after 20-30 seconds of video. 

One popular marketing method that checks all the boxes is the Graphics Interchange Format, better known as GIF. GIFs are a great option due to their versatility, small file size, and ability to convey emotions better than a static image or lengthy video. To create a GIF, you simply need the video file you want to transform, and the right tools to perform the operation. 

In this article, we will provide easy-to-follow steps to leverage a Video Conversion API to convert an MP4 video file into a GIF in Java. 

To begin, we will install the SDK using Maven or Gradle. To install with Maven, add a reference to the repository in pom.xml:

XML
 




x


 
1
<repositories>
2
    <repository>
3
        <id>jitpack.io</id>
4
        <url>https://jitpack.io</url>
5
    </repository>
6
</repositories>


Then, add a reference to the dependency:

XML
 




xxxxxxxxxx
1


 
1
<dependencies>
2
<dependency>
3
    <groupId>com.github.Cloudmersive</groupId>
4
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
5
    <version>v3.54</version>
6
</dependency>
7
</dependencies>


If you prefer to install with Gradle, add this in to your root build.gradle at the end of the repositories:

Java
 




xxxxxxxxxx
1


 
1
allprojects {
2
    repositories {
3
        ...
4
        maven { url 'https://jitpack.io' }
5
    }
6
}


Next, add the dependency in build.gradle:

Java
 




xxxxxxxxxx
1


 
1
dependencies {
2
        implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
3
}


Once the installation is complete, you will add the imports to your controller, configure your API key, and call the convert to GIF function with the following code:

Java
 




xxxxxxxxxx
1
32


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.VideoApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

          
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15

          
16
VideoApi apiInstance = new VideoApi();
17
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
18
String fileUrl = "fileUrl_example"; // String | Optional; URL of a video file being used for conversion. Use this option for files larger than 2GB.
19
Integer maxWidth = 56; // Integer | Optional; Maximum width of the output video, up to the original video width. Defaults to 250 pixels, maximum is 500 pixels.
20
Integer maxHeight = 56; // Integer | Optional; Maximum height of the output video, up to the original video width. Defaults to 250 pixels, maximum is 500 pixels.
21
Boolean preserveAspectRatio = true; // Boolean | Optional; If false, the original video's aspect ratio will not be preserved, allowing customization of the aspect ratio using maxWidth and maxHeight, potentially skewing the video. Default is true.
22
Integer frameRate = 56; // Integer | Optional; Specify the frame rate of the output video. Defaults to 24 frames per second.
23
OffsetDateTime startTime = OffsetDateTime.now(); // OffsetDateTime | Optional; Specify the desired starting time of the GIF video in TimeSpan format.
24
OffsetDateTime timeSpan = OffsetDateTime.now(); // OffsetDateTime | Optional; Specify the desired length of the GIF video in TimeSpan format. Limit is 30 seconds. Default is 10 seconds.
25
try {
26
    byte[] result = apiInstance.videoConvertToGif(inputFile, fileUrl, maxWidth, maxHeight, preserveAspectRatio, frameRate, startTime, timeSpan);
27
    System.out.println(result);
28
} catch (ApiException e) {
29
    System.err.println("Exception when calling VideoApi#videoConvertToGif");
30
    e.printStackTrace();
31
}


To ensure the API runs correctly, the following parameters should be considered:

  • API Key (required) – to obtain a free API key, head to the Cloudmersive website and register for the basic account; this will give you access to up to 800 calls/month across our library of APIs.
  • File (required) – input the MP4 file on which to perform the operation.
  • File URL (optional) – URL of MP4 file being used for conversion. Best option for files larger than 2GB.
  • Max Width (optional) – maximum width of the output video; defaults to 250 pixels, max is 500 pixels.
  • Max Height (optional) – maximum height of the output video; defaults to 250 pixels, max is 500 pixels.
  • Preserve Aspect Ratio (optional) – if false, the original video’s aspect ratio will not be preserved, allowing customization but also potential skewing. Default setting is true.
  • Frame Rate (optional) – specify the frame rate of the output video; the default is 24 frames/second.
  • Start Time (optional) – specify the desired starting time of the GIF video in the TimeSpan format.
  • Time Span (optional) – specify the desired length of the GIF video in the TimeSpan format; the limit is 30 seconds, while the default is 10 seconds.

After this operation runs its course, you will be presented with your final GIF that you can utilize on your website, social media, or whatever medium you choose. To supply additional insight on the process, this particular API uses one API call per 10 MB of file size, and one API call per additional minute of processing over 5 minutes, but up to a maximum of 25 minutes total processing time. While we focused on transforming an MP4 file in this tutorial, this function can be used on a variety of video formats. 

GIF Java (programming language) Convert (command) API

Opinions expressed by DZone contributors are their own.

Related

  • How To Convert Common Documents to PNG Image Arrays in Java
  • How To Convert ODF Files to PDF in Java
  • How to Convert Excel and CSV Documents to HTML in Java
  • 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