本文介绍了根据文本大小调整图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的PHP代码生成文本作为动态创建的图像,我怎样才能使图像只与文本一样大?谢谢。

The PHP code below generates text as a dynamically created image, how would I be able to get the image to only be as large as the text? Thanks.

<?php
    header('Content-Type: image/jpeg');

    $text='Test';

    $img = imageCreate(200,200);

    imagecolorallocate($img, 255, 255, 255);

    $textColor = imagecolorallocate($img, 0, 0, 0);

    imagefttext($img, 15, 0, 0, 55, $textColor, 'bgtbt.ttf', $text);

    imagejpeg($img);

    imagedestroy($img);
?>

更新1:我在这里找到了原始海报示例的答案 -

UPDATE 1: I found the answer here with the example of the original poster - Creating IMage from Text in PHP - how can I make multiline?

更新2:Martin Geisler的版本也运作良好

UPDATE 2: Martin Geisler's version also works well

推荐答案

使用TrueType字体时,使用功能使用您的字体获取字符串排版的边界框。边界框给出了从基点到文本占据的矩形中的四个角的偏移量。因此,如果您将边界框存储在 $ bb 中并使用 imagefttext 将文本放在( $ x,$ y),然后角将有这些坐标:

When using a TrueType font, you use the imageftbbox function to obtain the bounding box for a string typeset with your font. The bounding box gives the offsets from the base-point to the four corners in the rectangle occupied by the text. So if you store the bounding box in $bb and use imagefttext to put text at ($x, $y), then the corners will have these coordinates:

($x + $bb[6], $y + $bb[7])         ($x + $bb[4], $y + $bb[5])
                          +-------+
                          | Hello |
                          +-------+
($x + $bb[0], $y + $bb[1])         ($x + $bb[2], $y + $bb[3])

这告诉我们想要的图像宽度 ($ x + $ bb [2]) - ($ x + $ bb [6])= $ bb [2] - $ bb [6] 同样的图像高度 $ bb [3] - $ bb [7] 。然后应该在该图片中的坐标( - $ bb [6], - $ bb [7])中呈现文本,因为我们想要

That tells us that we want an image width of ($x + $bb[2]) - ($x + $bb[6]) = $bb[2] - $bb[6] and similarly an image height of $bb[3] - $bb[7]. The text should then be rendered at coordinates (-$bb[6], -$bb[7]) inside that picture since we want to have

(0, 0) = ($x + $bb[6], $y + $bb[7]) ==> $x = -$bb[6]  and $y = -$bb[7]

你可以尝试使用此代码。将它放入一个名为 img.php 的文件中并浏览到 img.php?q = Hello 进行测试:

You can try it out with this code. Put it into a file called img.php and browse to img.php?q=Hello to test:

<?php
header("Content-type: image/png");

$q     = $_REQUEST['q'];
$font  = "Impact.ttf";
$size  = 30;
$bbox   = imageftbbox($size, 0, $font, $q);

$width  = $bbox[2] - $bbox[6];
$height = $bbox[3] - $bbox[7];

$im    = imagecreatetruecolor($width, $height);
$green = imagecolorallocate($im, 60, 240, 60);

imagefttext($im, $size, 0, -$bbox[6], -$bbox[7], $green, $font, $q);
imagepng($im);
imagedestroy($im);
?>






如果您使用位图字体,请查看在和功能。

这篇关于根据文本大小调整图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:39