PHP-根据字符串和所用字体计算字符串所占宽高为多少像素
(2020-04-17 14:04:17)
标签:
imagettfbbox图片水印文字水印imagettftextimagejpeg |
分类: PHP |
其中返回一个数组, 有八个元素, 描述了四个角的坐标
0
1
2
3
4
5
6
7
$pos = imagettfbbox($font_size , 0, $font_file, $content);
其中$font_size、$font_file分别为字体的大小和所用字体;
$content 为文字内容字符串。
字符串所占宽度为:
$pos[2] - $pos[0]
字符串所占高度为:
$pos[5] - $pos[3]
之前写过一篇《php给图片加水印:文字水印和图片水印》,里面只是简单的设置。若将需求提升,水印(不论图片还是文字)的位置前端用户可以指定(左上、左下、右上、右下、中心),水印图片可以自行上传,文字水印可以自定义填写,并可设置文字大小,所有水印可设置透明度等需求。这时,对于图片水印我们可以很容易获得宽高像素,对于文字内容只是一个字符串,用strlen显然不行,这个是字符串长度,不是宽高像素,这样就使用到了本文前面提到的函数ImageTTFBBox(),就可以计算字符串的宽高像素。
文字水印实例代码:
//指定图片路径
$img = trim($_POST['img']);
//获取图片信息
$info = getimagesize($img);
//获取图片扩展名
$type = image_type_to_extension($info[2],false);
//动态的把图片导入内存中
$fun = "imagecreatefrom{$type}";
$image = $fun($img);
//指定字体类型
$font = '../ttfs/pingfang.ttf';
//指定字体颜色及透明度
$trans = intval($_POST['trans']); //水印字体的透明度
$color = imagecolorallocatealpha($image,255,255,0,$trans);
//指定字体内容及大小
$content = trim($_POST['content']);
$size = intval($_POST['size']);
//计算字符串宽高
$pos = imagettfbbox($size,0, $font, $content);
//字符串所占宽度
$str_width = $pos[2] - $pos[0];
//字符串所占高度
$str_height = $pos[5] - $pos[3];
//给图片添加文字
$location = intval($_POST['location']); //水印的位置
switch ( $location ) {
case 1://左上角
imagettftext($image, $size, 0, 10,10+$size, $color, $font, $content);
break;
case 2://右上角
imagettftext($image, $size, 0, $width-$str_width-10, 10+$size,$color, $font, $content);
break;
case 3://左下角
imagettftext($image,$size, 0, 10, $height-10, $color, $font, $content);
break;
case4://右下角
imagettftext($image, $size, 0, $width-$str_width-10,$height-10, $color, $font, $content);
break;
case 5://正中心
imagettftext($image, $size, 0, $width/2-$str_width/2,$height/2-$str_height/2, $color, $font, $content);
break;
default:
imagettftext($image, 30, 0, 100, 100, $color, $font, $content);
break;
}
//创建存放图片的文件夹
$lujing = '../attachment/images/';
if ( !is_dir( $lujing ) ) {
mkdir($lujing, 0777, true);
}
//保存合成后的图片
imagejpeg($image,$lujing.'photo_'.time().'.jpg');
//销毁图片
imagedestroy($image);