使用Php给图片添加中文水印,水印的位置自动居图片中间。自定义图片生成后的路径,根据图片保存的路径自动生成对应的文件夹。
function gPic_Url($content){
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";//正则
preg_match_all($pattern,$content,$match);//匹配图片
return $match[1];//返回所有图片的路径
}
function mkdirs($pathname, $mode = 0755){
is_dir(dirname($pathname)) || mkdirs(dirname($pathname), $mode);
return is_dir($pathname) || @mkdir($pathname, $mode);
}
function diy($imgs,$title) {//,$title
//img path
$domain ='shangjiewh';
if(strpos($imgs,$domain)){
$imageUrl= str_replace('http://www.shangjiewh.com','',$imgs);
}else{
$imageUrl= $imgs;
}
$url = pathinfo($imageUrl);
$dir = './k/'.$url['dirname'].'/';
if(!is_dir($dir))
{
@mkdirs($dir, 0777);
@fclose(fopen($dir.'/index.htm', 'w'));
}
//img path end
//img format
$format=$url['extension'];
if($format=='jpg'){
$bigImgPath = './rand/'.rand(1,4).'.jpg';
}else{
$bigImgPath = './rand/'.rand(1,4).'.png';
}
//img format end
$img = imagecreatefromstring(file_get_contents($bigImgPath));
$font = './fonts/yy.ttf';
//字体,字体文件需保存到相应文件夹下
$black = imagecolorallocate($img, 0, 255, 255);
//字体颜色 RGB
$fontSize = 20;
//字体大小
$circleSize = 0;
//旋转角度
//$left = 60; //左边距
//$top =120; //顶边距
$imgWidth = imagesx($img);
$imgHeight = imagesy($img);
$fonts = 10;
$fontWidth = imagefontwidth($fonts);
$fontHeight = imagefontheight($fonts);
$iswrite=true;
$tp=0;
$hang_size=40;
$temp_string = "";
$left = ($imgWidth-$fontWidth*strlen($title))/4;
$top = ($imgHeight-$fontHeight)/2;
$rowheight=5;
$width=400;
$tempstr = "";
$row = 0;
$y=100;
for ($i = 0; $i < mb_strlen($title, 'utf8'); $i++) {
if($row >= 3) {
break;
}
//第一 获取下一个拼接好的宽度 如果下一个拼接好的已经大于width了,就在当前的换行 如果不大于width 就继续拼接
$tempstr = $tempstr.mb_substr($title, $i, 1, 'utf-8');
//当前的文字
$nextstr = $tempstr.mb_substr($title, $i+1, 1, 'utf-8');
//下一个字符串
$nexttemp = imagettfbbox($fontSize, 0, $font, $nextstr);
//用来测量每个字的大小
$nextsize = ($nexttemp[2]-$nexttemp[0]);
if($nextsize > 400) {
//大于整体宽度限制 直接换行 这一行写入画布
$row = $row+1;
//获取文字所需的尺寸大小
imagettftext($img, $fontSize, 0, ceil(($imgWidth - $nexttemp[2]) / 2), $top, $black, $font, $tempstr);
$top = $top+$fontSize+$rowheight;
$tempstr = "";
} else if($i+1 == mb_strlen($title, 'utf8') && $nextsize<$width-10) {
$left = ($imgWidth-$fontWidth*strlen($tempstr))/4;
imagettftext($img, $fontSize, 0, ceil(($imgWidth - $nexttemp[2]) / 2), $top+$fontSize+$rowheight, $black, $font, $tempstr);
}
}
//imagefttext($img, $fontSize, $circleSize, $left, $top, $black, $font, $title);//zhix.net| 智昕网络
//$fileimgname = time()."-".rand(1000,9999).".jpg";
$fileimgname = basename($imgs);
imagepng($img,$dir.$fileimgname);
//在 images 目录下就会生成一个 circle.png 文件,上面也可设置相应的保存目录及文件名。
//$saveimg='./k/img/'.$fileimgname;
imagedestroy($img);
}