方法代码:
- /**
- * 图片加水印 (适用于 png/jpg/gif 格式)
- *
- * @author flynetcn
- *
- * @param $srcImg 原图片
- * @param $waterWord 水印文字
- * @param $savepath 保存路径
- * @param $savename 保存名字
- * @param $positon 水印位置
- * 1: 顶部居左, 角度 - 30 度; 2: 居中, 角度 30 度; 3: 居中, 角度 - 30 度; 4: 底部居左, 角度 30 度;
- * @param $size 字体大小
- * @param $alpha 透明度 -- 0: 完全透明, 100: 完全不透明
- *
- * @return 成功 -- 加水印后的新图片地址
- * 失败 -- -1: 原文件不存在, -2: 水印图片不存在, -3: 原文件图像对象建立失败
- * -4: 水印文件图像对象建立失败 -5: 加水印后的新图片保存失败
- */
- function water_mark($srcImg, $waterWord, $savepath = null, $savename = null, $positon = 3, $size = 74, $color = null, $alpha = 50) {
- // 判断文件是否存在
- $srcImgInfo = @getimagesize($srcImg);
- if (!$srcImgInfo) {
- return - 1;
- }
- // 建立图像对象
- $srcImgObj = image_create_from_ext($srcImg, $srcImgInfo[2]);
- if (!$srcImgObj) {
- return - 3; // 原文件图像对象建立失败
- }
- // 准备信息: 保存路径, 保存文件名
- $temp = pathinfo($srcImg);
- $name = $temp[basename];
- $path = $temp[dirname];
- $ext = $temp[extension];
- $color = $color ? $color: imagecolorallocate($srcImgObj, 255, 250, 250);
- $savename = $savename ? $savename: $name;
- $savepath = $savepath ? $savepath: $path;
- $savefile = $savepath. / .$savename;
- // 创建一个画布, 并给其填充颜色, 否则背景为黑色
- $imgW = 500;
- $imgH = $srcImgInfo[1] / ($srcImgInfo[0] / 500);
- $imgObj = imagecreatetruecolor($imgW, $imgH);
- $trans = imagecolorallocate($imgObj, 255, 255, 255);
- imagefill($imgObj, 0, 0, $trans);
- // 缩小图片到画布
- imagecopyresampled($imgObj, $srcImgObj, 0, 0, 0, 0, $imgW, $imgH, $srcImgInfo[0], $srcImgInfo[1]);
- // 确定生成水印的位置
- switch ($positon) {
- //1 顶部居左, 角度 - 20 度
- case 1:
- $x = $y = 20;
- $angle = -20;
- break;
- //2 居中, 角度 - 20 度
- case 2:
- $x = $imgW / 7;
- $y = $imgH / 3;
- $angle = -20;
- break;
- //3 居中, 角度 20 度
- case 3:
- $x = $imgW / 7;
- $y = $imgH / 1.5;
- $angle = 20;
- break;
- //4 底部居左, 角度 20 度
- case 4:
- $x = 20;
- $y = $imgH;
- $angle = 20;
- break;
- default:
- $x = $imgW / 7;
- $y = $imgH / 2;
- $angle = 20;
- break;
- }
- // 添加水印图片
- imagettftext($imgObj, $size, $angle, $x, $y, $color, . / fonts / STXINWEI.TTF, $waterWord);
- // 输出图片
- switch ($srcImgInfo[2]) {
- case 1:
- imagegif($imgObj, $savefile);
- break;
- case 2:
- imagejpeg($imgObj, $savefile);
- break;
- case 3:
- imagepng($imgObj, $savefile);
- break;
- default:
- return - 5; // 保存失败
- }
- // 销毁图像资源
- imagedestroy($imgObj);
- imagedestroy($srcImgObj);
- return $savefile;
- }
- /*
- * 创建图像对象
- * @param $imgFile 图片路径
- * @param $imgExt 图片扩展名
- * @return $im 图像对象
- **/
- function image_create_from_ext($imgFile, $imgExt) {
- $im = null;
- switch ($imgExt) {
- case 1:
- $im = imagecreatefromgif($imgFile);
- break;
- case 2:
- $im = imagecreatefromjpeg($imgFile);
- break;
- case 3:
- $im = imagecreatefrompng($imgFile);
- break;
- }
- return $im;
- }
测试:
- // 调用方法测试
- $res = water_mark(F:\test\test1.jpg, "金万维域名认证专用", null, res.jpg, 3, 36);
- var_dump($res);
来源: http://www.bubuko.com/infodetail-2543035.html