Thinkphp实现图片水印平铺效果

 MeLiu   2019-04-23 23:28   3205 人阅读  0 条评论

图水印平铺,有需要的了解一下
调用图片水印平铺代码

use think\Image;
class ....
public function test(){
        $image = Image::open('bg.jpg');
        // 给原图设置水印图片(colleced.png)并保存water_image.png
        $image->tilewater('colleced.png',100)->save('water_image.png');
        echo "<img src='/water_image.png'/>";
 }

关键代码操作
1、打开第三方类库文件:vendor\topthink\think-image\src\Image.php
2、把下面代码复制到上方地址的图片处理类库中(增加一个图片处理方法)

/**
     * 添加图片水印平铺
     *
     * @param  string $source 水印图片路径
     * @param int     $alpha  透明度
     * @return $this
     */
    public function tilewater($source, $alpha = 100)
    {
        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']-10; $x) {
                for ($y = 0; $y < $this->info['height']-10; $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];
                }
                $x += $info[0];
            }
            //销毁零时图片资源
            imagedestroy($src);
        } while (!empty($this->gif) && $this->gifNext());
        //销毁水印资源
        imagedestroy($water);
        return $this;
    }


本文地址:http://mobaishare.com/post/16.html
版权声明:本文为原创文章,版权归 MeLiu 所有,欢迎分享本文,转载请保留出处!

 发表评论


表情

还没有留言,还不快点抢沙发?