1

希望你们都做得很好。

我有一个使用 PHP GD 创建和编辑的图像,我使用以下代码将其发送到浏览器,但它显示完全与浏览器的左侧对齐,我尝试将 css 行为直接添加到 img 标签但没有发生了所以我想这永远不会起作用,因为它是一个显示图像的 php 标头,有没有办法在相同的代码中将图像与浏览器的中心对齐让我们说使用边距 0 自动对齐 div 的方式?如您所见,我仍然是 GD 的新手,所以这是我的代码,我真的很感激朋友们:

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


  // Create Image From Existing File
  $jpg_image = imagecreatefromjpeg('fabian.jpg');
      // get image dimensions
list($img_width, $img_height,,) = getimagesize("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
  $text =strtoupper($nombre);

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

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



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


 // Clear Memory
  imagedestroy($jpg_image);

?>

非常感谢您的建议!祝你有美好的一天。

4

2 回答 2

3

看起来您只是在提供的代码中输出图像文件。无法在此代码中指定任何浏览器应如何显示图像。

如果某处有单独的 HTML 代码显示此图像,则应在此处指定与外观和定位相关的任何内容。因此,它变成了一个关于如何使图像居中的 HTML/CSS 问题,并且与 PHP 或 GD 没有任何关系。

于 2013-04-13T17:37:31.143 回答
1

您将需要添加display: block;到您的 CSS 规则以使其集中。

但是,如果您只是在浏览器中请求图像,那么实际上没有办法解决它,因为您需要知道浏览器窗口的尺寸,而这些尺寸在服务器端是不可用的。

于 2013-04-13T17:36:15.663 回答