Imagecreate() PHP Function

The imagecreate() function is used in PHP to create a web page palette-based image using the GD library. The function's two parameters are width and then height (in pixels) of the image to be created. This creates a square or a rectangle that can contain a background color and text. You can use imagecreate() for charts or inline graphics or section markers.

Sample Code Using Imagecreate() Function

<?php 
 header ("Content-type: image/png"); 
 $handle = imagecreate (130, 50) or die ("Cannot Create image"); 
 $bg_color = imagecolorallocate ($handle, 255, 255, 0);  
 $txt_color = imagecolorallocate ($handle, 0,0,0) ;
 ImageString ($handle, 4, 4, 12, "Sample Text", $txt_color:
 ImagePng ($handle); 
 ?> 

This example code generates a PNG image. The imagecreate() function specifies a shape that is 130 pixels wide and 50 pixels tall. The background color of the image is set to yellow using the imagecolorallocate() function (which requires colors input in RGB values). The text color is set to black. The text that will print is "Sample Text," in size 4 (of 1-5) with an x ordinate of 4 and a y ordinate of 12.

The resulting image is a yellow rectangle with black type in it.

Considerations

  • The GD library must be enabled for this function to work properly; otherwise, the return value is False. It can be downloaded free from the internet if you don't already have it installed.
  • The PHP Manual recommends using imagecreatetruecolor() instead of imagecreate() to deliver the best quality image.
  • If you are unfamiliar with working in the RGB color space, check out this RGB explanation online.