PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to write text to images with different sizes using PHP GD

 October 10, 2022     gd, image-manipulation, php     No comments   

Issue

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.



Answered By - rwhite
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing