ThinkPHP水印功能现状与需求分析
本实例详细解析在ThinkPHP框架中为图片添加水印以及自定义水印位置的具体实现方法,供开发者参考与实践。
近期在使用ThinkPHP内置的图片水印功能时,注意到其默认行为仅限于将水印放置在图像的左下角。尽管PHP原生提供的水印处理机制相对简便,但核心在于调用[[wp:a数字]]函数: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 )
该函数的作用是将源图像[src_im]中从[src_x]、[src_y]起始,宽度为[src_w]、高度为[src_h]的区域,拷贝到目标图像[dst_im]的[dst_x]和[dst_y]坐标处。两个图像之间的混合程度由[pct]参数决定,取值范围为0至100。当[pct]为0时不执行任何操作;当值为100时,对于调色板图像其行为等同于imagecopy(),而对于真彩色图像则实现了Alpha透明通道效果。
以下是水印应用的效果示意图:

在实际需求中,往往需要将水印置于图片的正中央。经查阅ThinkPHP相关源码,发现开发者在内部逻辑中将位置参数固定化处理,因此需要对源代码进行适当调整以支持更灵活的位置设定。
/**
* 为图片添加水印
* @static public
* @param string $source 原文件名
* @param string $water 水印图片
* @param string $$savename 添加水印后的图片名
* @param string $postion 水印的具体位置 leftbottom rightbottom lefttop righttop center <新增>
* @param string $alpha 水印的透明度
* @return void
*/
static public function water($source, $water, $savename=null,$postion="center", $alpha=80) {
//检查文件是否存在
if (!file_exists($source) || !file_exists($water))
return false;
//图片信息
$sInfo = self::getImageInfo($source);
$wInfo = self::getImageInfo($water);
//如果图片小于水印图片,不生成图片
if ($sInfo["width"] < $wInfo["width"] || $sInfo['height'] < $wInfo['height']) return false; //建立图像 $sCreateFun = "imagecreatefrom" . $sInfo['type']; $sImage = $sCreateFun($source); $wCreateFun = "imagecreatefrom" . $wInfo['type']; $wImage = $wCreateFun($water); //设定图像的混色模式 imagealphablending($wImage, true); //图像位置,默认为右下角右对齐 $posArr = $this->WaterPostion($postion,$sInfo,$wInfo); //新增
//生成混合图像
imagecopymerge($sImage, $wImage, $posArr[0], $posArr[1], 0, 0, $wInfo['width'], $wInfo['height'], $alpha);
//输出图像
$ImageFun = 'Image' . $sInfo['type'];
//如果没有给出保存文件名,默认为原图像名
if (!$savename) {
$savename = $source;
@unlink($source);
}
//保存图像
$ImageFun($sImage, $savename);
imagedestroy($sImage);
}
private function WaterPostion($postion,$sInfo,$wInfo)
{
$posY = $sInfo["height"] - $wInfo["height"];
$posX = $sInfo["width"] - $wInfo["width"];
switch($postion)
{
case "rightbottom":
return array($posX,$posY);
break;
case "leftbottom":
return array($wInfo["width"],$posY);
break;
case "lefttop":
return array($wInfo["width"],$wInfo["height"]);
break;
case "righttop":
return array($posX,$wInfo["height"]);
break;
case "center":
return array($posX/2,$posY/2);
break;
}
}
期望上述关于ThinkPHP框架下PHP程序设计的水印处理技巧能对大家有所帮助。