【问题标题】:Image generated with PHP GD -How to align to the center of browser?使用 PHP GD 生成的图像 - 如何与浏览器的中心对齐?
【发布时间】:2013-04-06 03:02:05
【问题描述】:

希望你们都做得很好。

我有一个使用 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);

?>

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

【问题讨论】:

  • 您不能对图像本身执行此操作,因为 PHP 无法知道浏览器的尺寸以正确居中,您需要使用 HTML 显示图像,然后使用 CSS 将其居中。
  • 知道了,谢谢 cryptic 我会找到在正文中显示图像的方法,然后我会用 css 从那里获取它,我想我需要暂时保存它然后检索文件。谢谢!

标签: php gd


【解决方案1】:

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

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

【讨论】:

  • 非常感谢 pilsetnieks,知道这一点,根据上面 cryptic 输入的评论,我想我现在明白了,我现在有了一个想法。再次感谢朋友。
【解决方案2】:

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

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

【讨论】:

  • 谢谢亚当,我就是这么想的;将工作一段时间以找到检索图像的最佳方法,而不是在浏览器中请求图像。
猜你喜欢
  • 1970-01-01
  • 2016-06-28
  • 2014-06-18
  • 2015-08-01
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
相关资源
最近更新 更多