Search code examples
phpgdimage-manipulation

How to write text to images with different sizes using PHP GD


I'm creating images with different sizes. How can I write text on those images so that the texts always fit to the images?

$text = "some text as example";
$font = "arialbd.ttf"
$fontsize = 26;
offset_x = 0;
offset_y = 0;

$image01 = imagecreate( 1120 , 900 );
$image02 = imagecreate( 400 , 300 ); 
$image03 = imagecreate( 1120 , 900 );

I know that there is the imagefttext function that can apply text to the images but with that function I can only change the font size to make the text bigger. How can I find out that it fits into my image?


Solution

  • If you are looking to scale the font size so that text string fills the image width, try this. Using imagettfbbox, determine the current text box width:

     $bbox = imagettfbbox($fontsize,0,$fontpath,$string);
     $tbwidth = $bbox[2];
    

    Then divide the image width by the $tbwidth to get a factor

     $factor = round(($imgwidth / $tbwidth), 0, PHP_ROUND_HALF_DOWN); //ie. 800/240=3
    

    Multiple the $factor by you $fontsize to get an approximate increase.

     $newfontsize = $fontsize * $factor; //ie. 12(pt) * 3 = 36
    

    Keep in minds, if you're using GD 2.0, fontsize is in Points and not pixels. Your algorithm is going to calculate the difference between your default font size text box (expressed as a text box width) and the image width.