Convert an MP4 Video to GIF in Java
Learn how to transform an MP4 video file into an easily digestible GIF with Java.
Join the DZone community and get the full member experience.
Join For FreeBetween 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:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Then, add a reference to the dependency:
xxxxxxxxxx
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.54</version>
</dependency>
</dependencies>
If you prefer to install with Gradle, add this in to your root build.gradle at the end of the repositories:
xxxxxxxxxx
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Next, add the dependency in build.gradle:
xxxxxxxxxx
dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
}
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:
xxxxxxxxxx
// 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.VideoApi;
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");
VideoApi apiInstance = new VideoApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
String fileUrl = "fileUrl_example"; // String | Optional; URL of a video file being used for conversion. Use this option for files larger than 2GB.
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.
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.
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.
Integer frameRate = 56; // Integer | Optional; Specify the frame rate of the output video. Defaults to 24 frames per second.
OffsetDateTime startTime = OffsetDateTime.now(); // OffsetDateTime | Optional; Specify the desired starting time of the GIF video in TimeSpan format.
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.
try {
byte[] result = apiInstance.videoConvertToGif(inputFile, fileUrl, maxWidth, maxHeight, preserveAspectRatio, frameRate, startTime, timeSpan);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling VideoApi#videoConvertToGif");
e.printStackTrace();
}
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.
Opinions expressed by DZone contributors are their own.
Comments