In this post I will show you how to create a rounded corner box with a drop shadow. First set your background color, foreground color, and the color of the drop shadow.
Once you’ve set up your colors, the script will create two identical imagick objects, one for the background, and one for the foreground. The background is just a base file where you will composite over the drop shadow image and the foreground rounded rectangle.
First the script creates a rounded rectangle within the bounds of the background image with space enough to not cut off the drop shadow. Once this rectangle is drawn on the second “over” image, the script applies a gaussian blur to the image to create the effect of a drop shadow. Once this is done, the script draws another identical rounded rectangle over the drop shadow, only this time with the foreground color rather than the drop shadow color.
After thats all taken care of, the script composites the drop shadow/round rectangle image over the background image that was created first. And, its done. Uncomment the caching code to write the resulting file to disk.
<? $background = "#FFFFFF"; $foreground = "#EAEAEA"; $shadow = "#666666"; //$cachefile = './path/to/your/cachefile.png'; //if (!file_exists($cachefile)) { try{ $canvas = new Imagick(); $canvas->newImage(200, 200, $background, "png" ); $box_over = new Imagick(); $box_over->newImage(200, 200, $background, "png" ); $draw = new ImagickDraw(); $draw->setFillColor($shadow); $draw->roundRectangle(10, 10, 190, 190, 10, 10); $box_over->drawImage($draw); $box_over->blurImage(8, 5); $canvas->compositeImage($box_over, imagick::COMPOSITE_OVER, 0, 0); $draw = new ImagickDraw(); $draw->setFillColor($foreground); $draw->roundRectangle(10, 10, 190, 190, 10, 10); $box_over->drawImage($draw); $canvas->compositeImage($box_over, imagick::COMPOSITE_OVER, 0, 0); $canvas->setImageFormat('jpeg'); //$canvas->writeImage($cachefile); header( "Content-Type: image/jpg" ); echo $canvas; $canvas->clear(); $canvas->destroy(); }catch(Exception $e){ echo 'Error: ', $e->getMessage(), ""; } /* }else{ $canvas = new imagick($cachefile); header("Content-Type: image/png"); echo $canvas; } */ ?> |
NOTE: the cachefile folder must be writable by the server.
do you know of a similar example using GD? From my experience much fewer shared hosting environmnets support imagick so I cant use your good example in production environments for my clients ;(
All of the implementations using GD have severely jagged edges….mainly because of GD’s weak support of png files and transparency. You’ll notice in my code that I create the composite images as png files, which have proper alpha channels, then composite them together and output a jpg….there are versions of the bundled GD libraries that have blur filters, and you could probably get a similar effect, but it would look terrible compared to the imagick version….