温馨提示:QQ登录和微信登录将于2023年7月15日下线,为了不影响你的正常使用,请尽快绑定邮箱,使用邮箱登录。操作方法:登录后点击右上角【会员中心】,再点击左边的【绑定邮箱】。

你好,欢迎来到js代码网。

微信登录邮箱登录

首页>编程语言> php给图片添加文字水印可控制位置,旋转,多行文字(亲测可用)

php给图片添加文字水印可控制位置,旋转,多行文字(亲测可用)

  • 分类:编程语言
  • 时间:2022-04-17
  • 阅读:2558

最近PHP项目需要用到文字水印,百度了很多,普遍都是存在问题的。以下代码亲测可用,已用于项目中。有需要的小伙伴可参考学习。


特别需要注意的是:

1、字体路径必须绝对路径。

2、生成图片质量,JPEG图像生成的图像的质量的是一个范围从0(最低质量,最小的文件大小)到100(最高质量,最大文件大小),而PNG生成图像的质量范围从0到9,如果错用,则会报错,程序中需要根据水印图片的格式来动态赋值。


以下为PHP文字水印代码:


<?php

/**
 * Text Watermark Point:
 *   #1      #2    #3
 *   #4      #5    #6
 *   #7      #8    #9
 */

/**
 * 给图片添加文字水印 可控制位置,旋转,多行文字    **有效字体未验证**
 * @param string $imgurl  图片地址
 * @param array $text   水印文字(多行以'|'分割)
 * @param int $fontSize 字体大小
 * @param type $color 字体颜色  如: 255,255,255
 * @param int $point 水印位置
 * @param type $font 字体
 * @param int $angle 旋转角度  允许值:  0-90   270-360 不含
 * @param string $newimgurl  新图片地址 默认使用后缀命名图片
 * @return boolean 
 */
