如何为图像添加水印?

时间:2012-03-30 15:21:13

标签: php gd

我有一个jpg文件,我想在其上合并另一个图像png文件。我不知道如何使用php实现这个?

2 个答案:

答案 0 :(得分:1)

您可以使用gd的 imagecopy 功能。

此功能用于将部分图像从源复制到目标

imagecopy ( 
           $dst_im ,   // destination image (resource), imagecreatefrom(gif|jpg|png)
           $src_im ,   // destination image (resource), imagecreatefrom(gif|jpg|png) 
           $dst_x ,    // x cordinate in destination where u want the new obj placed
           $dst_y ,    // y cordinate in destination where u want the new obj placed
           $src_x ,    // x cordinate in source from wher u want the new obj placed
           $src_y ,    // y cordinate in source from where u want the new obj placed
           $src_w ,    // the width of the object to copy
           $src_h      // the height of the object to copy
);

正如上面代码中的注释所指出的,您必须为目标和源创建图像资源。

通常使用

完成
 $src = imagecreatefromjpg('image.jpg');
 $dst = imagecreatefromjpg('watermark');

其余部分只是简单的坐标。

另外,别忘了亲自访问imagecopy

答案 1 :(得分:0)

以下是使用GD进行热水印的一些示例:

const CORNER_TOP_LEFT       = 1;
const CORNER_TOP_RIGHT      = 2;
const CORNER_BOTTOM_LEFT    = 3;
const CORNER_BOTTOM_RIGHT   = 4;

$backgroundImagePath = "img/stamp.png";
$corner=CORNER_BOTTOM_RIGHT;
$alpha=60

$img_res=@imagecreatefromjpeg($filename);
$img_info=getimagesize($backgroundImagePath);

switch ($corner){
    case CORNER_TOP_LEFT:
        if(!imagecopymerge ($this->imageRes, $img_res, 0, 0, 0, 0, $img_info[0], $img_info[1], $alpha)){
            throw new RuntimeException("Unable to make stamp!");
        }
        break;
    case CORNER_TOP_RIGHT:
        if(!imagecopymerge ($this->imageRes, $img_res, $this->info[0]-$img_info[0], 0, 0, 0, $img_info[0], $img_info[1], $alpha)){
            throw new RuntimeException("Unable to make stamp!");
        }
        break;
    case CORNER_BOTTOM_LEFT:
        if(!imagecopymerge ($this->imageRes, $img_res, 0, $this->info[1]-$img_info[1], 0, 0, $img_info[0], $img_info[1], $alpha)){
            throw new RuntimeException("Unable to make stamp!");
        }
        break;
    case CORNER_BOTTOM_RIGHT:
        if(!imagecopymerge ($this->imageRes, $img_res, $this->info[0]-$img_info[0], $this->info[1]-$img_info[1], 0, 0, $img_info[0], $img_info[1], $alpha)){
            throw new RuntimeException("Unable to make stamp!");
        }
        break;
}

imagejpeg($img_res, "/path/to/save/image.jpg", 100);
相关问题