当前位置:编程学习 > php >>

php里面用Imagick将静态图片合成gif动画编程代码

将多张图片合并成一个GIF动态图片的php编程代码,主要通过imagick组件实现:
<?php
$animation = new Imagick();
$animation->setFormat( "gif" );
for ($i=1; $i<4; $i++) {
$thisimage = new Imagick();
$thisimage->readImage($i.'.png');
$thisimage->setImageFormat( "gif" );
$animation->addImage($thisimage);
$animation->setImageDelay(1000);
}
header( "Content-Type: image/gif" );
echo $animation->getImagesBlob();

然后,他发现图片怎么也没有动,于是有了第二次的代码PHP代码:

<?php
$image=new Imagick();
$animation = new Imagick(); //建立一个对象。
$animation->setFormat( "gif" ); //设置它的类型。
$delay = 30; //设置播放速度。

for ($i=1; $i<4; $i++) {
$thisimage = new Imagick();
$thisimage->readImage($i.'.jpg'); //我有三个图片分别叫:1.jpg,2.jpg,3.jpg 就是要合成他们三个。
$thisimage->setFormat( "gif" ); //把他们都转成GIF格式。
$animation->addImage($thisimage); //加入到刚才建立的那个gif imagick对象之中。
$animation->setImageDelay( $delay ); //设置好播放速度。
}
header( "Content-Type: image/gif" );
$animation->writeImages("9.gif",true); //文件存储。
在这样的情况下,他发现GIF图片可以动了。看来保存成功了。

根据他写的代码,我作了一个小小的测试PHP代码:

<?php
$filelist = array(
'1.jpg',
'2.jpg',
'3.jpg'
);

$animation = new Imagick(); //create animation object
$animation->setFormat('gif'); // set file type

foreach ( $filelist as $file ){
$image = new Imagick();
$image->readImage( $file );
$animation->addImage( $image );
$animation->setImageDelay(60);
unset( $image );
}
header( "Content-Type: image/gif" );
echo( $animation->getImagesBlob() );
//$animation->writeImages( time().".gif" ,true );

代码几乎没变,除了在readImage行下面那个setFormat函数去掉了。同样生成了GIF图片,现在我把问题和解决情况和大家说一下,也希望大家少走点弯路吧

1、在animation里设置好setFormat为gif后,其他地方可以不需要设,因为最终都是通过 $animation->addImage 进入载入图片的,所以载进来肯定是GIF了
2、$animation->setImageDelay( 60 ) ,这个设置帧数的设定只能在每次AddImage后才能设定,否则会报错:没有加载图片时不能设定帧数
3、$animation->writeImages函数,不能使用writeImage,因为是多帧的,它会认为是多张图片
4、至于为什么在使用header设定文件头和echo 输出后图片没有动,我目前怀疑这是浏览器的设定关系,因为,你右键点击生成的图片另存下来时,图片是可以正常的跳动的。

可以访问这里,如果你需要在线合成图片:http://www.zhaoxi.org/t/hecheng.htm

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,