简体   繁体   中英

Create animated gif from html with PHP

I have the following simple html which I need to use to create and save a new animated 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>

The gif towards the end of the code is an animated gif - I would then like to be able to overlay text and another jpeg graphic over the top of this, retaining the animation of the gif.

Firstly is this possible and secondly could someone please point me in the right direction if it is.

I'm guessing I might need to incorporate PHPs imagegif function somehow??

As far as I am aware, PHP's GD library function are not able to generate animated GIFs.

You will have to rely on other tools, such as ImageMagik's convert function (you can call it through exec ).

EDIT after comment:

If you just want to create a non-animated gif, then the process is easily done with GD libraries.

Say you have your text in a variable $txt , and two images image1.jpg and image2.gif that you want to stack.

The end result will look like

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

You would first open the two images:

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

Now find the size of the two images.

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

Your final image will have

// 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);

Now you create your output image

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

Put the text on top

$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);

Now add the images

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);

Finally, output the gif

header('Content-Type: image/gif');
imagegif($img); // Or imagejpeg, imagepng etc.

If you just want to save the image, without showing it just do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM