Skip to content

Instantly share code, notes, and snippets.

@mgng
Created February 5, 2013 06:24
Show Gist options
  • Save mgng/4712651 to your computer and use it in GitHub Desktop.
Save mgng/4712651 to your computer and use it in GitHub Desktop.
<?php
/**
* animate
* @param array $files
* @param string $out
* @param int $delay 切り替えmsec default 50
* @param int $loop ループ回数, 0で無限ループ default 1
* @param boolean $autoreverse 自動リバースするかどうか default false
* @param float $resize_percent リサイズ% default 1.0
* @param integer $quality 1 が最低, 255が最高 default 128
*/
function animate( $files, $out, $delay = 50, $loop = 1, $autoreverse = false, $resize_percent = 1.0, $quality = 128 ) {
if ( $autoreverse ) {
$files = array_merge( $files, array_reverse( array_slice( $files, 1, count($files) - 2 ) ) );
}
$anime = new Imagick();
$anime->setFormat('gif');
foreach( $files as $file ) {
$tmp_gd = imagecreatefromjpeg( $file );
$w = imagesx( $tmp_gd );
$h = imagesy( $tmp_gd );
$n_w = $w * $resize_percent;
$n_h = $h * $resize_percent;
$gd = imagecreatetruecolor( $n_w, $n_h );
imagecopyresized( $gd, $tmp_gd, 0, 0, 0, 0, $n_w, $n_h, $w, $h);
imagedestroy( $tmp_gd );
imagetruecolortopalette( $gd, true, $quality );
$blob = getImageBlob( $gd, 'gif' );
$gif = new Imagick();
$gif->readImageBlob( $blob );
$gif->setFormat( 'gif' );
$gif->setImageDelay( $delay );
$gif->setImageIterations( $loop );
$anime->addImage( $gif );
$gif->destroy();
}
$anime->writeImages($out, true);
$anime->destroy();
}
/**
* getImageBlob
*/
function getImageBlob( $gd, $type ) {
ob_start();
call_user_func( "image{$type}", $gd );
imagedestroy( $gd );
$out = ob_get_contents();
ob_end_clean();
return $out;
}
$files = glob( 'imgs/*.jpg' );
animate( $files, 'out.gif', 4, 0, true, 1.0, 256 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment