-
-
Save jasdeepkhalsa/4339969 to your computer and use it in GitHub Desktop.
Using PHP and GD to crop an image proportionally according to its aspect ratio. From: http://stackoverflow.com/questions/1855996/crop-image-in-php
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
<?php | |
$image = imagecreatefromjpeg($_GET['src']); | |
$filename = 'images/cropped_whatever.jpg'; | |
$thumb_width = 200; | |
$thumb_height = 150; | |
$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 ); | |
// 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); | |
?> |
Kudos!! to the designer of this site. Good job, I love it.
Isn't there a way the individual comments can be replied upon a click of a button?
Thanks, works great !
thanks for this code.
YOU ARE THE BEST
wow :)
Wow, brilliant, thanks so much!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The only, real working method to crop images in PHP. Thanks very much!