php文字水印,支持自动换行,自动截取(包括汉字)

php文字水印,支持自动换行,自动截取(包括汉字)(www.rijigu.com提供)

首先要建立image.class.php类,这个类选自dedecms的图片水印类,但是经过改变后可实现以下几个功能:

1.在图片上自定义位置添加水印文字;

2.如果文字太长,会自动截取可写下的文字,支持汉字,英文;

3.支持utf8,gbk截取;

4.在可编辑区域支持自动换行;

<?php
/**
 * 图像处理类
 * @license        http://www.rijigu.com
 * @link           http://www.rijigu.com
 */
class image
{
    var $attachinfo;
    var $targetfile;    //图片路径
    var $imagecreatefromfunc;
    var $imagefunc;
    var $attach;
    var $animatedgif;
    var $watermarkquality;
    var $watermarktext;
    var $thumbstatus;
    var $watermarkstatus;
    
    // 析构函数,兼容PHP4
    function image($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $cfg_watermarktype, $photo_marktrans,$trueMarkimg, $attach = array())
    {
        $this->__construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $cfg_watermarktype, $photo_marktrans,$trueMarkimg, $attach);
    }

    // 析构函数
    function __construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $cfg_watermarktype, $photo_marktrans,$trueMarkimg, $attach = array())
    {
        $this->thumbstatus = $cfg_thumb;
        $this->watermarktext = $cfg_watermarktext;
        $this->watermarkstatus = $photo_waterpos;
        $this->watermarkquality = $photo_marktrans;
        $this->watermarkminwidth = $photo_wwidth;
        $this->watermarkminheight = $photo_wheight;
        $this->watermarktype = $cfg_watermarktype;
        $this->watermarktrans = $photo_diaphaneity;
        $this->animatedgif = 0;
        $this->targetfile = $targetfile;
        $this->attachinfo = @getimagesize($targetfile);
        $this->attach = $attach;


        switch($this->attachinfo['mime'])
        {
            case 'image/jpeg':
                $this->imagecreatefromfunc = function_exists('imagecreatefromjpeg') ? 'imagecreatefromjpeg' : '';
                $this->imagefunc = function_exists('imagejpeg') ? 'imagejpeg' : '';
                break;
            case 'image/gif':
                $this->imagecreatefromfunc = function_exists('imagecreatefromgif') ? 'imagecreatefromgif' : '';
                $this->imagefunc = function_exists('imagegif') ? 'imagegif' : '';
                break;
            case 'image/png':
                $this->imagecreatefromfunc = function_exists('imagecreatefrompng') ? 'imagecreatefrompng' : '';
                $this->imagefunc = function_exists('imagepng') ? 'imagepng' : '';
                break;
        }//为空则匹配类型的函数不存在

        $this->attach['size'] = empty($this->attach['size']) ? @filesize($targetfile) : $this->attach['size'];
        if($this->attachinfo['mime'] == 'image/gif')
        {
            $fp = fopen($targetfile, 'rb');
            $targetfilecontent = fread($fp, $this->attach['size']);
            fclose($fp);
            $this->animatedgif = strpos($targetfilecontent, 'NETSCAPE2.0') === false ? 0 : 1;
        }
    }

    /**
     *  生成缩略图
     *
     * @access    public
     * @param     int  $thumbwidth  图片宽度
     * @param     int  $thumbheight  图片高度
     * @param     int  $preview  是否预览
     * @return    void
     */
    function thumb($thumbwidth, $thumbheight, $preview = 0)
    {
        $this->thumb_gd($thumbwidth, $thumbheight, $preview);

        if($this->thumbstatus == 2 && $this->watermarkstatus)
        {
            $this->image($this->targetfile, $this->attach);
            $this->attach['size'] = filesize($this->targetfile);
        }
    }

    /**
     *  图片水印
     *
     * @access    public
     * @param     int   $preview  是否预览
     * @return    void
     */
    function watermark($preview = 0)
    {
        if($this->watermarkminwidth && $this->attachinfo[0] <= $this->watermarkminwidth && $this->watermarkminheight && $this->attachinfo[1] <= $this->watermarkminheight)
        {
            return ;
        }
        $this->watermark_gd($preview);
    }

    /**
     *  使用gd生成缩略图
     *
     * @access    public
     * @param     int  $thumbwidth  图片宽度
     * @param     int  $thumbheight  图片高度
     * @param     int  $preview  是否预览
     * @return    void
     */
    function thumb_gd($thumbwidth, $thumbheight, $preview = 0)
    {

        if($this->thumbstatus && function_exists('imagecreatetruecolor') && function_exists('imagecopyresampled') && function_exists('imagejpeg'))
        {
            $imagecreatefromfunc = $this->imagecreatefromfunc;
            $imagefunc = $this->thumbstatus == 1 ? 'imagejpeg' : $this->imagefunc;
            list($imagewidth, $imageheight) = $this->attachinfo;
            if(!$this->animatedgif && ($imagewidth >= $thumbwidth || $imageheight >= $thumbheight))
            {
                $attach_photo = $imagecreatefromfunc($this->targetfile);
                $x_ratio = $thumbwidth / $imagewidth;
                $y_ratio = $thumbheight / $imageheight;
                if(($x_ratio * $imageheight) < $thumbheight)
                {
                    $thumb['height'] = ceil($x_ratio * $imageheight);
                    $thumb['width'] = $thumbwidth;
                }
                else
                {
                    $thumb['width'] = ceil($y_ratio * $imagewidth);
                    $thumb['height'] = $thumbheight;
                }
                $targetfile = !$preview ? ($this->thumbstatus == 1 ? $this->targetfile.'.thumb.jpg' : $this->targetfile) : './watermark_tmp.jpg';
                $thumb_photo = imagecreatetruecolor($thumb['width'], $thumb['height']);
                imagecopyresampled($thumb_photo, $attach_photo, 0, 0, 0, 0, $thumb['width'], $thumb['height'], $imagewidth, $imageheight);
                if($this->attachinfo['mime'] == 'image/jpeg')
                {
                    $imagefunc($thumb_photo, $targetfile, 100);
                }
                else
                {
                    $imagefunc($thumb_photo, $targetfile);
                }
                $this->attach['thumb'] = $this->thumbstatus == 1 ? 1 : 0;
            }
        }
    }
	
	/* 返回一个字符的数组 */
	function chararray($str,$charset="utf-8"){
		$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']	  = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']	  = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		return $match;
	}
	
	/* 返回一个字符串在图片中所占的宽度 */
	function charwidth($fontsize,$fontangle,$ttfpath,$char){
		$box = @imagettfbbox($fontsize,$fontangle,$ttfpath,$char);
        $width = max($box[2], $box[4]) - min($box[0], $box[6]);
		return $width;
	}
	
    /**
     *  使用gd进行水印
     *
     * @access    public
     * @param     int   $preview  是否预览
     * @return    void
     */
    function watermark_gd($preview = 0)
    {
        if($this->watermarkstatus && function_exists('imagecopy') && function_exists('imagealphablending') && function_exists('imagecopymerge'))
        {
            $imagecreatefunc = $this->imagecreatefromfunc;
            $imagefunc = $this->imagefunc;
            list($imagewidth, $imageheight) = $this->attachinfo;
            if($this->watermarktype < 2)
            {
                $watermark_file = $this->watermarktype == 1 ? DEDEDATA.'/mark/mark.png' : DEDEDATA.'/mark/mark.gif';
                $watermarkinfo = @getimagesize($watermark_file);
                $watermark_logo = $this->watermarktype == 1 ? @imagecreatefrompng($watermark_file) : @imagecreatefromgif($watermark_file);
                if(!$watermark_logo)
                {
                    return ;
                }
                list($logowidth, $logoheight) = $watermarkinfo;
            }
            else
            {
                $box = @imagettfbbox($this->watermarktext['size'], $this->watermarktext['angle'], $this->watermarktext['fontpath'],$this->watermarktext['text']);
                $logowidth = max($box[2], $box[4]) - min($box[0], $box[6]);
                $logoheight = max($box[1], $box[3]) - min($box[5], $box[7]);
                $ax = min($box[0], $box[6]) * -1;
                $ay = min($box[5], $box[7]) * -1;
            }
			
			
			$imgMaxWidth = $this->watermarktext['imgMaxWidth'];
			$imgMaxHeight = $this->watermarktext['imgMaxHeight'];
			$base_x = $this->watermarktext['base_x']+$ax;
			$base_y = $this->watermarktext['base_y']+$ay;
			$actRows = floor($imgMaxHeight/$logoheight);//实际可使用的行数
			$actwidth = $imgMaxWidth*$actRows;//实际可用的字符串宽度
			$chararray = $this -> chararray($this->watermarktext['text']);
			$textarray = array();
			$width = 0;
			$rowwidth = 0;
			$rowstring = '';
			$i = 0;
			foreach($chararray[0] as $key => $val){
				$temp_width = $this -> charwidth($this->watermarktext['size'], $this->watermarktext['angle'], $this->watermarktext['fontpath'],$val)+$this->watermarktext['extend_len'];
				if($width+$temp_width>$actwidth){
					$textarray[$i]['text'] = $rowstring;
					$textarray[$i]['x'] = $base_x;
					$textarray[$i]['y'] = $base_y+$i*$logoheight;
					break;
				}
				$width += $temp_width;
				if($key == (count($chararray[0])-1)){
					$rowwidth += $temp_width;
					$rowstring .= $val;
				}
				if($rowwidth+$temp_width>$imgMaxWidth || $key == (count($chararray[0])-1)){
					$textarray[$i]['text'] = $rowstring;
					$textarray[$i]['x'] = $base_x;
					$textarray[$i]['y'] = $base_y+$i*$logoheight;
					$rowwidth = 0;
					$rowstring = '';
					$i = $i + 1;
				}
				$rowwidth += $temp_width;
				$rowstring .= $val;
			}
            $wmwidth = $imagewidth - $imgMaxWidth;
            $wmheight = $imageheight - $imgMaxHeight;

            if(($this->watermarktype < 2 && is_readable($watermark_file) || $this->watermarktype == 2) && $wmwidth > 10 && $wmheight > 10 && !$this->animatedgif)
            {
                switch($this->watermarkstatus)
                {
                    case 1:

                        $x = +5;
                        $y = +5;
                        break;
                    case 2:
                        $x = ($imagewidth - $logowidth) / 2;
                        $y = +5;
                        break;
                    case 3:
                        $x = $imagewidth - $logowidth - 5;
                        $y = +5;
                        break;
                    case 4:
                        $x = +5;
                        $y = ($imageheight - $logoheight) / 2;
                        break;
                    case 5:
                        $x = ($imagewidth - $logowidth) / 2;
                        $y = ($imageheight - $logoheight) / 2;
                        break;
                    case 6:
                        $x = $imagewidth - $logowidth - 5;
                        $y = ($imageheight - $logoheight) / 2;
                        break;
                    case 7:
                        $x = +5;
                        $y = $imageheight - $logoheight - 5;
                        break;
                    case 8:
                        $x = ($imagewidth - $logowidth) / 2;
                        $y = $imageheight - $logoheight - 5;
                        break;
                    case 9:
                        $x = $imagewidth - $logowidth - 5;
                        $y = $imageheight - $logoheight -5;
                        break;
					case 10:
						break;
                }
                $dst_photo = @imagecreatetruecolor($imagewidth, $imageheight);
                $target_photo = $imagecreatefunc($this->targetfile);
                imagecopy($dst_photo, $target_photo, 0, 0, 0, 0, $imagewidth, $imageheight);
                if($this->watermarktype == 1)
                {
                    imagecopy($dst_photo, $watermark_logo, $x, $y, 0, 0, $logowidth, $logoheight);
                }
                elseif($this->watermarktype == 2)
                {
                    if(($this->watermarktext['shadowx'] || $this->watermarktext['shadowy']) && $this->watermarktext['shadowcolor'])
                    {
                        $shadowcolorrgb = explode(',', $this->watermarktext['shadowcolor']);
                        $shadowcolor = imagecolorallocate($dst_photo, $shadowcolorrgb[0], $shadowcolorrgb[1], $shadowcolorrgb[2]);
                        imagettftext($dst_photo, $this->watermarktext['size'], $this->watermarktext['angle'],
                        $x + $ax + $this->watermarktext['shadowx'], $y + $ay + $this->watermarktext['shadowy'], $shadowcolor,
                        $this->watermarktext['fontpath'], $this->watermarktext['text']);
                    }
                    $colorrgb = explode(',', $this->watermarktext['color']);
                    $color = imagecolorallocate($dst_photo, $colorrgb[0], $colorrgb[1], $colorrgb[2]);
					foreach($textarray as $val){
							imagettftext($dst_photo, $this->watermarktext['size'], $this->watermarktext['angle'],
                    $val['x'], $val['y'], $color, $this->watermarktext['fontpath'], $val['text']);
					}
                    //imagettftext($dst_photo, $this->watermarktext['size'], $this->watermarktext['angle'],
                    //$x + $ax, $y + $ay, $color, $this->watermarktext['fontpath'], $this->watermarktext['text']);
                }
                else
                {
                    imagealphablending($watermark_logo, true);
                    imagecopymerge($dst_photo, $watermark_logo, $x, $y, 0, 0, $logowidth, $logoheight, $this->watermarktrans);
                }
                $targetfile = !$preview ? $this->targetfile : './watermark_tmp.jpg';
                if($this->attachinfo['mime'] == 'image/jpeg')
                {
                    $imagefunc($dst_photo, $targetfile, $this->watermarkquality);
                }
                else
                {
                    $imagefunc($dst_photo, $targetfile);
                }
                $this->attach['size'] = filesize($this->targetfile);
            }
        }
    }
}//End Class


