There are several reasons why you'd want to create a GIF from a video. One of the most common reasons is to make a short GIF snippet out of an MP4. If you want to do this using Python, you'll need an API that supports GIF output. Fortunately, it only takes a few lines of code:
import requests
json = {
'source': {
'output_format': 'gif',
'gif_quality': 'best',
'gif_compression': 100,
'frame_rate': '10 fps',
'duration': 3,
'elements': [
{
'type': 'video',
'source': 'https://cdn.creatomate.com/demo/bird.mp4'
}
]
}
}
response = requests.post(
'https://api.creatomate.com/v1/renders',
headers={
# Find your API key under 'Project Settings' in your account:
# https://creatomate.com/docs/api/rest-api/authentication
'Authorization': 'Bearer Your-API-Key',
'Content-Type': 'application/json',
},
json=json
)
# Wait a minute, then visit the URL provided in the response:
print(response.json())
How it works: You do not need to install any additional libraries; simply import the "requests" package, which is included with your Python installation. You can now set up a GIF composition. Here, define a single video element with its "source" parameter set to a video URL.
To generate a GIF file, choose "gif" as the output format. If you want to generate a different format, remember that the API also supports "jpg", "png", and "mp4" output formats.
If you're exporting a GIF, you can tweak the "gif_quality" and "gif_compression" options. Use "best" or "fast" for "gif_quality" depending on whether you care more about quality or speed. The "gif_compression" parameter can go from 0 to 200 and compresses the file further, but a high value may cause artifacts.
For this example, "frame_rate" is set to 10 frames per second and GIF duration is set to 3 seconds. You can specify the "width" and "height" properties if you want the GIF cropped to a specific size. Here, we're using the input video's dimensions.
If you want to overlay a logo or caption on top of your GIF, you can do that as well. The related examples below will show you how, but make sure you also try the video editor too. This online tool enables you to design your own GIF overlays and export the corresponding code for use in your Python application.