2010-02-03 29 views

Respuesta

6

No es posible usar las funciones estándar de GD que vienen pre-empaquetadas con PHP.

Hay un class on phpclasses.org para esto. Nunca lo he usado, pero lo usan muchos otros paquetes.

Alternativamente, si tiene acceso a ImageMagick desde PHP, usando la biblioteca MagickWand o la línea de comando, úselo. Con ImageMagick, no hay problema.

+0

El código de ** phpclasses.org ** es una pesadilla para acceder y los archivos de entrada deben ser archivos GIF. No funciona para archivos JPEG ...: -/ –

+0

Puede convertir sus imágenes JPEG de entrada a imágenes GIF (estáticas) usando esta respuesta a otra pregunta SO: https://stackoverflow.com/a/755843/1617737 –

3

Esto no se puede hacer con GD, pero me encontré con una gran biblioteca para ello. Aunque es un poco complicado, aquí hay un enlace a la biblioteca que hace gifs animados con php. Explica cómo usarlo a fondo. http://www.phpclasses.org/package/3163-PHP-Generate-GIF-animations-from-a-set-of-GIF-images.html

Seleccione 2 imágenes y escriba 100 para velocidad 900 para ancho y alto. Los pondrá en una presentación animada de gif.

Este es el código para ese guión:

<?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> 

Como se puede ver que hace referencia a la clase GIFEncoder encontrado en el primer enlace. También utiliza algunas validaciones de javascript y jQuery multiupload.

Nota: esta pregunta ya ha sido formulada.

+0

¡Gracias por tu genial ejemplo! – Roy

+0

@Tom cuando probé este código, devolvió un error como "no se puede mostrar porque contiene errores". Podrías ayudarme. – Jalpa

7

Para una solución agradable, rápida y más reciente, vea this SO answer.

Para una solución aún más reciente, here is my fork de ella, con una serie de pequeñas correcciones & mejoras. Un ejemplo de ello desde una aplicación real:

$anim = new GifCreator\AnimGif(); 

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

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

(Requiere PHP5.3 con GD2.)

Ejemplo que funciona con PHP 5.6 y 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; 
+0

Esto no funciona para mi (PHP5.6 con GD2.4.11). Solo me da 'La imagen" ..."no se puede mostrar porque contiene errores". –

+1

@ ban-geoengineering, gracias por señalarlo. (Bueno, todo es posible, ya que PHP5.6 no existía en ese momento). Se ha fusionado una posible solución con el código allí, por favor vuelva a intentarlo, y si el problema persiste, envíe un problema al proyecto en GitHub, para que se pueda abordar allí correctamente. –

+0

Gracias por eso. Acabo de actualizar su respuesta con un fragmento de código que funciona. –