PHP GD -对齐文本中心水平和减小字体大小,以保持它在图像内


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

祝你一切顺利。

我还是一个新手使用php之后做一些阅读和检查一些帖子在这里我能够把一些文本图像与imagecreatefrompng()函数使用php GD,用户会来一个表单和他们将能够输入他们的名字,这个名字会写图像,不幸的是我无法对齐文本中心水平,我尝试所有可能的方法(我的方式显然和必须是错误的)imagettfbbox但我在我所有的尝试失败了,你们能帮我把弦的中心水平对齐吗?另外,由于我使用了一种可选的大字体,所以如果输入的名称有点长,我需要减小尺寸,这样它就不会超过图像的限制,并保持在中间。我从一个表单的文本的值,你可以检查在我的代码的开始:

<?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);
  ?>

你的帮助将是非常感激的,后来我会打破我的头试图通过点击提交按钮保存图像,因为我不希望用户通过右键单击保存图像。

谢谢朋友!

你需要图片的宽度和文字的宽度来将两者联系起来。

// 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);

您可以使用still/gd-text类来对齐文本。免责声明:我是作者。

<?php
use GDText'Box;
use GDText'Color;
$jpg_image = imagecreatefromjpeg('fabian.jpg');
$textbox = new Box($jpg_image);
$textbox->setFontSize(75);
$textbox->setFontFace('fabian.TTF');
$textbox->setFontColor(new Color(255, 255, 255));
$textbox->setBox(
    50,  // distance from left edge
    50,  // distance from top edge
    200, // textbox width
    100  // textbox height
);
// text will be aligned inside textbox to center horizontally and to top vertically
$textbox->setTextAlign('center', 'top');
$textbox->draw(strtoupper($nombre));

但这不是一个完整的答案,因为它不能自动减小字体大小