PHP使用ImageMagic添加图片水印教程

之前说过如何在Linx命令行下利用ImageMagic快速生成缩略图,现在说下如果利用php的Image扩展库生成缩略图.

首生,我们来安装imagick扩展库:

wget http://pecl.php.net/get/imagick

tar xzvf imagick

cd imagick-3.1.0RC1

phpize

./configure --with-imagick='/usr/local/imk'

make

make install

到这里就安装了,重载PHP-FPM使之生效:

php-fpm reload

下面是PHP生成缩略图的代码:

function waterMark($groundImage , $waterPos = 0 , $waterImage = "" ,$alpha=0.5){
$bg_h = $bg_w = $water_h = $water_w = 0;
//获取背景图的高,宽
if(is_file($groundImage) && !empty($groundImage)){
   $bg = new Imagick();
   $bg ->readImage($groundImage);
   $bg_h = $bg->getImageHeight();
   $bg_w = $bg->getImageWidth();
}

//获取水印图的高,宽
if(is_file($waterImage) && !empty($waterImage)){
   $water = new Imagick($waterImage);
   $water_h = $water->getImageHeight();
   $water_w = $water->getImageWidth();
}
//如果背景图的高宽小于水印图的高宽或指定的高和宽则不加水印
if($bg_h < $minHeight || $bg_w < $minWidth || $bg_h < $water_h || $bg_w < $water_w ) {
   return ;
}

$dw = new ImagickDraw();  
   //加图片水印
   if(is_file($waterImage)){
    $water->setImageOpacity($alpha);
    $dw -> setGravity($waterPos);
    $dw -> composite($water->getImageCompose(),10,20,50,0,$water);
    $bg -> drawImage($dw);
    if(!$bg -> writeImage($groundImage)){
     return FALSE;
    }  
   }
}

使用示例:

waterMark('test.png',Imagick::GRAVITY_SOUTHEAST,'watter_mark.png');

表示在大图(test.png)的右下角放置一个水印(watter_mark.png)

发表评论?

1 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>