Convert MP4 video to GIF using PHP

GIFs are a popular image format for animation on websites, social media and messaging apps. Common use cases are memes or for displaying screen recordings on a web page or email.

Often the source footage for an animated GIF starts life as a video such as an MP4 file. This means you need a way to convert the MP4 to GIF format. This can be done with free online tools or meme generators, but if you want to automatically convert multiple MP4 files to GIFs or integrate a video to GIF feature into your application or workflow, you might want a way to automate the process using code.

The Shotstack video editing API makes it easy to automatically convert MP4 video to GIF using any programming language. For this tutorial however, I want to show you how to convert MP4 to GIF using PHP.

The Shotstack API and SDK

Shotstack provides a cloud-based video editing API. Rendering videos is a time-consuming process that can take hours to edit and generate at scale. Fortunately, Shotstack's infrastructure allows for the simultaneous rendering of multiple media files, such as video, audio, and GIFs, in minutes.

Shotstack also has a number of SDK’s in different languages including a PHP video editing SDK.

Developers have unlimited access to Shotstack API’s using a free sandbox account. Sign up for a developer account before following this tutorial to get your API key.

Requirements

You need to have PHP 7.3+ and the SDK package. The recommended way to use the SDK is a composer package. Create a new folder for this tutorial, and in there, install the SDK using the following command:

composer require shotstack/shotstack-sdk-php

Create a PHP script that converts MP4 files to GIFs

In your preferred IDE or text editor, create a PHP script file. You can call it whatever you want, but we named it mp4-to-gif.php for this tutorial. Then, open the file and start editing.

Import the Shotstack SDK classes

Our script will use several of the Shotstack SDK video editing modules. The SDK is divided into many small classes that each manipulate and manage the video edit from start to finish.

Copy the code below into your script:

<?php
require 'vendor/autoload.php';

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;
use Shotstack\Client\Model\Edit;
use Shotstack\Client\Model\Output;
use Shotstack\Client\Model\Timeline;
use Shotstack\Client\Model\Track;
use Shotstack\Client\Model\Clip;
use Shotstack\Client\Model\VideoAsset;

Setting up the API client

Next, add the following, which configures the API client with the sandbox URL and API key issued to you:

$config = Configuration::getDefaultConfiguration()
->setHost('https://api.shotstack.io/stage')
->setApiKey('x-api-key', 'your_key_here'); // use the API key issued to you

$client = new EditApi(null, $config);

Replace your_key_here with the sandbox API key found in the dashboard, remember it is free for testing and development. Notice also that the URL is set to https://api.shotstack.io/stage, which is the sandbox URL.

Configuring the video clip

Following the meme use case we will use MP4 video footage from the movie American Psycho staring Christian Bale hosted on Imgflip. The MP4 file is hosted at the URL https://i.imgflip.com/66o1m8.mp4. The video must be hosted on the internet and be accessible via a public or signed URL.

To load this footage into our edit we need to use the VideoAsset class. Add the following code to the script after the use statements:

$videoAsset = new VideoAsset();
$videoAsset
->setSrc('https://i.imgflip.com/66o1m8.mp4');

Next, create a Clip. A clip is a container for different types of assets, including the VideoAsset. We can change the length or duration and start time on the timeline from which it will play.

For our clip, we use the $videoAsset we just created, with a start time of 0 seconds and a length of 3 seconds by adding the following code:

$videoClip = new Clip();
$videoClip
->setAsset($videoAsset)
->setLength(3)
->setStart(0);

Inserting a video clip into the timeline

The Shotstack API uses many techniques used in desktop video editing software like Adobe Premiere or Davici Resolve. Features such as a timeline, tracks and clips should be familiar.

From the SDK we will need to set up a timeline. The timeline contains a single track. And finally the track will contain the video clip we already set up.

Below we add our $videoClip to the Track clips array, and then add our track to the array of tracks of the Timeline using setTracks([]):

Add the following code to the end of the script to configure the Timeline, Track and add the $videoClip to the track.

$track = new Track();
$track->setClips([$videoClip]);

$timeline = new Timeline();
$timeline->setTracks([$track]);

Configuring the final edit and GIF output

Next, we configure the output format and add the timeline and output to create an edit.

And, since we want the output to be in GIF format, we'll set the format to gif which will convert the file from MP4 to an animated GIF that will loop indefinitely.

Because it is a GIF, we also want to reduce the file size using a very low frame rate (fps) and low resolution (width/height). These options reduce the file size and the render time of the GIF.

Add the following code:

