php imagick complex gradient composite image

Manipulating images with imagemagick for php can be difficult, especially when you are trying to create complex images for a web template. Here is a more complex example of how to create sweet dynamic web graphics. This is a version of a header image that I created for a template design. It involves 4 colors, and adds a nice gradient sheen over the top of the base gradients.

The script first creates an new base image using the background color. Next, the script uses imagickdraw to create some lines and solid rectangles. Then the script creates another image which will fill in a gradient between the top two lines. Now comes the more complicated part, adding the sheen over the image that was just created.

The hard part of this is the fact we need an almost horizontal gradient. This involves creating two vertical gradients, reversing the color directions, then compositing them together. Once they have been combined, we rotate the image just beyond vertical, then set the transparency to 50%.

Now, the script puts the gradient image and sheen image together, and you have a sweet looking header image….

$background = "#FFFFFF";
$color1 = '#999999';
$color2 = '#333333';
$color3 = '#CCCCCC';
//$cachefile = 'path/to/cachefile.jpg';
//if (!file_exists($cachefile)) {
	$im = new Imagick();
	$im->newImage( 400, 86, $background, "jpg" );
	$draw1 = new ImagickDraw();
	$draw1->rectangle(0, 0, 400, 3);
	$draw1->rectangle(0, 73, 400, 86);
	$draw1->line(0, 2, 400, 2);
	$draw1->line(0, 73, 400, 73);
	$gradient1 = new Imagick();
	$gradient1->newPseudoImage(400, 70, "gradient:".$color1."-".$color2);
	$im->compositeImage( $gradient1, imagick::COMPOSITE_OVER, 0, 3 );
	$gradient_over1 = new Imagick();
	$gradient_over1->newPseudoImage(400, 200, "gradient:transparent-".$background);
	$gradient_over2 = new Imagick();
	$gradient_over2->newPseudoImage(400, 200, "gradient:".$background."-transparent");
	$gradient_over = new Imagick();
	$gradient_over->compositeImage( $gradient_over1, imagick::COMPOSITE_OVER, 0, 0 );
	$gradient_over->compositeImage( $gradient_over2, imagick::COMPOSITE_OVER, 0, 200 );
	$im->compositeImage($gradient_over, imagick::COMPOSITE_OVER, -100, -200 );	
	header( "Content-Type: image/jpg" );
	echo $im;
}catch(Exception $e){
	echo 'Error: ',  $e->getMessage(), "";
	$canvas = new Imagick($cachefile);
	header("Content-Type: image/png");
	echo $canvas;

As usual, I have commented out file caching code. Simply uncomment those lines and put a correct cachefile path (directory must be writable by the server).

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>