On: 2006/02/02 Viewed: 26142 times

Here is a small PHP function I wrote that emulates a gradient fill of an image.
Disclaimer : there are probably existing alternatives or classes, maybe in PEAR. I didn't check. I wanted to write a function myself, as part of my GD training grounds.

Usage

The function is packaged as a PHP class, the code you need is something like :

PHP:
  1. require_once('/path/to/gd-gradient-fill.php');
  2. $image = new gd_gradient_fill($width,$height,$direction,$startcolor,$endcolor,$step);

The class call needs 5 arguments and accepts an optional 6th :

  1. integer $width
    Width of the image
  2. integer $height
    Height of the image
  3. string $direction
    The shape or direction of the gradient, which can be any of : vertical, horizontal, ellipse, ellipse2, circle, circle2, rectangle, diamond.
  4. string $startcolor
    Gradient start color, 3 or 6 digit hexadecimal ("#ff0" or "#dd4578")
  5. string $endcolor
    Gradient end color
  6. Optional : $step
    Breaks the gradient smooth blending

Results

Here are a few examples of gradients from color #101040 to #a1a1ff. Hover the image for some unnecessary explanation.

Gradient Fill : Vertical Gradient Fill : Horizontal Fill Gradient Fill : Ellipse Gradient Fill : Rectangle Gradient Fill : Diamond

Of course, the function handles non-square images just fine as well.

Get the function

Credits

I started from file header-img.php, part of Wordpress core file, which contains a similar hack to draw a gradient fill from lines. I believe this smart code is from Andy Skelton.

If you happen to use this function in any project, be sure to let me know. This makes my day :)

Related posts

Metastuff

This page "PHP and GD : Emulate Gradient Fill" was posted on 02/02/2006 at 6:37 pm
Watch this discussion : Comments RSS 2.0. You can trackback this post from your own site

