在php图像中居中文字 [英] Centering text in php image

查看:229
本文介绍了在php图像中居中文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何使用imagettftext在php创建的图像中居中放置文本.这是我的代码:

I'm not sure how I can center text in a php-created image using imagettftext. Here's my code:

header('Content-Type: image/png');
$im = imagecreatetruecolor(260, 180);
$background = imagecolorallocate($im, 0, 0, 255);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 60, 153, 181);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 200, $white);
$text = $_GET['tname'];
$font = 'OpenSans-Semibold.ttf';
imagettftext($im, 20, 0, $x+1, $y+1, $grey, $font, $text);
imagettftext($im, 20, 0, $x, $y, $black, $font, $text);
imagepng($im);
imagedestroy($im);

推荐答案

以下是一个有效的示例,基于 imagetttfbbox :

Here is a working example, based on imagetttfbbox:

$im = imagecreatetruecolor(200, 75);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// text, font and size to draw
$text = 'hello world';
$font = 'OpenSans-Semibold.ttf';
$size = 30;

// determine the size of the text so we can center it
$box = imagettfbbox($size, 0, $font, $text);
$text_width = abs($box[2]) - abs($box[0]);
$text_height = abs($box[5]) - abs($box[3]);
$image_width = imagesx($im);
$image_height = imagesy($im);
$x = ($image_width - $text_width) / 2;
$y = ($image_height + $text_height) / 2;

// add text
imagettftext($im, $size, 0, $x, $y, $white, $font, $text);

// set content type
header('Content-Type: image/png');

// output and destroy image
imagepng($im);
imagedestroy($im);

这篇关于在php图像中居中文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