/* create a new canvas. New canvas dimensions should be larger than the original's */ list($o_width, $o_height) = getimagesize($src); $width = $o_width + DS_OFFSET; $height = $o_height + DS_OFFSET; $image = imagecreatetruecolor($width, $height);
/* floodfill the canvas with the background color */ imagefilledrectangle($image, 0,0, $width, $height, $colors[0]);
/* draw overlapping rectangles to create a drop shadow effect */ for ($i = 0; $i < count($colors); $i++) { imagefilledrectangle($image, DS_OFFSET, DS_OFFSET, $width, $height, $colors[$i]); $width -= DS_SPREAD; $height -= DS_SPREAD; }
/* overlay the original image on top of the drop shadow */ $original_image = imagecreatefromjpeg($src); imagecopymerge($image, $original_image, 0,0, 0,0, $o_width, $o_height, 100);
/* output the image */ header("Content-type: image/jpeg"); imagejpeg($image, "", 100);
/* clean up the image resources */ imagedestroy($image); imagedestroy($original_image); } ?>
And here is a sample of generated output:
Conclusion
The process for adding a drop shadow dynamically is pretty straightforward. A slightly larger image is created, the shadow is drawn to the new canvas and then the original image is overlaid. The resulting image is then sent back to satisfy the content request made by the browser.
The material presented here has room for many modifications and extensions. For example, you could make the script more flexible by using a constant to determine the shadow's angle, or perhaps even consider other methods of drawing a shadow. Your exploration doesn't have to end with this tutorial.
About The Author
Timothy Boronczyk lives in Syracuse, NY, where he works as an E-Services Coordinator for a local credit union. He has a background in elementary education, over 5 years experience in web design and has written tutorials on web design, PHP, Ruby, XML and various other topics. His hobbies include photography and composing music.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.