function createWordsWatermark($imgurl, $text, $fontSize = '14', $color = '0,0,0', $point = '1', $font = 'simhei.ttf', $angle = 0, $newimgurl = '') {

    $imageCreateFunArr = array('image/jpeg' => 'imagecreatefromjpeg', 'image/png' => 'imagecreatefrompng', 'image/gif' => 'imagecreatefromgif');
    $imageOutputFunArr = array('image/jpeg' => 'imagejpeg', 'image/png' => 'imagepng', 'image/gif' => 'imagegif');

//获取图片的mime类型
    $imgsize = getimagesize($imgurl);

    if (empty($imgsize)) {
        return false; //not image
    }

    $imgWidth = $imgsize[0];
    $imgHeight = $imgsize[1];
    $imgMime = $imgsize['mime'];

    if (!isset($imageCreateFunArr[$imgMime])) {
        return false; //do not have create img function
    }
    if (!isset($imageOutputFunArr[$imgMime])) {
        return false; //do not have output img function
    }

    $imageCreateFun = $imageCreateFunArr[$imgMime];
    $imageOutputFun = $imageOutputFunArr[$imgMime];

    $im = $imageCreateFun($imgurl);

    /*
     * 参数判断
     */
    $color = explode(',', $color);
    $text_color = imagecolorallocate($im, intval($color[0]), intval($color[1]), intval($color[2])); //文字水印颜色
    $point = intval($point) > 0 && intval($point) < 10 ? intval($point) : 1; //文字水印所在的位置
    $fontSize = intval($fontSize) > 0 ? intval($fontSize) : 14;
    $angle = ($angle >= 0 && $angle < 90 || $angle > 270 && $angle < 360) ? $angle : 0; //判断输入的angle值有效性 
    $fontUrl = '/data/static/image/seccode/font/ch/' . ($font ? $font : 'simhei.ttf'); //有效字体未验证
    $text = explode('|', $text);
    $newimgurl = $newimgurl ? $newimgurl : $imgurl . '_WordsWatermark.jpg'; //新图片地址 统一图片后缀

    /**
     *  根据文字所在图片的位置方向,计算文字的坐标
     * 首先获取文字的宽,高, 写一行文字,超出图片后是不显示的
     */
    $textLength = count($text) - 1;
    $maxtext = 0;
    foreach ($text as $val) {
        $maxtext = strlen($val) > strlen($maxtext) ? $val : $maxtext;
    }
    $textSize = imagettfbbox($fontSize, 0, $fontUrl, $maxtext);
    $textWidth = $textSize[2] - $textSize[1]; //文字的最大宽度
    $textHeight = $textSize[1] - $textSize[7]; //文字的高度
    $lineHeight = $textHeight + 3; //文字的行高
//是否可以添加文字水印 只有图片的可以容纳文字水印时才添加
    if ($textWidth + 40 > $imgWidth || $lineHeight * $textLength + 40 > $imgHeight) {
        return false; //图片太小了,无法添加文字水印
    }

    if ($point == 1) { //左上角
        $porintLeft = 20;
        $pointTop = 20;
    } elseif ($point == 2) { //上中部
        $porintLeft = floor(($imgWidth - $textWidth) / 2);
        $pointTop = 20;
    } elseif ($point == 3) { //右上部
        $porintLeft = $imgWidth - $textWidth - 20;
        $pointTop = 20;
    } elseif ($point == 4) { //左中部
        $porintLeft = 20;
        $pointTop = floor(($imgHeight - $textLength * $lineHeight) / 2);
    } elseif ($point == 5) { //正中部
        $porintLeft = floor(($imgWidth - $textWidth) / 2);
        $pointTop = floor(($imgHeight - $textLength * $lineHeight) / 2);
    } elseif ($point == 6) { //右中部
        $porintLeft = $imgWidth - $textWidth - 20;
        $pointTop = floor(($imgHeight - $textLength * $lineHeight) / 2);
    } elseif ($point == 7) { //左下部
        $porintLeft = 20;
        $pointTop = $imgHeight - $textLength * $lineHeight - 20;
    } elseif ($point == 8) { //中下部
        $porintLeft = floor(($imgWidth - $textWidth) / 2);
        $pointTop = $imgHeight - $textLength * $lineHeight - 20;
    } elseif ($point == 9) { //右下部
        $porintLeft = $imgWidth - $textWidth - 20;
        $pointTop = $imgHeight - $textLength * $lineHeight - 20;
    }

//如果有angle旋转角度,则重新设置 top ,left 坐标值
    if ($angle != 0) {
        if ($angle < 90) {
            $diffTop = ceil(sin($angle * M_PI / 180) * $textWidth);

            if (in_array($point, array(1, 2, 3))) {// 上部 top 值增加
                $pointTop += $diffTop;
            } elseif (in_array($point, array(4, 5, 6))) {// 中部 top 值根据图片总高判断
                if ($textWidth > ceil($imgHeight / 2)) {
                    $pointTop += ceil(($textWidth - $imgHeight / 2) / 2);
                }
            }
        } elseif ($angle > 270) {
            $diffTop = ceil(sin((360 - $angle) * M_PI / 180) * $textWidth);

            if (in_array($point, array(7, 8, 9))) {// 上部 top 值增加
                $pointTop -= $diffTop;
            } elseif (in_array($point, array(4, 5, 6))) {// 中部 top 值根据图片总高判断
                if ($textWidth > ceil($imgHeight / 2)) {
                    $pointTop = ceil(($imgHeight - $diffTop) / 2);
                }
            }
        }
    }

    foreach ($text as $key => $val) {
        imagettftext($im, $fontSize, $angle, $porintLeft, $pointTop + $key * $lineHeight, $text_color, $fontUrl, $val);
    }

// 输出图像
// JPEG图像生成的图像的质量的是一个范围从0(最低质量,最小的文件大小)到100(最高质量,最大文件大小)
// PNG生成图像的质量范围从0到9的
    $imageOutputFun($im, $newimgurl, 80);

// 释放内存
    imagedestroy($im);
    return $newimgurl;
}

//$imgurl, $text, $fontSize='14', $color='0,0,0', $point='1', $font = 'simhei.ttf', $angle=0, $newimgurl=''
$img = createWordsWatermark('./data/attachment/portal/202204/13/120000zb0zepfkpjkbpfbs.jpg', 'js代码网|www.jsdaima.com', '12', '255,1,1', '7', '', '30', './newpic.jpg');
echo '<img src="' . $img . '" />';

?>

相关文章