PHP计算字符串真正的宽度和高度像素(图片加文字水印示例)

后端开发   发布日期:2025年05月30日   浏览次数:149

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

以上就是PHP计算字符串真正的宽度和高度像素(图片加文字水印示例)的详细内容,更多关于PHP计算字符串真正的宽度和高度像素(图片加文字水印示例)的资料请关注九品源码其它相关文章!