Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP GD - Align text center-horizontally and decrease font size to keep it inside the image

Hope you are doing great.

I’m still a newbie with php so after making some reading and while checking some posts here I was able to put some text over an image with the imagecreatefrompng() function using the PHP GD, users will come to a form and they will be able to enter their name and the name will be written over the image , unfortunately I have been unable to align the text center horizontally, I tried all ways possible (my ways obviously and must be wrong) with imagettfbbox but I failed in all my attempts, could you please guys help me out a little bit to align the string center horizontally? Also since I’m using a kind of alternative big font I need that the size decrease if the name entered is kind of long so this way it will not surpass the image limits and will stay at the center. I’m getting the value of the text from a form as you may check at the beginning of my code:

<?php
 $nombre=$_POST['nombre'];
  //Set the Content Type
  header('Content-type: image/jpeg');

  // Create Image From Existing File
  $jpg_image = imagecreatefromjpeg('fabian.jpg');

  // Allocate A Color For The Text
  $white = imagecolorallocate($jpg_image, 255, 255, 255);

  // Set Path to Font File
  $font_path = 'fabian.TTF';

  // Set Text to Be Printed On Image , I set it to uppercase
  $text =strtoupper($nombre);

  // Print Text On Image
  imagettftext($jpg_image, 75, 0, 50, 400, $white, $font_path, $text);



  // Send Image to Browser
  imagepng($jpg_image);

  // Clear Memory
  imagedestroy($jpg_image);

  ?>

Your help will be highly appreciated, later on I will break my head trying to save the image by clicking a submit button since I do not want the users to save the image by right clicking on it.

Thanks pals!

like image 653
i'llbdevsomeday Avatar asked Apr 13 '13 00:04

i'llbdevsomeday


1 Answers

You need the width of the image and the width of the text to relate both.

// get image dimensions
list($img_width, $img_height,,) = getimagesize("fabian.jpg");

// find font-size for $txt_width = 80% of $img_width...
$font_size = 1; 
$txt_max_width = intval(0.8 * $img_width);    

do {        
    $font_size++;
    $p = imagettfbbox($font_size, 0, $font_path, $text);
    $txt_width = $p[2] - $p[0];
    // $txt_height=$p[1]-$p[7]; // just in case you need it
} while ($txt_width <= $txt_max_width);

// now center the text
$y = $img_height * 0.9; // baseline of text at 90% of $img_height
$x = ($img_width - $txt_width) / 2;

imagettftext($jpg_image, $font_size, 0, $x, $y, $white, $font_path, $text);
like image 135
michi Avatar answered Sep 29 '22 20:09

michi