Smarter resizing of images in PHP
Whenever I want to resize images in PHP code I use the SimpleImage.php script by Simon Jarvis. This code wraps PHP’s image functionality into a nice little class that’s very quick to implement.
One of the most helpful features of the script is its ability to resize an image to a set height or width, while maintaining the image aspect ratio:
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
But the problem with this sort of resize operation is that users will always find a way to upload the longest and thinnest image they can, or the shortest and widest image they can, and mess up your nice layout.
Instead, adding the following code to the SimpleImage.php class addresses this issue:
function resizetoMax($size) {
if ($this->getWidth() > $this->getHeight())
resizeToWidth($size);
else
resizeToHeight($size);
}
Calling the function resizetoMax(150); will resize the image so that neither the width nor the height are over 150px. However if it is a long, thin image then the height will take up the entire 150 pixels, and if it is a short, wide image then the width will take up the entire 150 pixels.