下面是引用示例,自己要准备一张jpg的图片,还有字体,字体可以任选,如果要想支持中文的话,所选字体必须要支持中文。笔者就是因为这个折腾了不少时间。

<?php
/* php文字水印,支持自动换行,自动截取(包括汉字)(www.rijigu.com提供)
	文件中未带字体,请自己准备字体
	$srcFile 图片路径
	$photo_watertext 要写入的文字
	$base_x 开始的x坐标
	$base_y 开始的y坐标
	$photo_MaxWidth 可写区域的最大宽度(行宽)
	$photo_MaxHeight 可写区域的最大高度
	$photo_fontcolor 字体颜色
	$photo_fontsize 字体大小
	$photo_fontttf ttf路径
	$extend_len=0 单行文字偏移量
*/
require_once('image.class.php');
WaterImg("b.png",$sy,82,165,265,120,'67,157,252',20,'simhei.ttf',4);//附加内容
function WaterImg($srcFile,$photo_watertext,$base_x,$base_y,$photo_MaxWidth,$photo_MaxHeight,$photo_fontcolor,$photo_fontsize,$photo_fontttf,$extend_len=0)
{
	$cfg_watermarktext['text'] = $photo_watertext;
	$cfg_watermarktext['base_x'] = $base_x;
	$cfg_watermarktext['base_y'] = $base_y;
	$cfg_watermarktext['imgMaxWidth'] = $photo_MaxWidth;
	$cfg_watermarktext['imgMaxHeight'] = $photo_MaxHeight;
	$cfg_watermarktext['color'] = $photo_fontcolor;
	$cfg_watermarktext['size'] = $photo_fontsize;
	$cfg_watermarktext['fontpath'] = $photo_fontttf;
	$cfg_watermarktext['angle'] = '0';
	$cfg_watermarktext['shadowx'] = '0';
	$cfg_watermarktext['shadowy'] = '0';
	$cfg_watermarktext['shadowcolor'] = '0,0,0';
	$cfg_watermarktext['extend_len'] = $extend_len;
	$photo_marktrans = 85;
	$img = new image($srcFile,0, $cfg_watermarktext,1,100, 120, 120,2,85,'');
	$img->watermark(0);
}	
?>

这个应用程序是由www.rijigu.com 提供的,希望跟多网友来到日记谷,支持 日记谷,让日记谷成为最好的日记网站。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值