Shibbir
Shibbir

Reputation: 2041

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

Upvotes: 1

Views: 3451

Answers (1)

Eugen Rieck
Eugen Rieck

Reputation: 65314

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.

EDIT

It was of course imagefilledrectangle, not 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);

?>

Upvotes: 3

Related Questions