Saturday, January 29, 2011

php resize image keeping constrants proportions

A simplest and efficient method to resize a image keeping the constraint proportions.
<?
list($width, $height) = getimagesize($image);
$new_dimensions = resize_dimensions($targetwidth,$targetheight,$width,$height);
// Calculates restricted dimensions with a maximum of $target_width by $target_height
function resize_dimensions($target_width,$target_height,$width,$height) {
    $return = array(‘width’ => $width, ‘height’ => $height);
    // If the ratio > target ratio and the width > target width resize down to target width
    if ($width/$height > $target_width/$target_height && $width > $target_width) {
        $return['width'] = $target_width;
        $return['height'] = $target_width/$width * $height;
    }
    // Otherwise, if the height > target, resize down to target height
    else if ($height > $target_height) {
        $return['width'] = $target_height/$height * $width;
        $return['height'] = $target_height;
    }
    return $return;
}
?>

No comments:

Post a Comment