Friday, February 25, 2005

PHPretty Images

function tn($url) {
$step = 2;
list($width, $height, $type, $attr) = getimagesize($url);

if ($width <= $height) { $ratio["width"] = $height/$width; $ratio["height"] = 1; } else { $ratio["width"] = 1; $ratio["height"] = $width/$height; } while ($height > 90) {
$height = $height - $step * $ratio["width"];
$width = $width - $step * $ratio["height"];


return array("width" => $width, "height" => $height);

That's it. Badly remembered primary school math and PHP. Result? Reasonably sized thumbnails. I thought it would have been harder.

Refactoring & Optimisation Thoughts

  • $step is derived from the current height of the image vs. the intended size, thus really big images are quickly reduced initially. The closer you get to ideal, the smaller the step. Probably a good idea to set a bottom for the step, unless you want to waste a lot of cycles.

  • More generalisation during refactoring. $step, ideal $height & ideal $width should all be parameters.

  • Is there a way to ditch the iterations? That would improve performance a gadzillion-fold.

This code is part of - see, I'm not being that lazy!
Post a Comment