PHP - 如何从两个JPEG图像创建简单的动态GIF?

16

请问是否有可能从两个不同的JPEG文件生成一个动画GIF,显示其中一个图像x秒,然后显示另一个图像,如此循环?

欢迎提供任何建议。

谢谢。

3个回答

11

对于一个好的、快速且更近期的解决方案,请参见此SO答案

对于一个更加近期的解决方案,这是我的分支,其中有一些小修复和改进。以下是来自实际应用的示例:

$anim = new GifCreator\AnimGif();

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

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

(需要 PHP5.3 与 GD2.)

适用于 PHP 5.6 和 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;

这对我的(PHP5.6 with GD2.4.11)不起作用。只是给了我The image "..." cannot be displayed because it contains errors. - ban-geoengineering
1
@ban-geoengineering,感谢您指出这一点。(嗯,当时还不存在PHP5.6,所以任何事情都有可能发生。)现在代码中已经合并了一个可能的修复方案,请重试,如果问题仍然存在,请在GitHub项目中提交一个问题,以便可以适当地解决它。 - Sz.
谢谢你。我刚刚更新了你的答案,并添加了可工作的代码片段。 - ban-geoengineering

8

1
phpclasses.org 的代码难以访问,且其输入文件必须为 GIF 格式。对于 JPEG 格式的文件无法正常运行... :-/ - ban-geoengineering
您可以使用另一个SO问题的答案(https://dev59.com/fHRA5IYBdhLWcg3w_DHF#755843)将输入的JPEG图像转换为(静态)GIF图像。 - ban-geoengineering

3
这不能使用GD实现,但我找到了一个很棒的库。不过它有点复杂,所以这里提供一个链接,可以用php制作动画gif。它详细解释了如何使用。http://www.phpclasses.org/package/3163-PHP-Generate-GIF-animations-from-a-set-of-GIF-images.html 选择2张图片,并将速度设置为100,宽度和高度设置为900。它将把它们放在一个动画GIF幻灯片中。
以下是该脚本的代码:
<?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>

正如您所见,它引用了第一个链接中找到的GIFEncoder类。它还使用一些JavaScript验证和jQuery多上传。

注意:此问题已经被问过。


@Tom 当我尝试运行这段代码时,会返回错误信息 "无法显示,因为它包含错误。" 请问你能帮忙吗? - Jalpa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接