Fitting Text into an Image

Posted by Abs on Stack Overflow See other posts from Stack Overflow or by Abs
Published on 2010-05-15T21:54:55Z Indexed on 2010/05/15 22:02 UTC
Read the original article Hit count: 215

Filed under:
|

Hello all,

I have a function which takes in a font (ttf or otf file) and generates an image of text in different fonts.

The problem I have is trying to work out how I can make the text fit in the image regardless of the font-size, type of font, and amount of text.

I have tried to make the image rectangle variable so that it contains the text of different fonts without cutting a bit of the text since the image is not long or wide enough.

Here is the function that I currently have, I have tried using the number of characters to determine the width of the image, but in some cases for some fonts and sizes, it still gets cut off.

function generate_image($save_path, $text, $font_path){

    $length = strlen($text) * 15;

    // Create the image
    $im = imagecreatetruecolor($length, 40);

    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);

    imagefilledrectangle($im, 0, 0, $length, 40, $white);

    $font = $font_path;

    imagettftext($im, 30, 0, 0, 25, $black, $font, $text);

    if(imagepng($im, $save_path)){

        $status = true;

    }else{

        $status = false;

    }

    imagedestroy($im);

    return $status;

}

Thank you all for any help

© Stack Overflow or respective owner

Related posts about php

Related posts about image