Created
January 9, 2014 06:13
-
-
Save faishal/8330120 to your computer and use it in GitHub Desktop.
Auto crop image using image magic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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