现在的位置: 首页 > 综合 > 正文

ThinkPHP水印功能,修复PNG透明水印增加JPEG图片质量可调整

2013年08月24日 ⁄ 综合 ⁄ 共 1531字 ⁄ 字号 评论关闭

TP自带有图片类,有给图片加水印的功能。
这里完善了:
1,png水印透明
2,加水印后质量调整(只限于JPG格式)
代码如下:
红色为原系统的
绿色为修改过的

/**
+———————————————————-
* 为图片添加水印
+———————————————————-
* @static public
+———————————————————-
* @param string $source 原文件名
* @param string $water 水印图片
* @param string $$savename 添加水印后的图片名
* @param string $alpha 水印的透明度
+———————————————————-
* @return string
+———————————————————-
* @throws ThinkExecption
+———————————————————-
*/
static public function water($source, $water, $savename=null, $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);

//图像位置,默认为右下角右对齐
$posY = $sInfo["height"] – $wInfo["height"];
$posX = $sInfo["width"] – $wInfo["width"];

/* 为了保持PNG的透明效果 使用imagecopy */
imagecopy($sImage,
$wImage, $posX, $posY, 0, 0, $wInfo['width'], $wInfo['height']);

//生成混合图像,这是系统的
//
imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo['width'],
$wInfo['height'], $alpha);
//输出图像
$ImageFun = ‘Image’ . $sInfo['type'];
//如果没有给出保存文件名,默认为原图像名
if (!$savename) {
$savename = $source;
@unlink($source);
}
//保存图像,如果是jpg,则设置一下水印质量
if
($sInfo['type'] == “jpg” || $sInfo['type'] == “jpeg”) {

imagejpeg($sImage,
$savename, 90);//第3个参数即使质量大小,因为只有imagejpeg支持这个参数

}
else {

$ImageFun($sImage,
$savename);

}
//$ImageFun($sImage,
$savename);

imagedestroy($sImage);
}

最后,感谢KONAKONA提供。

抱歉!评论已关闭.