登录

图片水印换行 + 图片拼接

PHP笔记
0 793

  /**
     * 图片拼接
     */
    public function image_stitching()
    {
        $this->water(imagecreatefrompng('img/body.png'));
        $imgs = array();
        $imgs[0] = 'img/top.png';
        $imgs[1] = 'img/body_water.png';
        $imgs[2] = 'img/foot.png';
        $target = 'img/sskb.png'; //背景图片

        $target_img = Imagecreatefrompng($target);

        $source = array();

        foreach ($imgs as $k => $v) {
            $source[$k]['source'] = Imagecreatefrompng($v);
            $source[$k]['size'] = getimagesize($v);
        }

        // imagecopy ($target_img$source[0]['source']2200$source[0]['size'][0]$source[0]['size'][1]);
        // imagecopy ($target_img$source[1]['source']250200$source[1]['size'][0]$source[1]['size'][1]);
        $tmpy = 0; // 图片之间的间距
        for ($i = 0; $i < count($imgs); $i++) {
            @imagecopy($target_img $source[$i]['source'] 0 $tmpy 0 0 $source[$i]['size'][0] $source[$i]['size'][1]);
            $tmpy = $tmpy + $source[$i]['size'][1];
        }
        Imagepng($target_img 'img/new_sskb.png');
        @unlink('img/body_water.png');
    }

    /**
     * 水印
     */
    public function water($bg)
    {
        $content = "文字内容。";

//        $bg = imagecreatefrompng('body.png');

        $fontFamily = 'simkai.ttf';
        $fontSize = 60;
        $charset = 'utf8';
        $textcolor = imagecolorallocate($bg 0 0 0);
        $lineHeight = 100;
        $startX = 100;
        $startY = 70;

        $lineWidth = imagesx($bg) - $startX - $startY;

        $lineArr = $this->autoLineSplit($content $fontFamily $fontSize $charset $lineWidth);

        foreach ($lineArr as $k => $v) {
            imagettftext($bg $fontSize 0 $startX ($startY + ($lineHeight * $k)) $textcolor $fontFamily $v);
        }

        $fileName = 'img/body_water.png';

        imagepng($bg $fileName 3);
    }

    /**
     * 绘图文字分行函数
     * by COoL
     * - 输入:
     * str: 原字符串
     * fontFamily: 字体
     * fontSize: 字号
     * charset: 字符编码
     * width: 限制每行宽度(px)
     * - 输出:
     * 分行后的字符串数组
     */
    function autoLineSplit($str $fontFamily $fontSize $charset $width)
    {
        $result = [];
        $len = (strlen($str) + mb_strlen($str $charset)) / 2;
        // 计算总占宽
        $dimensions = imagettfbbox($fontSize 0 $fontFamily $str);
        $textWidth = abs($dimensions[4] - $dimensions[0]);
        // 计算每个字符的长度
        $singleW = $textWidth / $len;
        // 计算每行最多容纳多少个字符
        $maxCount = floor($width / $singleW);
        while ($len > $maxCount) {
            // 成功取得一行
            $result[] = mb_strimwidth($str 0 $maxCount '' $charset);
            // 移除上一行的字符
            $str = str_replace($result[count($result) - 1] '' $str);
            // 重新计算长度
            $len = (strlen($str) + mb_strlen($str $charset)) / 2;
        }
        // 最后一行在循环结束时执行
        $result[] = $str;
        return $result;
    }

发表评论

0 个回复