Skip to content

Instantly share code, notes, and snippets.

@faishal
Created January 9, 2014 06:13
Show Gist options
  • Save faishal/8330120 to your computer and use it in GitHub Desktop.
Save faishal/8330120 to your computer and use it in GitHub Desktop.
Auto crop image using image magic
//Calculate frame ratio
$frame_ratio = ( float ) $frame_w / ( float ) $frame_h ;
//Calculate image ratio
$image_ratio = ( float ) $image_w / ( float ) $image_h ;
//Checking if both ratio are same
if ( round ( $frame_ratio , 2 ) != round ( $image_ratio , 2 ) ) {
//Ratio are not same, in that case we need to calculate new width and height of image to crop
//checking frame and image are of same type (portrait, landscape or square )
if ( floor ( $image_ratio ) != floor ( $frame_ratio ) ) {
//here not same type, in that case we will temporary interchange the height & width to make them same type
$temp = $image_w ;
$image_w = $image_h ;
$image_h = $temp ;
}
//calculating new width and height by taking minimum value
if ( $image_w < $image_h ) {
//Portrait
$frame_w = $image_w ;
//calculating height from ratio
$frame_h = $image_w / $frame_ratio ;
} else {
//Landscape
$frame_h = $image_h ;
//calculating width from ratio
$frame_w = $image_h * $frame_ratio ;
}
}
//reading image
$image = new Imagick ( $image_path ) ;
//this will scale and crop the image from the Center
$image -> cropThumbnailImage ( $frame_w , $frame_h ) ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment