[英]How to add background color on the image text content using PHP?
Using bellow PHP code I can add text to an image but Now I want to add a background color to image text. 使用下面的PHP代码我可以向图像添加文本,但现在我想为图像文本添加背景颜色。 Can you tell me how to do this?
你能告诉我怎么做吗?
Note: The text background needs to bellow the image. 注意:文本背景需要低于图像。
What is now: 现在是什么:
What I want: 我想要的是:
PHP code: 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);
The problem becomes easy, if you don't think of it as a background color, but as drawing a rectangle before writing the text: 如果您不将其视为背景颜色,而是在编写文本之前绘制矩形,则问题变得容易:
$bcolor=imagecolorallocate($jpg_image, 0x00, 0xC0, 0xFF);
imagerectangle($jpg_image, 0, $orig_height*0.8, 0, $orig_height, $bcolor);
before the imagettftext
. 在
imagettftext
之前。
EDIT 编辑
It was of course imagefilledrectangle
, not imagerectangle
. 它当然是
imagefilledrectangle
,而不是imagerectangle
。 Here is the complete script 这是完整的脚本
<?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);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.