PHP Create Drop Shadow on Image


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. /* set drop shadow options */
  3.  
  4. /* offset of drop shadow from top left */
  5. define("DS_OFFSET", 5);
  6.  
  7. /* number of steps from black to background color /*
  8. define("DS_STEPS", 10);
  9.  
  10. /* distance between steps */
  11. define("DS_SPREAD", 1);
  12.  
  13. /* define the background color */
  14. $background = array("r" =&gt; 255, "g" =&gt; 255, "b" =&gt; 255);
  15.  
  16. $src = isset($_REQUEST['src']) ? urldecode($_REQUEST['src']) : null;
  17. if(isset($src) &amp;&amp; file_exists($src)) {
  18.  
  19. /* create a new canvas. New canvas dimensions should be larger than the original's */
  20. list($o_width, $o_height) = getimagesize($src);
  21. $width = $o_width + DS_OFFSET;
  22. $height = $o_height + DS_OFFSET;
  23. $image = imagecreatetruecolor($width, $height);
  24.  
  25. /* determine the offset between colors */
  26. $step_offset = array("r" =&gt; ($background["r"] / DS_STEPS), "g" =&gt; ($background["g"] / DS_STEPS), "b" =&gt; ($background["b"] / DS_STEPS));
  27.  
  28. /* calculate and allocate the needed colors */
  29. $current_color = $background;
  30. for ($i = 0; $i &lt;= DS_STEPS; $i++) {
  31. $colors[$i] = imagecolorallocate($image, round($current_color["r"]), round($current_color["g"]), round($current_color["b"]));
  32.  
  33. $current_color["r"] -= $step_offset["r"];
  34. $current_color["g"] -= $step_offset["g"];
  35. $current_color["b"] -= $step_offset["b"];
  36. }
  37.  
  38. /* floodfill the canvas with the background color */
  39. imagefilledrectangle($image, 0,0, $width, $height, $colors[0]);
  40.  
  41. /* draw overlapping rectangles to create a drop shadow effect */
  42. for ($i = 0; $i &lt; count($colors); $i++) {
  43. imagefilledrectangle($image, DS_OFFSET, DS_OFFSET, $width, $height, $colors[$i]);
  44. $width -= DS_SPREAD;
  45. $height -= DS_SPREAD;
  46. }
  47.  
  48. /* overlay the original image on top of the drop shadow */
  49. $original_image = imagecreatefromjpeg($src);
  50. imagecopymerge($image, $original_image, 0,0, 0,0, $o_width, $o_height, 100);
  51.  
  52. /* output the image */
  53. header("Content-type: image/jpeg");
  54. imagejpeg($image, "", 100);
  55.  
  56. /* clean up the image resources */
  57. imagedestroy($image);
  58. imagedestroy($original_image);
  59. }
  60. ?>

URL: http://www.codewalkers.com/c/a/Miscellaneous/Adding-Drop-Shadows-with-PHP/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.