PHP图片文字合成居中

180it 2021-05-28 PM 1041℃ 0条
<?php
function imageAddText($path, $content, $x = 'auto', $y = 'auto', $fontSize = 38, $font = './t.ttf'){
    $temp = array(1=>'gif', 2=>'jpeg', 3=>'png');
    // 获取图片信息
    $imageInfo = getimagesize($path);
    $imageType = $temp[$imageInfo[2]];
 
    $getfunc = "imagecreatefrom$imageType";
    $outfunc = "image$imageType";
 
    $resource = $getfunc($path);
 
    $width    = imagesx($resource);
    $height   = imagesy($resource);
 
    $color = imagecolorallocatealpha($resource, 255, 255, 255, 0);
 
    $fontBox = imagettfbbox($fontSize, 0, $font, $content);//文字水平居中实质
 
    if ($x === 'auto'){
        $x = ceil(($width - $fontBox[2]) / 2);
    }
    if ($y === 'auto'){
    $y = ceil(($height - $fontBox[1] - $fontBox[7]) / 2);
}
 
    imagettftext($resource, $fontSize, 0, $x, $y, $color, $font, $content);
 
    /*输出图片*/
    //浏览器输出
    header("Content-type:".$imageType);
    $outfunc($resource);
}
 
// 自动居中
// imageAddText('./test.jpg', 'My name is Siam,中文名是宣言');
// 声明x y值
// imageAddText('./test.jpg', 'My name is Siam,中文名是宣言',200);
// imageAddText('./test.jpg', 'My name is Siam,中文名是宣言','auto', '300');
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP图片文字合成居中