利用php的imagick给gif图片加水印
尝试多次直接用GD库给gif图片加水印均未达到理想效果后,决定用imagick扩展给gif图片加水印,虽然帧数太多的情况下速度不太给力外,效果蛮理想。
开启imagick扩展,可参考http://www.vpser.net/manage/lnmp-lnmpa-imagemagick-install-tutorial.html
果断先上图:
再上代码:
$image_name = '01351346.gif';
//$image_name = 'Left_spinning_dancer.gif';
//$image_name = 'gifmerge.gif';
function createTextImagickDraw($fontSize=12, $fillColor='', $underColor='', $font='msyh.ttf'){
$draw = new ImagickDraw();
$draw->setFont($font);
$draw->setFontSize($fontSize);
//$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);//设置水印位置
if(!empty($underColor)) $draw->setTextUnderColor(new ImagickPixel($underColor));
if(!empty($fillColor)) $draw->setFillColor(new ImagickPixel($fillColor));
return $draw;
}
function createWaterImagickDraw($waterImg='water.png',$x=10,$y=85,$width=16,$height=16){
$water = new Imagick($waterImg);
//$second->setImageOpacity (0.4);//设置透明度
$draw = new ImagickDraw();
//$draw->setGravity(Imagick::GRAVITY_CENTER);//设置位置
$draw->composite($water->getImageCompose(), $x, $y, $width, $height,$water);
return $draw;
}
$image = new Imagick($image_name);
$animation = new Imagick();
$animation->setFormat( "gif" );
$image = $image->coalesceImages();
$unitl = $image->getNumberImages();
for ($i=0; $i<$unitl; $i++) {
$image->setImageIndex($i);
$thisimage = new Imagick();
$thisimage->readImageBlob($image);
$delay = $thisimage->getImageDelay();
$thisimage->annotateImage(createTextImagickDraw(12, 'red'), 30, 100, 0, '阿维卡');
$thisimage->annotateImage(createTextImagickDraw(12, 'green'), 10, 120, 0, 'http://kller.cn');
$thisimage->annotateImage(createTextImagickDraw(12, 'blue'), 10, 140, 0, 'http://www.aweika.com');
$thisimage->drawImage(createWaterImagickDraw('f.jpg'));
$animation->addImage($thisimage);
$animation->setImageDelay( $delay );
}
$animation->writeImages('new/'.$image_name, true);
header( "Content-Type: image/gif" );
echo $animation->getImagesBlob();