How to add background color on the image text content using PHP?

127

Using bellow PHP code I can add text to an image but Now I want to add a background color to image text. Can you tell me how to do this?

Note: The text background needs to bellow the image.

What is now:

enter image description here

What I want:

enter image description here

PHP code:

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

Answer

Solution:

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 theimagettftext.

EDIT

It was of courseimagefilledrectangle, notimagerectangle. 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);

?>

People are also looking for solutions to the problem: php - Switching to GetSingleItem instead of findItemsAdvanced with the ebay-api

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.