PHP如何计算字符串真正的宽度和高度像素

后端开发   发布日期:2023年07月09日   浏览次数:518

这篇文章主要介绍“PHP如何计算字符串真正的宽度和高度像素”,在日常操作中,相信很多人在PHP如何计算字符串真正的宽度和高度像素问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”PHP如何计算字符串真正的宽度和高度像素”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

PHP计算字符串用strlen()只能得到字符串长度,不是宽高像素,使用到了php函数ImageTTFBBox(),就可以根据字体的大小和所用字体计算字符串的宽高像素。

ImageTTFBBox函数介绍

imagettfbbox() 计算并返回一个包围着 TrueType 文本范围的虚拟方框的像素大小。

语法

  1. imagettfbbox ( float $size , float $angle , string $fontfile , string $text )

参数

参数 必需的 描述
size 像素单位的字体大小。
angle text 将被度量的角度大小。
fontfile TrueType 字体文件的文件名(可以是 URL)。根据 PHP 所使用的 GD 库版本,可能尝试搜索那些不是以 '/' 开头的文件名并加上 '.ttf' 的后缀并搜索库定义的字体路径。
text 要度量的字符串。

返回值

返回一个含有 8 个单元的数组表示了文本外框的四个角:

  • 0 左下角 X 位置

  • 1 左下角 Y 位置

  • 2 右下角 X 位置

  • 3 右下角 Y 位置

  • 4 右上角 X 位置

  • 5 右上角 Y 位置

  • 6 左上角 X 位置

  • 7 左上角 Y 位置

这些点是相对于文本的而和角度无关,因此“左上角”指的是以水平方向看文字时其左上角。

本函数同时需要 GD 库和 FreeType 库。

图片加文字水印示例

  1. <?php
  2. //指定图片路径
  3. $img = trim($_POST['img']);
  4. //获取图片信息
  5. $info = getimagesize($img);
  6. //获取图片扩展名
  7. $type = image_type_to_extension($info[2],false);
  8. //动态的把图片导入内存中
  9. $fun = "imagecreatefrom{$type}";
  10. $image = $fun($img);
  11. //指定字体类型
  12. $font = '../ttfs/pingfang.ttf';
  13. //指定字体颜色及透明度
  14. $trans = intval($_POST['trans']); //水印字体的透明度
  15. $color =imagecolorallocatealpha($image,255,255,0,$trans);
  16. //指定字体内容及大小
  17. $content= trim($_POST['content']);
  18. $size= intval($_POST['size']);
  19. //计算字符串宽高
  20. $pos =imagettfbbox($size,0,$font, $content);
  21. //字符串所占宽度
  22. $str_width = $pos[2] -$pos[0];
  23. //字符串所占高度
  24. $str_height = $pos[5] -$pos[3];
  25. //给图片添加文字
  26. $location =intval($_POST['location']); //水印的位置
  27. switch ( $location )
  28. {
  29. case 1://左上角
  30. imagettftext($image, $size, 0,
  31. 10,10+$size, $color, $font, $content);
  32. break;
  33. case 2://右上角
  34. imagettftext($image, $size, 0,$width-$str_width-10, 10+$size,$color, $font,$content);
  35. break;
  36. case 3://左下角
  37. imagettftext($image,$size, 0, 10,$height-10, $color, $font, $content);
  38. break;
  39. case4://右下角
  40. imagettftext($image, $size, 0,$width-$str_width-10,$height-10, $color, $font,$content);
  41. break;
  42. case 5://正中心
  43. imagettftext($image, $size, 0,$width/2-$str_width/2,$height/2-$str_height/2, $color, $font,$content);
  44. break;
  45. default:
  46. imagettftext($image, 30, 0, 100, 100,$color, $font, $content);
  47. break;
  48. }
  49. //创建存放图片的文件夹
  50. $lujing ='../attachment/images/';
  51. if ( !is_dir( $lujing ) )
  52. {
  53. mkdir($lujing, 0777,true);
  54. }
  55. //保存合成后的图片
  56. imagejpeg($image,$lujing.'photo_'.time().'.jpg');
  57. //销毁图片
  58. imagedestroy($image);

以上就是PHP如何计算字符串真正的宽度和高度像素的详细内容,更多关于PHP如何计算字符串真正的宽度和高度像素的资料请关注九品源码其它相关文章!