I found a php code to resize a image with aspect ratio without cropping. Its very easy and useful.
<?php
function resize($blob_binary, $desired_width, $desired_height) {
// simple function for resizing images to specified dimensions from the request variable in the url
$im = imagecreatefromstring($blob_binary);
$old_x = imageSX($im);
$old_y = imageSY($im);
# v_fact and h_fact are the factor by which the original vertical / horizontal
# image sizes should be multiplied to get the image to your target size.
$v_fact = $desired_height / $old_y ;
$h_fact = $desired_width / $old_x ;
# you want to resize the image by the same factor in both vertical
# and horizontal direction, so you need to pick the correct factor from
# v_fact / h_fact so that the largest (relative to target) of the new height/width
# equals the target height/width and the smallest is lower than the target.
# this is the lowest of the two factors
$im_fact = min($v_fact, $h_fact);
$thumb_h = $old_y * $im_fact;
$thumb_w = $old_x * $im_fact;
$new = ImageCreateTrueColor($thumb_w,$thumb_h) or exit("bad url");
imagecopyresampled($new,$im,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y) or exit("bad url");
imagedestroy($im);
imagejpeg($new, null, 85) or exit("bad url");
echo $new;
}
?>
<?php
function resize($blob_binary, $desired_width, $desired_height) {
// simple function for resizing images to specified dimensions from the request variable in the url
$im = imagecreatefromstring($blob_binary);
$old_x = imageSX($im);
$old_y = imageSY($im);
# v_fact and h_fact are the factor by which the original vertical / horizontal
# image sizes should be multiplied to get the image to your target size.
$v_fact = $desired_height / $old_y ;
$h_fact = $desired_width / $old_x ;
# you want to resize the image by the same factor in both vertical
# and horizontal direction, so you need to pick the correct factor from
# v_fact / h_fact so that the largest (relative to target) of the new height/width
# equals the target height/width and the smallest is lower than the target.
# this is the lowest of the two factors
$im_fact = min($v_fact, $h_fact);
$thumb_h = $old_y * $im_fact;
$thumb_w = $old_x * $im_fact;
$new = ImageCreateTrueColor($thumb_w,$thumb_h) or exit("bad url");
imagecopyresampled($new,$im,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y) or exit("bad url");
imagedestroy($im);
imagejpeg($new, null, 85) or exit("bad url");
echo $new;
}
?>
No comments:
Post a Comment
Leave a Comment