Wednesday, August 25, 2010

Creating web thumbnails with PHP Imagick


// the location of your image $imagePath = '/path/to/source_image'; // these are treated as maximums and aspect ratio is maintained $thumbnailWidth = 100; $thumbnailHeight = 100; // path to the sRGB ICC profile $srgbPath = '/path/to/sRGB_v4_ICC_preference.icc'; // load the original image $image = new Imagick($imagePath); // get the original dimensions $width = $image->getImageWidth(); $height = $image->getImageHeight(); // set colour profile // this step is necessary even though the profiles are stripped out in the next step to reduce file size $srgb = file_get_contents($srgbPath); $image->profileImage('icc', $srgb); // strip colour profiles $image->stripImage(); // set colorspace $image->setImageColorspace(Imagick::COLORSPACE_SRGB); // determine which dimension to fit to $fitWidth = ($thumbnailWidth / $width) < ($thumbnailHeight / $height); // create thumbnail $image->thumbnailImage(   $fitWidth ? $thumbnailWidth : 0,   $fitWidth ? 0 : $thumbnailHeight ); // generate a thumbnail filename $imagePathParts = pathinfo($imagePath); $thumbnailPath =   $imagePathParts['dirname'].'/'.   $imagePathParts['filename'].'_'.   $thumbnailWidth.'x'.$thumbnailHeight.   '.jpg'; // save thumbnail and free up memory $image->writeImage($thumbnailPath); $image->clear(); $image->destroy();

No comments:

Post a Comment