本文實例講述了ThinkPHP打水印及設置水印位置的方法。分享給大家供大家參考,具體如下:
最近在用Thinkphp的打水印的功能,發現只能打在左下角。 PHP打水印功還是很容易的,最要是用到
復制代碼 代碼如下: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 透明。
水印demo圖:

我需要把水印打到圖片的真中間,查看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相關內容感興趣的讀者可查看本站專題:《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結》、《ThinkPHP常用方法總結》、《smarty模板入門基礎教程》及《PHP模板技術總結》。
希望本文所述對大家基於ThinkPHP框架的PHP程序設計有所幫助。