Posted in: Uncategorized

Using Imagick for drop shadows

I wrote this code for this website. I wanted to be able to upload images and it would automatically add a drop shadow to those images and create a thumbnail.

You can use ImageMagick (using the exec() function) but if you’re on a shared server, you need to use Imagick which is a native php extension using the ImageMagick API. At the time of development, this site was only on a shared server.

<?php
// load in the original image
$image = new Imagick('input.jpg');
// set it to PNG so we can have a transparent layer (drop shadow)
$image->setImageFormat("png");
// clone the image into a new image, 'thumbnail'
$thumbnail = $image->clone();
// set the maximum width or height of the thumbnail
$maxsize = 300;
// Resizes to whichever is larger, width or height
if($thumbnail->getImageHeight() <= $thumbnail->getImageWidth()) {
 // Resize image using the lanczos resampling algorithm based on width
 $thumbnail->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
} else {
 // Resize image using the lanczos resampling algorithm based on height
 $thumbnail->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}
// duplicate for the shadow - full size image
$shadow_layer = $image->clone();
$shadow_layer->setImageBackgroundColor( new ImagickPixel( 'black' ) );
$shadow_layer->shadowImage( 60, 18, 0, 0 ); // 60% transparency, blur of 18
$shadow_layer->compositeImage( $image, Imagick::COMPOSITE_OVER, 36, 18 ); // overlay the image but move it 36px across, 18px down
// duplicate for the shadow - thumbnail image
$shadow_layer_thumbnail = $thumbnail->clone();
$shadow_layer_thumbnail->setImageBackgroundColor( new ImagickPixel( 'black' ) );
$shadow_layer_thumbnail->shadowImage( 60, 12, 0, 0 ); // 60% transparency, blur of 12
$shadow_layer_thumbnail->compositeImage( $thumbnail, Imagick::COMPOSITE_OVER, 24, 12 ); // overlay the image but move it 24px across, 12px down
// save the 2 images
$shadow_layer->writeImage ( "output.png"); // saved here so GD can open it
$shadow_layer_thumbnail->writeImage ( "thumbnail.png");
// convert the saved PNG to a JPG using GD (Imagick can't convert a PNG to JPG!!)
$input_file = "output.png";
$output_file = "output.jpg";
$input = imagecreatefrompng($input_file);
list($width, $height) = getimagesize($input_file);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
imagejpeg($output, $output_file);
//delete output.png
unlink('output.png');
// clear the GD resources
imagedestroy($input);
imagedestroy($output);
// clear the imagick resources
$image->clear();
$thumbnail->clear();
$shadow_layer->clear();
$shadow_layer_thumbnail->clear();
?>
<img src='thumbnail.png'>
<img src='output.jpg'>

image_create.php

Have your say

Recurring Date Settings

day week month year on
date of month day of week