$output = new Output();
$output
->setFormat('gif')
->setfps(12)
->setResolution('preview');

$edit = new Edit();
$edit
->setTimeline($timeline)
->setOutput($output);

Sending the edit to the API for rendering

Finally, we use the API to send the edit for processing and rendering. The Shotstack SDK handles the conversion of our objects to JSON, the addition of our key to the request header, and the POSTing of everything to the API.

try {
$response = $client->postRender($edit)->getResponse();
} catch (ApiException $e) {
die('Request failed: ' . $e->getMessage() . $e->getResponseBody());
}

echo $response->getMessage() . "\n";
echo ">> render id: " . $response->getId() . "\n";

The final MP4 to GIF PHP script

The final MP4 to GIF PHP script is included below which you can copy and paste in one go:

<?php
require 'vendor/autoload.php';

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;
use Shotstack\Client\Model\Edit;
use Shotstack\Client\Model\Output;
use Shotstack\Client\Model\Timeline;
use Shotstack\Client\Model\Track;
use Shotstack\Client\Model\Clip;
use Shotstack\Client\Model\VideoAsset;

$config = Configuration::getDefaultConfiguration()
->setHost('https://api.shotstack.io/stage')
->setApiKey('x-api-key', 'iqVSPWVr4W3a0iaohm5SmaRrw6INMzLqalwEaljs'); // use the API key issued to you

$client = new EditApi(null, $config);

$videoAsset = new VideoAsset();
$videoAsset
->setSrc('https://i.imgflip.com/66o1m8.mp4');

$videoClip = new Clip();
$videoClip
->setAsset($videoAsset)
->setLength(3)
->setStart(0);

$track = new Track();
$track->setClips([$videoClip]);

$timeline = new Timeline();
$timeline->setTracks([$track]);

$output = new Output();
$output
->setFormat('gif')
->setfps(12)
->setResolution('preview');

$edit = new Edit();
$edit
->setTimeline($timeline)
->setOutput($output);

try {
$response = $client->postRender($edit)->getResponse();
} catch (ApiException $e) {
die('Request failed: ' . $e->getMessage() . $e->getResponseBody());
}

echo $response->getMessage() . "\n";
echo ">> render id: " . $response->getId() . "\n";

Running the script

Use the php command to run the script from the command line:

php mp4-to-gif.php

If the render request is successful, the API will output the render id which we can use to retrieve the status of the render in the next step. The output should look something like this:

Render Successfully Queued
>> render id: 34d88fea-a67b-4b9d-4427-75d59d829fab

Reviewing the render status and output URL

To check the status, we need another script which will call the API render status endpoint.

Create a file called status.php and paste the following code:

<?php
require 'vendor/autoload.php';

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;

$config = Configuration::getDefaultConfiguration()
->setHost('https://api.shotstack.io/stage')
->setApiKey('x-api-key', 'your_key_here'); // use the API key issued to you

$client = new EditApi(null, $config);
$response = $client->getRender($argv[1], false, true)->getResponse();

echo "\nStatus: " . strtoupper($response->getStatus()) . "\n\n";

if ($response->getStatus() == 'done') {
echo ">> Asset URL: " . $response->getUrl() . "\n";
}
?>

Then run the script using,

php status.php {renderId}

Replace {renderId} with the ID returned from the mp4-to-gif.php script.

Re-run the status.php script every couple of seconds until the status is done and a URL is returned in the output response. If something goes wrong the status will show as failed.

You should see something like this once the GIF is ready:


Status: DONE

>> Asset URL: https://shotstack-api-stage-output.s3-ap-southeast-2.amazonaws.com/jwtlocc3y5/34d88fea-a67b-4b9d-4427-75d59d829fab.gif

The final rendered GIF is now ready to be hosted or transferred to your application:

American Psycho gif meme

Final thoughts

This tutorial should have given you a basic understanding of how to programmatically convert an MP4 video to an animated GIF using PHP and the Shotstack video editing API. As a next step you could add other assets like text and images to create a fully automated meme experience.

Of course, this article only scratches the surface of what is possible with the Shotstack API. You can create automated video editing processes for different video use cases like real estate, automotive, media and entertainment, sports highlights and more.

Emad Bin Abid

BY EMAD BIN ABID
4th October, 2023

Become an Automated Video Editing Pro

Every month we share articles like this one to keep you up to speed with automated video editing.


You might also like

Convert MP4 video to MP3 audio using PHP

Convert MP4 video to MP3 audio using PHP

Emad Bin Abid
How to add captions to video using PHP

How to add captions to video using PHP

Vlad Bartusica