用PHP从html创建gif动画


Create animated gif from html with PHP

我有以下简单的html,我需要使用它来创建和保存一个新的动画gif:

<div id="wrap">
  <div id="content">
    <p>Message here</p>
    <img src="image.jpg" />
  </div>
  <img src="image.gif" width="709" height="425" />
</div>

代码末尾的gif是一个动画gif -然后我希望能够在此顶部覆盖文本和另一个jpeg图形,保留gif的动画。

首先,这是可能的,其次,如果是的话,有人能告诉我正确的方向吗?

我猜我可能需要以某种方式合并php的imagegif函数??

据我所知,PHP的GD库函数无法生成动画gif。

您将不得不依赖其他工具,例如ImageMagik的convert函数(您可以通过exec调用它)。

编辑后注释:

如果你只想创建一个非动画的gif,那么这个过程很容易用GD库完成。

假设你的文本在一个变量$txt中,还有两个图像image1.jpgimage2.gif,你想要堆叠。

最终结果将看起来像

    TEXT
-------------
|           |
|  IMAGE 1  |
|           |
 -----------
-------------
|           |
|  IMAGE 2  |
|           |
 -----------

首先打开两个图像:

$i1 = imagecreatefromjpeg("image1.jpg");
$i2 = imagecreatefromgif("image2.gif");

现在找到两个图像的大小。

$i1_w = imagesx($i1);
$i1_h = imagesy($i1);
$i2_w = imagesx($i2);
$i2_h = imagesy($i2);

您的最终图像将包含

// Add 30px for the text, you can calculate this precisely 
// using imagettfbbox but be sure to use imagettftext 
// instead of imagestring later
$height = $i1_h + $i2_h + 30;
$width = max($i1_w, $i2_w);

现在创建您的输出图像

$img = imagecreatetruecolor($width, $height);

把文字放到最上面

$black = imagecolorallocate($img, 0, 0, 0);
// Instead of using 1 as 2nd parameter you can use a font created 
// with imageloadfont. Also, you may want to calculate text coordinates
// so that it is centered etc.
imagestring($img, 1, 10, 10, $txt, $black);
现在添加图片
imagecopy($img, $img1, ($width-$img1_w)/2, 30, 0, 0, $img1_w, $img1_h);
imagecopy($img, $img2, ($width-$img2_w)/2, 35+$img1_h, 0, 0, $img2_w, $img2_h);
最后,输出gif
header('Content-Type: image/gif');
imagegif($img); // Or imagejpeg, imagepng etc.

如果你只是想保存图像,而不显示它,只需:

imagegif($img, "output.gif");