PHP计算字符串真正的宽度和高度像素(图片加文字水印示例)(php字符长度)这都可以?

随心笔谈12个月前发布 admin
93 0

<?php
//指定图片路径
$img=trim($_POST[‘img’]);

//获取图片信息
$info=getimagesize($img);

//获取图片扩展名
$type=image_type_to_extension($info[2],false);

//动态的把图片导入内存中
$fun=”imagecreatefrom{$type}”;
$image=$fun($img);

//指定字体类型
$font=’https://www.jb51.net/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=’https://www.jb51.net/attachment/images/’;
if ( !is_dir( $lujing ) )
{
mkdir($lujing, 0777,true);
}

//保存合成后的图片
imagejpeg($image,$lujing.’photo_’.time().’.jpg’);

//销毁图片
imagedestroy($image);

© 版权声明

相关文章