//字体库
define('FONTFILE','C:/Windows/Fonts/MSYH.TTC');
$text='2020/12/31';
$fontfile='C:/Windows/Fonts/MSYH.TTC';
$newImageName=NULL;//NULL 不保存输出到浏览器;若保存文件则改为要保存的文件名
//$newImageName='D:/myWorkspace/get_img/deal_img/jiaShuiYin/aaa.jpg';
$imgData=array('src'=>'D:/myWorkspace/get_img/deal_img/jiaShuiYin/sun.jpg',
'fontcolor'=>array(0,0,0),
'x'=>190,
'y'=>352,
);
water_text($text,$fontfile,$imgData,$newImageName);//加水印调用函数
/*
参数:$src--图片地址,$text--要添加的文字;$fontsize--文字大小;$jiaodu--文字偏角;$x--文字左上角x;$y--文字左上角y;
$fontcolor=array(255,0,0)---文字颜色,数组,长度3,红绿蓝颜色分配;$fontfile--字体文件路径,默认Fonts/times.ttf
water_text($src,$text='',$text2='',$fontsize=20,$jiaodu=0,$x=0,$y=0,$x2=0,$y2=0,$fontcolor=array(255,0,0),$fontfile='Fonts/times.ttf')
*/
function water_text($text,$fontfile,$imgData,$newImageName){
$fontsize=15;//字体大小
$jiaodu=0;//字体旋转角度
$x=$imgData['x'];//加水印x轴
$y=$imgData['y'];//加水印y轴
$src=$imgData['src'];//原图路径
$fontcolor=$imgData['fontcolor'];//字体颜色
//图片相关信息数组
$arr=getimagesize($src);
if(!$arr)return '读取图片出错';
switch($arr[2]){
//索引 2 给出的是图像的类型,返回的是数字,其中1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD
case 1:$img=imagecreatefromgif($src);break;
case 2:$img=imagecreatefromjpeg($src);break;
case 3:$img=imagecreatefrompng($src);break;
//default:;
}
if(!is_array($fontcolor)||count($fontcolor)<3)return 0;
if(!file_exists($fontfile))$fontfile=FONTFILE;
if(!file_exists($fontfile))return 'fontfile was not found';
//文字的宽高
$box=imagettfbbox($fontsize,$jiaodu,$fontfile,$text);
$k=max($box[2], $box[4]) - min($box[0], $box[6]);
$g=max($box[1], $box[3]) - min($box[5], $box[7]);
//设置左下脚
$x1=$x;
$y1=$y+$g;
//文字颜色
$color=imagecolorallocate($img,$fontcolor[0],$fontcolor[1],$fontcolor[2]);
//写入字符串
imagettftext($img,$fontsize,$jiaodu,$x1,$y1,$color,$fontfile,$text);
switch($arr[2]){
case 1:header('content-type:image/gif');imagegif($img,$newImageName,100);break;
case 2:header('content-type:image/jpeg');imagejpeg($img,$newImageName,100);break;
case 3:header('content-type:image/png');imagepng($img,$newImageName,100);break;
}
return 1;
}