Resize images and keep proportions

One common task for programmers is to create thumbnails, or resize images in general. Different programming languages and systems have different ways to handle the actual image resize process in bitmap level.

The low level resize process is usually handled by a specialized library for image processing. However, before the program gets in the final resize process the programmer is required to provide the dimensions of the new image version. If keeping proportions is not required the entire process is very straight forward. If keeping proportions is required, which usually is, your program must calculate the new width and height.

The following code is a small script in PHP that calculates the resize dimensions. The variables $dst_w and $dst_h (short for denstination width and denstination height respectively) are the input variables you should fill in and $rsz_w and $rsz_h (short for resized width and height) are the dimensions you need to find.

$dst_w = 100; // customize this value
$dst_h = 100; // customize this value

$rsz_h = $dst_h;
$rsz_w = (int) floor($src_w * $dst_h / $src_h);
if ($rsz_w > $dst_w) {
    $rsz_h = (int) floor($dst_w * $src_h / $src_w);
    $rsz_w = $dst_w;
}