PHP文字转图片 PHP文字生成图片Logo


使用场景很多,而且这个图片是自适应的,关于字体的话,推荐大家使用黑体或者间距小一点的字体,否则可能会产生BUG。

trans.php代码:

<?php
$text_string     = $_REQUEST["t"];
$font_ttf        = "simhei.ttf"; 
$font_size       = 14; 
$text_angle      = 0; 
$text_padding    = 0;
$the_box        = calculateTextBox($text_string, $font_ttf, $font_size, $text_angle); 
$imgWidth    = $the_box["width"] + $text_padding; 
$imgHeight    = $the_box["height"] + $text_padding; 
$image = imagecreate($imgWidth,$imgHeight); 
imagecolorallocatealpha($image,255,255,255,127); 
$color = imagecolorallocate($image,0,0,0); 
imagettftext($image, 
$font_size, 
$text_angle, 
$the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2), 
$the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2), 
$color, 
$font_ttf, 
$text_string); 

header("Content-Type: image/png"); 
imagepng($image); 
imagedestroy($image); 

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) { 
    $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text); 
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6])); 
    $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6])); 
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7])); 
    $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7])); 
    return array( 
     "left"   => abs($minX) - 1, 
     "top"    => abs($minY) - 1, 
     "width"  => $maxX - $minX, 
     "height" => $maxY - $minY, 
     "box"    => $rect 
    ); 
} 
?>

Img代码调用:

<img src="/trans.php?t=神霄道境" />

- END -


文章链接:https://www.ityinhu.com/748.html

作者邮箱:ponyj@qq.com