- - - By CrazyStat - - -
Last modified:
03.10.2023 - 16:42:36

Generate a gradient

The following function generates a gradient. You can configure width, height and the colors of the 4 corners.
Sample of a gradient generated by this function:

Example gradient


function gradient($w=100$h=100$c=array('#FFFFFF','#FF0000',
'#00FF00','#0000FF'), $hex=true) {

 Generates a gradient image

 Author: Christopher Kramer
 w: width in px
 h: height in px
 c: color-array with 4 elements:
    $c[0]:   top left color
    $c[1]:   top right color
    $c[2]:   bottom left color
    $c[3]:   bottom right color
 if $hex is true (default), colors are hex-strings like '#FFFFFF'
     (NOT '#FFF')
 if $hex is false, a color is an array of 3 elements which are the
    rgb-values, e.g.:  $c[0]=array(0,255,255);
$hex) {  // convert hex-values to rgb
for($i=0;$i<=3;$i++) {
$rgb=$c[0]; // start with top left color
for($x=0;$x<=$w;$x++) { // loop columns
for($y=0;$y<=$h;$y++) { // loop rows
   // set pixel color
// calculate new color 
for($i=0;$i<=2;$i++) {
$c[0][$i]*(($w-$x)*($h-$y)/($w*$h)) +
$c[1][$i]*($x     *($h-$y)/($w*$h)) +
$c[2][$i]*(($w-$x)*$y     /($w*$h)) +
$c[3][$i]*($x     *$y     /($w*$h));

hex2rgb($hex) {

// usage example

$image=gradient(300300, array('#000000''#FFFFFF'

header('Content-type: image/png');


Parameters are width, height and the colors of the 4 corners. An image handle with the gradient-image will be returned.
You can directly output the image or copy it onto another image using imagecopy. This can be useful to generate a shadow or glow-effect. For a glow-effect, generate 8 gradients, one for each corner and one for each sides and place them around your image. The outer side of the gradients has the background color, the inner side has a light color such as white.

Attention: This function is not optimized for speed and might become slow when gradients are getting big. If you want to generate shadow or glow effects, caching the images is mostly possible so this should not be an issue.

Note: I strongly recommend truecolor for gradients. So if you copy the gradient onto another image, make sure it was generated as a truecolor image.

This function was originally posted by me on