php功能-php给图片加水印
PHP的GD函数库里有两个常用函数可用于水印添加:imagecopy和imagecopymerge,两者的唯一区别是:前者比后者少了个合并程度参数,如:
bool imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )
bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )
当$pct=100时,两函数完全一样。
那么,究竟用哪一个函数好呢?答案是都不好,两个结合起来用最好。两个函数都作过测试,效果明显没有结合起来用好,具体什么原因,据说是通道的问题,网上说法不一,如果你感兴趣,可以研究一下。
见代码:
<?php
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
$opacity=$pct;
// getting the watermark width:得到水印宽度
$w = imagesx($src_im);
// getting the watermark height:得到了水印的高度
$h = imagesy($src_im);
// creating a cut resource :创建一个资源剪切后的资源/函数:重采样拷贝部分图像并调整大小
$cut = imagecreatetruecolor($src_w, $src_h);
// copying that section of the background to the cut:复制这部分剪切后的的背景 -cn拷贝图像的一部分
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
// inverting the opacity :反向不透明
$opacity = 100 - $opacity;
// placing the watermark now:函数:拷贝图像的一部分
imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
//函数:拷贝并合并图像的一部分
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity);
}
define('__WATER_IMG__', 'watermark.png'); //水印路径,举例用,实现不存在
$testpg = '1.jpg';//需要加水印的图片
$img_thumb = imagecreatefromjpeg($testpg);//读取图片,为资源类型
$testpg_arr = @getimagesize($testpg);//获取相关信息,返回内容:
// array
// 0 => int 1024 //宽
// 1 => int 768 //高
// 2 => int 2
// 3 => string 'width="1024" height="768"' (length=25)
// 'bits' => int 8
// 'channels' => int 3
// 'mime' => string 'image/jpeg' (length=10)
$isAddWaterImg = true;//由于这部分代码是加在其它公用函数中,故加了一个开关
//添加水印图片
if($isAddWaterImg) {
//缩放处理后的图片大小
$thumb_w = $testpg_arr[0];//$thumb_width;
$thumb_h = $testpg_arr[1];//$thumb_height;
$img_watername = __WATER_IMG__;
$water_arr = getimagesize($img_watername);
if(!$water_arr){
$ret['msg']="水印图片不存在或路径不正确!";
return $ret;
}
$water_w = $water_arr[0];
$water_h = $water_arr[1];
$src_x = 0;
$src_y = 0;
$img_water = imagecreatefrompng($img_watername);//读取水印图片资源
$dstx_ = $water_w+$thumb_w*0.05;//水印右边缘与被加水印图片右边缘的距离,这里设置为5%的浮动位置(不要问为什么这么设置,你可以随便设置)
$dsty_ = $water_h+$thumb_h*0.05;//水印下边缘与被加水印图片下边缘的距离,这里设置为5%的浮动位置
if($thumb_w>=$dstx_ && $thumb_h>=$dsty_) {
$dst_x = $thumb_w - $dstx_;
$dst_y = $thumb_h - $dsty_;
imagecopymerge_alpha($img_thumb, $img_water, $dst_x, $dst_y, $src_x, $src_y, $water_w, $water_h, 65);
}
imagejpeg($img_thumb, $newimg = 'test0011.jpg');//参数定义生成添加水印后的图片名称
echo "<img src={$newimg}>"; // 显示生成图片
}
?>