Tutorial: Logic behind resizing image and keeping aspect ratio

Once in a while you'll encounter this problem and the logic usually remains the same regardless of what language you're using.

Use cases are:

  1. Resize to given width and height, ignoring image aspect ratio
  2. Resize to given width, keeping height in the correct aspect ratio
  3. Resize to height, keeping height in the correct aspect ratio

The tutorial/example below is given in PHP, but if you skim the lines of code its just some common control statements that are used.

if (!file_exists($resized_file)) {
$image_info = image_get_info($input_file);
$w = $image_info['width'];
$h = $image_info['height'];

if (!$reso['keep_ratio']) {
$w = intval($reso['width'] != -1 ? $reso['width'] : $image_info['width'] * ($reso['height'] / $image_info['height']));
$h = intval($reso['height'] != -1 ? $reso['height'] : $image_info['height'] * ($reso['width'] / $image_info['width']));
}

else {
// Check if resize needed ...
if (($image_info['width'] > $reso['width']) || ($image_info['height'] > $reso['height'])) {
// Compare ratios to determine which side is longer
// If width ratio < height ratio, then use height/width, otherwise width/height
$resize_by_width = (($image_info['width'] / $reso['width']) > ($image_info['height'] / $reso['height']));

$resize_ratio = ($resize_by_width ? $reso['width'] / $image_info['width'] : $reso['height'] / $image_info['height']);

$w = $image_info['width'] * $resize_ratio;
$h = $image_info['height'] * $resize_ratio;
}
}

image_resize($input_file, $resized_file, $w, $h);
}

Hopefully thats fairly easy to translate into another programming language.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog