16

Does anyone know if it's possible to generate an animated GIF from two different JPEG files, displaying one image for x seconds then the other, and so on..?

Any advice appreciated.

Thanks.

Dan
  • 4,068
  • 10
  • 41
  • 51

3 Answers3

11

For a nice, quick and more recent solution, see this SO answer.

For an even more recent solution, here is my fork of it, with a number of small fixes & improvements. An example of it from an actual application:

$anim = new GifCreator\AnimGif();

$gif = $anim->create($image_files);
//file_put_contents("test.gif", $gif);

header("Content-type: image/gif");
echo $gif;

(Requires PHP5.3 with GD2.)

Example that works with PHP 5.6 and GD 2.4.11:

require_once "AnimGif.php";

/*
 * Create an array containing file paths, resource var (initialized with imagecreatefromXXX), 
 * image URLs or even binary code from image files.
 * All sorted in order to appear.
 */
$image_files = array(
    //imagecreatefrompng("/../images/pic1.png"), // Resource var
    //"/../images/pic2.png", // Image file path
    //file_get_contents("/../images/pic3.jpg"), // Binary source code
    'https://yt3.ggpht.com/-KxeE9Hu93eE/AAAAAAAAAAI/AAAAAAAAAAA/D-DB1Umuimk/s100-c-k-no-mo-rj-c0xffffff/photo.jpg', // URL
    'https://media.licdn.com/mpr/mpr/shrinknp_100_100/AAEAAQAAAAAAAAloAAAAJDRkZGY2MWZmLTM1NDYtNDBhOS04MjYwLWNkM2UzYjdiZGZmMA.png', // URL
    'http://is5.mzstatic.com/image/thumb/Purple128/v4/e4/63/e7/e463e779-e6d0-0c3d-3ec1-97fdbaae230a/source/100x100bb.jpg' // URL
);

/*
 * Create an array containing the duration (in millisecond) of each frame.
 */
$durations_millis = array(
    1000,
    2000,
    3000
);

/*
 * Fix durations.
 */
$durations = array();
for ($i = 0; $i < count($durations_millis); $i++) {
    $durations[$i] = $durations_millis[$i] / 10;
}

/*
 * Specify number of loops. (0 = infinite looping.)
 */
$num_loops = 0;

/*
 * Create gif object.
 */
$anim_gif = new GifCreator\AnimGif();
$gif_object = $anim_gif->create($image_files, $durations, $num_loops);

/*
 * Get the animated GIF binary.
 */
$gif_binary = $gif_object->get();

/*
 * Set the file name of the saved/returned animated GIF.
 */
$file_name = "animated.gif";

/*
 *  Optionally, save animated GIF in a folder as a GIF:
 */
//file_put_contents($file_name, $gif_binary);

/*
 * Optionally, return the animated GIF to client.
 */
header("Content-type: image/gif");
header('Content-Disposition: filename="' . $file_name . '"'); // Optional
echo $gif_binary;

/*
 * All done.
 */
exit;
ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253
Sz.
  • 3,342
  • 1
  • 30
  • 43
  • This doesn't work for my (PHP5.6 with GD2.4.11). Just gives me `The image "..." cannot be displayed because it contains errors.` – ban-geoengineering Dec 06 '17 at 20:17
  • 1
    @ban-geoengineering, thanks for pointing that out. (Well, anything's possible, as PHP5.6 didn't exist back then.) A possible fix has just been merged to the code there; please retry, and if the problem remains, please submit an issue to the project at GitHub, so that it can be addressed there properly. – Sz. Dec 07 '17 at 18:52
  • Thanks for that. Have just updated your answer with working code snippet. – ban-geoengineering Dec 12 '17 at 00:16
8

It's not possible using the standard GD functions that come pre-packed with PHP.

There is a class on phpclasses.org for this. I have never used it myself, but it's used by a lot of other packages.

Alternatively, if you have access to ImageMagick from PHP, using either the MagickWand library or the command line, use it. With ImageMagick, it's no problem.

kurdtpage
  • 3,142
  • 1
  • 24
  • 24
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 1
    The **phpclasses.org** code is a nightmare to access and the inputs files for it must be GIF files. It doesn't work for JPEG files... :-/ – ban-geoengineering Dec 06 '17 at 20:45
  • You can convert your input JPEG images to (static) GIF images using this answer to another SO question: https://stackoverflow.com/a/755843/1617737 – ban-geoengineering Dec 06 '17 at 21:17
3

This cannot be done with GD but I found a great library for it. It is a bit complicated though, so here is a link to the library which makes animated gifs with php. It explains how to use it thoroughly. http://www.phpclasses.org/package/3163-PHP-Generate-GIF-animations-from-a-set-of-GIF-images.html

Select 2 pictures and write 100 for speed 900 for width and height. It will put them in an animated gif slideshow.

Here is the code for that script:

<?php
if(isset($_POST['speed']))
{
    header('Content-type: image/gif');
    if(isset($_POST['download'])){
    header('Content-Disposition: attachment; filename="animated.gif"');
    }
    include('GIFEncoder.class.php');
    function frame($image){
        ob_start();
        imagegif($image);
        global $frames, $framed;
        $frames[]=ob_get_contents();
        $framed[]=$_POST['speed'];
        ob_end_clean();
    }
    foreach ($_FILES["images"]["error"] as $key => $error)
    {
        if ($error == UPLOAD_ERR_OK)
        {
            $tmp_name = $_FILES["images"]["tmp_name"][$key];
            $im = imagecreatefromstring(file_get_contents($tmp_name));
            $resized = imagecreatetruecolor($_POST['width'],$_POST['height']);
            imagecopyresized($resized, $im, 0, 0, 0, 0, $_POST['width'], $_POST['height'], imagesx($im), imagesy($im));
            frame($resized);
        }
    }
    $gif = new GIFEncoder($frames,$framed,0,2,0,0,0,'bin');
    echo $gif->GetAnimation();
}
?>
<form action="" method="post" enctype="multipart/form-data">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="jquery.MultiFile.js"></script>
<script src="jquery.placeholder.js"></script>
<input type="file" name="images[]" class="multi" />
<script>
    $(function(){
        $('input[placeholder], textarea[placeholder]').placeholder();
   });
</script>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
<input name="speed" maxlength="10" type="text" placeholder="Speed of frames in ms" onkeypress="return isNumberKey(event)">
<input name="width" maxlength="4" type="text" placeholder="Width" onkeypress="return isNumberKey(event)">
<input name="height" maxlength="4" type="text" placeholder="Height" onkeypress="return isNumberKey(event)">
<input type="submit" name="download" value="Download!">
<input type="submit" name="preview" value="Preview!">
</form>

As you see it references the GIFEncoder class found on the first link. It also uses some javascript validation and jQuery multiupload.

Note: this question has already been asked.

Tom
  • 4,422
  • 3
  • 24
  • 36
  • @Tom when i tried this code return error like "cannot be displayed because it contains errors." can you please help me. – Jalpa Aug 24 '17 at 05:03