如何使用PHP在图像文本内容上添加背景颜色?

时间:2017-12-24 11:19:27

标签: php

使用下面的PHP代码我可以向图像添加文本但现在我想为图像文本添加背景颜色。你能告诉我怎么做吗?

注意:文字背景需要低于图像。

现在是什么:

enter image description here

我想要的是什么:

enter image description here

PHP代码:

 //Set the Content Type
  header('Content-type: image/jpg');

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

  // Allocate A Color For The Text
  $color = imagecolorallocate($jpg_image, 0, 0, 0);      

  // Set Path to Font File
  $font_path = 'arial.ttf';

  // Set Text to Be Printed On Image
  $text = "My Content Goes to here";

  // Print Text On Image
  //$image = imagecreatefromjpg($jpg_image);
  $orig_width = imagesx($jpg_image);
  $orig_height = imagesy($jpg_image);

  imagettftext($jpg_image,  20, 0, 10, $orig_height-10, $color, $font_path, $text);

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

  // Clear Memory
  imagedestroy($jpg_image);

1 个答案:

答案 0 :(得分:3)

如果您不认为它是背景颜色,而是在编写文本之前绘制矩形,问题就变得容易了:

$bcolor=imagecolorallocate($jpg_image, 0x00, 0xC0, 0xFF);
imagerectangle($jpg_image,  0, $orig_height*0.8, 0, $orig_height, $bcolor);

imagettftext

之前

修改

当然是imagefilledrectangle,而不是imagerectangle。这是完整的脚本

<?php

  // Create Image From Existing File
  $jpg_image = imagecreatefromjpeg('test-02.jpg');
  $orig_width = imagesx($jpg_image);
  $orig_height = imagesy($jpg_image);

  // Allocate A Color For The background
  $bcolor=imagecolorallocate($jpg_image, 0x00, 0xC0, 0xFF);

  //Create background
  imagefilledrectangle($jpg_image,  0, $orig_height*0.8, $orig_width, $orig_height, $bcolor);

  // Set Path to Font File
  $font_path = realpath(dirname(__FILE__)).'/arial.ttf';

  // Set Text to Be Printed On Image
  $text = "New Content Goes to here";

  // Allocate A Color For The Text
  $color = imagecolorallocate($jpg_image, 0, 0, 0);      

  // Print Text On Image
  imagettftext($jpg_image,  20, 0, 10, $orig_height-10, $color, $font_path, $text);

  //Set the Content Type
  header('Content-type: image/jpg');

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

  // Clear Memory
  imagedestroy($jpg_image);

?>