ThinkPHP5实现图片水印平铺效果

 5270

我们有时需要对推片打上水印,防止别人盗用,thinkphp 自己的水印功能只能选择位置添加水印,但是有时候图片某些位置比较干净(空白部分),很容易处理掉,这样就无法起到防止盗用图片的效果。

这篇教程分享一下使用 ThinkPHP5 实现图片水印平铺的效果。

关键代码操作

1、打开第三方类库文件:vendor\topthink\think-image\src\Image.php

2、把下面代码复制到上方地址的图片处理类库中(即增加一个图片处理方法)

  1. /**
  2.  * 添加图片水印平铺
  3.  *
  4.  * @param  string $source 水印图片路径
  5.  * @param int     $alpha  透明度
  6.  * @return $this
  7.  */
  8. public function tilewater($source, $alpha = 100)
  9. {
  10.     if (!is_file($source)) {
  11.         throw new ImageException('水印图像不存在');
  12.     }
  13.     //获取水印图像信息
  14.     $info = getimagesize($source);
  15.     
  16.     if (false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))) {
  17.         throw new ImageException('非法水印文件');
  18.     }
  19.     //创建水印图像资源
  20.     $fun   = 'imagecreatefrom' . image_type_to_extension($info[2], false);
  21.     $water = $fun($source);
  22.     //设定水印图像的混色模式
  23.     imagealphablending($water, true);
  24.     do {
  25.         //添加水印
  26.         $src = imagecreatetruecolor($info[0], $info[1]);
  27.         // 调整默认颜色
  28.         $color = imagecolorallocate($src, 255, 255, 255);
  29.         imagefill($src, 0, 0, $color);
  30.         //循环平铺水印
  31.         for ($x = 0; $x < $this->info['width']-10; $x) {
  32.             for ($y = 0; $y < $this->info['height']-10; $y) {
  33.                 imagecopy($src, $this->im, 0, 0, $x, $y, $info[0], $info[1]);
  34.                 imagecopy($src, $water, 0, 0, 0, 0, $info[0], $info[1]);
  35.                 imagecopymerge($this->im, $src, $x, $y, 0, 0, $info[0], $info[1], $alpha);
  36.                 $y += $info[1];
  37.             }
  38.             $x += $info[0];
  39.         }
  40.         //销毁临时图片资源
  41.         imagedestroy($src);
  42.     } while (!empty($this->gif) && $this->gifNext());
  43.     //销毁水印资源
  44.     imagedestroy($water);
  45.     return $this;
  46. }

使用方法:

注意:仅供参考,你可以改造到你的项目的上传图片部分!

  1. use think\Image;
  2. class ....
  3. public function test(){
  4.     $image = Image::open('bg.jpg');
  5.     // 给原图设置水印图片(colleced.png)并保存 water_image.png(可以带路径)
  6.     $image->tilewater('colleced.png',100)->save('water_image.png');
  7.     echo "<img src='/water_image.png'/>";
  8. }

效果如下:

5f6c62e7a9412.jpg

本文网址:https://www.zztuku.com/detail-7939.html
站长图库 - ThinkPHP5实现图片水印平铺效果
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