How to Convert a Video to GIF using Python?

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:

Input 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())

Output GIF

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.

Edit this Code Example in the Video Editor

Easily design your own video templates using the online editor. Then, export your templates as JSON and integrate them into your Python application to create any kind of video – completely through code.

Related Python Video Editing Questions

Start automating today

Start with a full-featured trial with 50 credits, no credit card required.
Get started for free