Wednesday, April 3, 2013

Image Manipulation using PHP and ImageMagicK

So there were a couple of problems with my last image processing functions (http://nodstrum.com/2006/12/09/image-manipulation-using-php/).
1. If you were trying to process a massive image > 1024px×768px it failed.
2. I only accounted for people processing Jpegs.
3. CPU spikes, because of the amount of processing that is being done with the image the CPU is really taking a hit.
4. The functions were really quite long.

These new function will use ImageMagicK, not all servers have ImageMagicK installed by default, check with your hosting provider.

So, here are the functions…
Thumbnail
function createThumbIMK($img, $imgPath, $thumbDir, $suffix, $newWidth, $newHeight) {
  // add in the suffix after the '.' dot.
 $newNameE = explode(".", $img);
 $newName = ''. $newNameE[0] .''. $suffix .'.'. $newNameE[1] .'';
 
  // ImageMagicK doesnt like '/' and 'x' characters in the command line call.
 $uploadedImg = ''. $imgPath .'/'. $img .'';
 $newThumb = ''. $thumbDir .'/'. $newName .'';
 $newRes = ''. $newWidth .'x'. $newHeight .'';
 
  // This makes a command line call to ImageMagicK.
  // My path to ImageMagicK Convert is '/usr/lib/php/bin/convert'
  // 'convert' is a program (UNIX) so no forward slash.
 $ct = system("/usr/lib/php/bin/convert -resize $newRes $uploadedImg $newThumb", $retval);
 
 return $ct;
}
Resize
function createResizedIMK($img, $imgPath, $thumbDir, $suffix, $by) {
  // add in the suffix after the '.' dot.
 $newNameE = explode(".", $img);
 $newName = ''. $newNameE[0] .''. $suffix .'.'. $newNameE[1] .'';
 
  // ImageMagicK doesnt like '/' and 'x' characters in the command line call.
  // And workout the size based on '$by'.
 $uploadedImg = ''. $imgPath .'/'. $img .'';
 $newResized = ''. $reduceDir .'/'. $newName .'';
 list($width, $height, $type, $attr) = getimagesize("$imgPath/$img");
 $newWidth = ($width/$by);
 $newHeight = ($height/$by);
 $newRes = ''. $newWidth .'x'. $newHeight .'';
 
  // This makes a command line call to ImageMagicK.
  // My path to ImageMagicK Convert is '/usr/lib/php/bin/convert'
  // 'convert' is a program (UNIX) so no forward slash.
 $cr = system("/usr/lib/php/bin/convert -resize $newRes $uploadedImg $newResized", $retval);
 
 return $cr;
}
!! Important: you must ensure that when you pass $img to the functions that it has no spaces in it… here is an example (replacing spaced with ‘_’ underscores. Also dont forget to rename the actual file. !!
$imgSafe = str_replace(" ", "_", $img);
rename("$dir/$img", "$dir/$imgSafe");
Here are some examples. Building Original (916K (2576×1932)) Building Thumb (20K (120×90)) Building Resized and Reduced (71K (515×386))

No comments:

Post a Comment