首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP

TP5 添加平铺水印并设置水印之间的间距

作者:小萝卜 2019-05-27 浏览 2201

简介TP5 添加平铺水印并设置水印之间的间距

1、安装扩展

使用Composer安装ThinkPHP5的图像处理类库:

composer require topthink/think-image

use think\Image;
class ....
public function test(){
        $image = Image::open('bg.jpg');
        // 给原图设置水印图片(colleced.png)并保存water_image.png
        $image->tilewater('colleced.png',100,50,30)->save('water_image.png');
    }
关键代码操作

 

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

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

    /**
     * 添加图片水印平铺
     *
     * @param  string $source 水印图片路径
     * @param int     $alpha  透明度
     * @param int     $cx  x方向间距
     * @param int     $cy  y方向间距
     * @return $this
     */
    public function tilewater($source, $alpha = 100,$cx = 10,$cy = 10)
    {
        if (!is_file($source)) {
            throw new ImageException('水印图像不存在');
        }
        //获取水印图像信息
        $info = getimagesize($source);
        
        if (false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))) {
            throw new ImageException('非法水印文件');
        }
        //创建水印图像资源
        $fun   = 'imagecreatefrom' . image_type_to_extension($info[2], false);
        $water = $fun($source);
        //设定水印图像的混色模式
        imagealphablending($water, true);
        do {
            //添加水印
            $src = imagecreatetruecolor($info[0], $info[1]);
            // 调整默认颜色
            $color = imagecolorallocate($src, 255, 255, 255);
            imagefill($src, 0, 0, $color);
            //循环平铺水印
            for ($x = 0; $x < $this->info['width']; $x) {
                for ($y = 0; $y < $this->info['height']; $y) {
                    imagecopy($src, $this->im, 0, 0, $x, $y, $info[0], $info[1]);
                    imagecopy($src, $water, 0, 0, 0, 0, $info[0], $info[1]);
                    imagecopymerge($this->im, $src, $x, $y, 0, 0, $info[0], $info[1], $alpha);
                    $y += $info[1]+$cy;
                }
                $x += $info[0]+$cx;
            }
            //销毁零时图片资源
            imagedestroy($src);
        } while (!empty($this->gif) && $this->gifNext());
        //销毁水印资源
        imagedestroy($water);
        return $this;
    }
测试如下:

很赞哦! (0)

文章评论

    高端网站建设