Reputation: 653
I'm trying to resize (keeping the aspect ratio) and crop the excess of image (outside the thumbnail limits), but doing that while crop x = center and y = top.
I'm missing something here, but my final image fits inside the thumbnail area, and not fill it and crop the excess. Hope someone can help me on this.
This is my code, so far:
$image_width = 725; // not static, just an example
$image_height = 409; // not static, just an example
// image can be wide or portrait
$width = 140;
$height = 160;
$thumbnail = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($thumbnail, 255, 255, 255);
imagefill($thumbnail, 0, 0, $white);
$width_ratio = $image_width/$width;
$height_ratio = $image_height/$height;
if ($width_ratio>$height_ratio) {
$dest_width=$width;
$dest_height=$image_height/$width_ratio;
}
else{
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
}
$int_width = ($width - $dest_width)/2;
$int_height = ($height - $dest_height)/2;
imagecopyresampled($thumbnail, $original_image, $int_width, $int_height, 0, 0, $dest_width, $dest_height, $image_width, $image_height);
Thanks!
Upvotes: 0
Views: 1863
Reputation: 672
Your $image_width
, $image_height
, $width
and $height
are static, which means $width_ratio
and $height_ratio
are always they same aswell (respectively: 5.1785714285714
and 2.55625
, so width ratio is always higher then height ratio).
In this case, this block of your code:
if ($width_ratio>$height_ratio) {
$dest_width=$width;
$dest_height=$image_height/$width_ratio;
}
else{
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
}
will always run if
and never run else
- remove it and leave just:
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
and your image will be cropped based on higher value - in this case height will be resized accordingly to new height and excess of width will be cut off.
Hope this is what you were looking for!
EDIT:
Right now script if cutting off edges equally. If you want them to be cut fully from top or left (depends on ratio), then:
Remove that part of code totally:
$int_width = ($width - $dest_width)/2;
$int_height = ($height - $dest_height)/2;
Change your if
else
condition mentioned before to:
if($width_ratio < $height_ratio) {
$dest_width=$width;
$dest_height=$image_height/$width_ratio;
$int_width = ($width - $dest_width)/2;
$int_height = 0;
} else {
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
$int_width = 0;
$int_height = ($height - $dest_height)/2;
}
EDIT 2
Horizontal always cut off equally, vertical always from the top - as you wanted:
if($width_ratio < $height_ratio) {
$dest_width=$width;
$dest_height=$image_height/$width_ratio;
} else {
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
}
$int_width = ($width - $dest_width)/2;
$int_height = 0;
Upvotes: 1