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

TP5 添加平铺文字水印,并设置文字之间的间距和文字的角度

作者:小萝卜 2019-05-28 浏览 2297

简介TP5 添加平铺文字水印并设置文字之间的间距和文字的角度

TP5 添加平铺文字水印并设置文字之间的间距和文字的角度

1、安装扩展

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

composer require topthink/think-image

use think\Image;
class ....
public function test(){
   $image = Image::open('bg.jpg');
   //1.文字 2字体路径 3文字大小 4 文字颜色(#00000000)后面两位数可以控制文字的透明度  
   //5.文字的倾斜角度 6.x轴间距 7.y轴间距  注意字体路径是否正确
   $image>tiletext($text,'simkai.ttf',15,#ffffff,50,100,50)->save('look.jpg');
}
关键代码操作

 

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

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

    /**
     * 图像添平铺文字 带角度
     *
     * @param  string  $text   添加的文字
     * @param  string  $font   字体路径
     * @param  integer $size   字号
     * @param  string  $color  文字颜色
     * @param  integer $angle  文字倾斜角度
     * @param  int     $cx     x方向间距
     * @param  int     $cy     y方向间距
     * @return $this
     * @throws ImageException
     */
    public function tiletext($text, $font, $size, $color = '#00000000', $angle = 0 ,$cx = 10,$cy=10) {

        if (!is_file($font)) {
            throw new ImageException("不存在的字体文件:{$font}");
        }
        //获取文字信息
        $info = imagettfbbox($size, $angle, $font, $text);

        /* 设置颜色 */
        if (is_string($color) && 0 === strpos($color, '#')) {
            $color = str_split(substr($color, 1), 2);
            $color = array_map('hexdec', $color);
            if (empty($color[3]) || $color[3] > 127) {
                $color[3] = 0;
            }
        } elseif (!is_array($color)) {
            throw new ImageException('错误的颜色值');
        }
        do {
            //循环平铺水印 $this->info['width']是被处理图片的宽度
            for ($x = 0; $x < $this->info['width']; $x) {
                for ($y = 10; $y < $this->info['height']; $y) {
                    $col = imagecolorallocatealpha($this->im, $color[0], $color[1], $color[2], $color[3]);
                    imagettftext($this->im, $size, $angle, $x, $y, $col, $font, $text);
                    $y += $cy;
                }
                $x += $cx;
            }
            
        } while (!empty($this->gif) && $this->gifNext());
        return $this;
    }
测试如下:

很赞哦! (1)

文章评论

    高端网站建设