27 Blablas

  1. 1
    Sander Netherlands »
    commented, on 07/Jun/06 at 3:09 pm # :

    Hi There,

    While trying your gradient functions, i noticed that when you render an image wider than 256 pixels, the colors are incorrect.

    Try rendering this:
    $image = imagecreate(500,100);
    gd_gradient_fill($image,'horizontal','#fff','#000');

    You'll see it does not end black, but gray.

    Could you please help me in finding out why?

    Regards,

    Sander

  2. 2
    Ozh France »
    thought, on 09/Jun/06 at 12:01 am # :

    This is fixed in version 1.1 uploaded today

  3. 3
    Sergey Choob Russia »
    wrote, on 11/Jul/06 at 10:15 am # :

    Will you please tell me how to code a gradient figure with light in the middle and color at the ends (half one type - the other half opposite type). I would appriciate your help. Regards.

  4. 4
    Thomas Devol United States »
    said, on 17/Jul/06 at 3:31 pm # :

    How did you do these corners on this form, this is totally awesome. I'm using your library to create a server side dynamic gradient generator, that I could also adopt to create soft shadows of any color dynamically, on the fly. I plan to implement caching as well.

  5. 5
    Thomas Devol United States »
    replied, on 17/Jul/06 at 3:53 pm # :

    I'm having a problem, no matter what I do - it comes out as an ellipse. Some type of caching issue?;

    $img=imagecreate(100,50);
    require_once('gd-gradient-fill.php');
    gd_gradient_fill($img,'hoizontal','#fff','#000');
    header("Content-type: image/jpeg");
    imagejpeg($img);

  6. 6
    Dx Argentina »
    commented, on 25/Jul/06 at 7:32 am # :

    Ozh is offline.. but maybe i can answer some questions ;)

    @Sergey Choob: I don't understand that, but try with ellipse and setting well the colors.

    @Thomas Devol[1]: it's a propietary addition of mozilla/firefox, that maybe will be implemented later as standard :)
    By now: -moz-border-radius: unit; -moz-border-radius-topleft: unit; -moz-border-radius-bottomleft: unit;
    and so.

    @Thomas Devol[2]: there says "hoizontal". Typo.

  7. 7
    tom Poland »
    said, on 05/Aug/06 at 7:56 pm # :

    Hello!

    And what about transparency?
    How to create .png image with gradient from color to transparency?

  8. 8
    DeadMeatGF United States »
    thought, on 12/Aug/06 at 9:01 pm # :

    I am trying to draw a gradient bar on a bar-graph, and the techniques I've tried so far basically allocate the colours as they draw the bar.
    However, I hace found that when the graph requires 2 or more bars, the second stops - investigation suggests that the image simply runs out of colours!
    With my limited knowledge of PHP, the class appears to return an image rather than adding to an existing one - so can I use this class to add gradiated bars to my chart, or will it need some alterations to the code?

  9. 9
    R.M.D. United States »
    wrote, on 29/Aug/06 at 7:54 am # :

    I modified the last line in the switch cases for circle2 and ellipse in the fill method so
    that the gradient fades into transparency. I found it useful. Maybe you will.

    $eCol = imagecolorallocate( $im, $r1, $g1, $b1 );
    imagecolortransparent($im,$eCol);
    imagefill($im, 0, 0, $eCol); // make this transparent

    Thanks for the library. It's great!

  10. 10
    Ryley Canada »
    thought, on 22/Dec/06 at 9:17 pm # :

    Instead of tracking colors and dealing with allocation issues, try one of these two options:

    $fill = imagecolorresolve( $im, $r, $g, $b );

    That one should do the best job of find you your color... but for gradients it may not be good. Instead, this might be best:

    $fill = imagecolorexact( $im, $r, $g, $b );
    if ($fill === -1){
    $fill = imagecolorallocate( $im, $r, $g, $b );
    if ($fill === -1){
    $fill = imagecolorclosest( $im, $r, $g, $b );
    }
    }

    I use other libraries that do this to excellent effect (GD::Graph in perl for instance).

  11. 11
    Willy Germany »
    wrote, on 13/Jun/07 at 2:52 pm # :

    Hi,

    thank you for that class, it works realy great.

    I had first the same problem like Thomas Devol posted on July 06, all created pictures comes out as eclipse.

    Now I recognize the problem, if you test it you have to
    comment the line 48 in the file gd-gradient-fill.php, than it works fine.

    Best Regards from Berlin
    Willy

  12. 12
    Ozh France »
    replied, on 13/Jun/07 at 9:09 pm # :

    Willy » well yeah, that line serves as an example :)

  13. 13
    Joe Auricchio United States »
    wrote, on 26/Jun/07 at 8:19 am # :

    Hi!

    I wanted to make a simple gradient across the top inch or so of my blog, fading from light grey into white. I knew recent versions of WP have a gradient-maker script, so I googled for some information on it. Google, in its infinite wisdom, brought me here instead.

    PHP:
    1. $image = new gd_gradient_fill(32,120,"vertical","#ccc","#fff",1);

    Tada! :)

    Thanks so much for the script.
    -joe

  14. 14
    Breachware Great Britain (UK) »
    said, on 29/Jun/07 at 2:45 pm # :

    This module is so cool. But does anyone know how to get it to fill diagonally?

  15. 15
    Jack Italy »
    said, on 18/Jul/07 at 5:55 pm # :

    Rectangle render doesn't work properly. This works better:

    imagefilledrectangle ($im, $i, $i*$height/$width, $width-$i+1, $height-($i*$height/$width) + 1, $fill);

    line 216

    Thanks

    Jack

  16. 16
    Os United Arab Emirates »
    said, on 25/Jul/07 at 6:26 pm # :

    Rectangle render Problem. This works even better:

    PHP:
    1. if( $height <= $width )    
    2.  {
    3.   imagefilledrectangle ($im, $i, $i*$height/$width, $width-$i+1, $height-($i*$height/$width) + 1, $fill);
    4.  }
    5. else
    6.  {
    7.   imagefilledrectangle ($im,$i*$width/$height , $i,$width-($i*$width/$height) + 1 ,$height-$i+1 , $fill);
    8.  }

  17. 17
    Thomas Cayne United States »
    wrote, on 30/Aug/07 at 10:55 am # :

    Hi Ozh,

    Thanks for providing this great class. I find it very helpful to fill an entire image. I am trying to fill a gradient polygon ON an image, like a diagonal banner or a sash for a beauty pageant, done dynamically. For example, to fill within the [code]$coords=array(0, 0, 249, 249, 249,164,85,0);[code] with an image size 250px by 250px. I thought it would be simple to do but after 4 hours my eyes are really heavy.

    Thanks.

  18. 18
    Ozh France »
    wrote, on 30/Aug/07 at 11:03 am # :

    Thomas » I guess simplest way of doing so is first generate the gradient image, then merge it with your original image with imagecopymerge

  19. 19
    Tiziano Italy »
    said, on 13/Sep/07 at 12:47 am # :

    Hi, great piece of code.
    I'm trying to use the generated image as a table cell background, but i'm not able to do it.
    How can i do it?
    Thanks in advance.

  20. 20
    Orlando United States »
    said, on 13/Sep/07 at 6:13 pm # :

    Hello Guys I'm kind of new in PHP and I'm just trying to use this library but I get this error

    Unable to create an image.

    Can you give an idea what it could cause this problem.

    THANKS

  21. 21
    Ozh France »
    commented, on 13/Sep/07 at 8:16 pm # :

    Tiziano » this is a pure CSS issue. Something like the following would work:

    CSS:
    1. td {background-image: url('url/to/image.php')

    Where image.php would be the file that generates your gradient.

    Orlando » this requires PHP extension GD, which you probably don't have on your server then.

  22. 22
    Dragen Great Britain (UK) »
    thought, on 15/Sep/07 at 6:17 pm # :

    hi,
    I've been testing your script for a while and am also using in some of my work, but during testing with ellipse and cirle it seems that ellipse is the same as circle2 and circle2 is the same as ellipse..
    Is this just me?

    Thanks

  23. 23
    kiuwenayk Philippines »
    wrote, on 21/Oct/07 at 5:51 am # :

    hi,
    how do i stretch a gradient image to fill up the entire screen to use as background color. Like one whole ellipse filling the entire screen. Great code indeed!

  24. 24
    fahad Great Britain (UK) »
    replied, on 07/Feb/08 at 7:22 pm # :

    I used it in my site :)
    I used to use a static gradient, now I use your script, that either draws the static gradient, or uses the gradient stored in a cookie.

  25. 25
    Jordan Shaw Canada »
    commented, on 04/Apr/08 at 1:19 am # :

    This is great, thanks so much! works like a new million dollar bill.

  26. 26
    arne Netherlands »
    replied, on 27/Jun/08 at 10:13 pm # :

    hello, does anyone know how to get a vertical gradient that fades from color to transparant? i can't get it to work :(

  27. 27
    Asad Hasan United States »
    commented, on 21/Jul/08 at 11:51 pm # :

    Amazing job, this is GD at its best!

Leave a Reply

Comment Guidelines or Die

  • HTML: You can use these tags: <a href=""> <em> <i> <b> <strong> <blockquote>
  • Posting code: Post raw code (no <> &lt; etc) within appropriate tags : [php][/php], [css][/css], [html][/html], [js][/js], [sql][/sql], [xml][/xml], or generic [code][code]
  • Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar.
  • Spam: Various spam plugins on patrol. I'll put pins in a Voodoo doll if you spam me.
  • I will mark as Spam test comments, all comments with SEO names (ie "My Cool Online Shop" instead of "Joe") or containing forum-like signatures.

Close
E-mail It