简体   繁体   中英

Make image just fit to a text

I'm using PHP GD and trying to draw a text and make the image size just fit to the text.

I found this question and tried Martin Geisler's code.

Resize image size according to size of text

It looked work fine, but when I tried other texts, some got out of the image.

Of course, I could add extra padding, but required padding depends on the text. That's too ad-hock.

Does anyone know proper way to do this?

Thanks in advance.

// Martin Geisler's version using MS Gothic
header("Content-type: image/png");

$q     = 'Image example';
$font  = './msgothic.ttc';  // MS Gothic
$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);

http://www.betatechnology.jp/~ao/imageexample.png

This is an issue related to the width of the text you are writing. 3 i's are smaller than 3 o's unless you are using fixed font.

Instead of trying to create an image that has the exact right proportions I would rather make it big enough and then crop out the unused space around it.

Since you create the image, you can make the border a solid color and then crop it. See this here for an instruction on how to do the cropping:

Crop whitespace from image in PHP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM