How to create a new true-color image in PHP using imagecreatetruecolor()?

PHPServer Side ProgrammingProgramming

imagecreatetruecolor( ) is an inbuilt function in PHP that is used to create a new true-color image. It returns a blank image of the given size.

Syntax

resource imagecreatetruecolor($width, $height)

Parameters

imagecreatetruecolor() takes two paramters, $width and $height.

  • $width − The $width parameter is used to set the image width.

  • $height − The $height parameter is used to set the image height.

Return Values

imagecreatetruecolor() returns an image resource identifier on success or it returns false on errors.

Example 1

<?php
   // Set the vertices of polygon
   $values = array(
      150, 50, // Point 1 (x, y)
      50, 250, // Point 2 (x, y)
      250, 250 // Point 3 (x, y)
   );
   // Create the size of image or blank image
   $image = imagecreatetruecolor(700, 350);

   // Set the background color of image
   $background_color = imagecolorallocate($image, 122, 122, 122);

   // Fill background with above selected color
   imagefill($image, 0, 0, $background_color);

   // Allocate a color for the polygon
   $image_color = imagecolorallocate($image, 0, 255, 255);

   // Draw the polygon
   imagepolygon($image, $values, 3, $image_color);

   // Output the picture to the browser
   header('Content-type: image/png');

   imagepng($image);
?>

Output

Example 2 − Below PHP code will create a new GD image stream

<?php
   header ('Content-Type: image/gif');
   $img = @imagecreatetruecolor(550, 220)
   or die('Cannot Initialize new GD image stream');
   $text_color = imagecolorallocate($img, 255, 255, 0);
   
   imagestring($img, 10, 50, 50, 'A Simple PHP Example', $text_color);
   imagepng($img);
   imagedestroy($img);
?>

Output

raja
Published on 09-Aug-2021 11:36:12
Advertisements