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

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

ImageTTFBBox函数介绍

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

语法

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

参数

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

返回值

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

  • 0 左下角 X 位置
  • 1 左下角 Y 位置
  • 2 右下角 X 位置
  • 3 右下角 Y 位置
  • 4 右上角 X 位置
  • 5 右上角 Y 位置
  • 6 左上角 X 位置
  • 7 左上角 Y 位置

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

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

图片加文字水印示例

<?php
//指定图片路径
$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);

原文地址: