Skip to content

Instantly share code, notes, and snippets.

@ckchaudhary
Created January 26, 2014 06:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckchaudhary/8629182 to your computer and use it in GitHub Desktop.
Save ckchaudhary/8629182 to your computer and use it in GitHub Desktop.
<?php
/**
* wdw_crop_img (http://webdeveloperswall.com/wordpress/crop-image-script)
* crops the image to given width and height
* Parameters :-
* $image_url : string : absolute url to the image
* $width: int : desired width after cropping
* $height : desired height after cropping
* $upload_directory : name of the target directory (directoty inside wp-content>uploads folder)
* Returns :- an array containing errors/success messages, new(cropped) file path and cropped file url
returned array example:
$msg['message'] will be either 'success' or 'error'
$msg['path'] will be either blank (error) or something like c:\\path\to\wordpress\wp-content\uploads\myuploads\cropped_image.jpg
$msg['url'] will be either blank (error) or something like http://yourdomain.com/wp-content/uploads/myuploads/cropped_image.jpg
*/
function wdw_crop_img($image_url, $i_width, $i_height, $upload_directory){
$msg = array(
'message' => '',
'path' => '',
'url' =>''
);
$upl_dir = wp_upload_dir();
//an array : $upload_directory[basedir] => C:\path\to\wordpress\wp-content\uploads
$upload_folder = $upl_dir['basedir']."/" . $upload_directory;
$upload_url = $upl_dir['baseurl']."/" . $upload_directory;
$new_name = "img_" .uniqid(). uniqid() . ".jpg";
$filename = $upload_folder . "/" . $new_name;
$fileurl = $upload_url . "/" . $new_name;
$image = imagecreatefromstring(file_get_contents($image_url));
$thumb_width = $i_width;
$thumb_height = $i_height;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
try {
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
$msg['message'] = 'success';
$msg['url'] = $fileurl;
$msg['path'] = $filename;
}
catch(Exception $e){
$msg['message'] = 'error';
}
return $msg;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment