使用PHP GD将图像上的文字居中 [英] Center text on image using PHP GD

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

问题描述

所以我正在创建横幅生成器.

So I am creating a banner generator.

我将在中间添加文本,但希望它恰好在中间. 我知道imagettftext可用于在横幅上书写,但这不会使其居中.

I will be adding text in the middle, but would like it to be exactly in the center. I know that imagettftext can be used to write onto the banner, but that won't center it.

一种可能的解决方案是找到文本的宽度,然后使用从横幅宽度的一半中减去的一半,但是我不知道该怎么做.

A likely solution could be to find the width of the text and then use half of it taken away from half of the banner width, but I've got no idea about how to do this.

我正在使用PHP-GD,并且不想使用必须安装的其他任何软件.

I am using PHP-GD and do not want to use anything else I will have to install.

imagettftext($img, 14, 0, (468 - ((strlen($_GET['description']) * imagefontwidth(imageloadfont('minecraft.ttf'))) / 1)), 85, imagecolorallocate($img, 0, 0, 0), 'minecraft.ttf', $_GET['description']);

上面的代码产生了上面的结果.使用小字符串是可以的,但是一定有问题,因为一旦它们变长,它就会失败.

The code above is making the result above. It is fine with small strings but there must be something wrong since as soon as they become long, it fails.

推荐答案

签出imagettfbbox: http://www.php.net/manual/en/function.imagettfbbox.php .它将为您提供您希望呈现的文本的范围.然后,将其居中放置在图像上就很简单了.

Check out imagettfbbox: http://www.php.net/manual/en/function.imagettfbbox.php. It will give you the extents of the text you wish to render. Then it's simple arithmetic to center that on your image.

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

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