For a website I run, users can upload pictures they've drawn to a gallery. We create a thumbnail and a small view of that image to display to other users (clicking the small view image shows the full sized image).
With this in mind, I created a very simple resize script. In most cases this script works perfectly. However, I've come across a single odd case in which the script messes up entirely.
When running the file http://img191.imageshack.us/img191/2268/935full.png (1641x3121) through the script (which creates one thumbnail with a max width or height of 150 and another of 400) we get a perfect thumbnail http://img267.imageshack.us/img267/5803/935thumb.png (78x150) and a small view image sized properly, but which is cut off and stretched http://img28.imageshack.us/img28/4002/935show.png (211 x 400).
With that in mind, my question is: Is this a problem in PHP or a logic error? And how can I fix it?
Thank you for your time. The code I use to create these thumbnails is below.
<?php
/**
* Creates a thumbnail for any type of pre-existing image. Always saves as PNG image
*
* @param string - The location of the pre-existing image.
* @param string - The location to save the thumbnail, including filename and extension.
* @param int - The Maximum Width, Default of 150
* @param int - The Maximum Height, Default of 150
* @return bool - Success of saving the thumbnail.
*/
function imagecreatethumbnail($file,$output,$max_width = 150,$max_height = 150)
{
$img = imagecreatefromstring(file_get_contents($file));
list($width, $height, $type, $attr) = getimagesize($file);
if($height > $max_height || $width > $max_width)
{
if($width > $height)
{
$thumb_width = $max_width;
$thumb_height = ceil(($height * $thumb_width)/$width);
}
else
{
$thumb_height = $max_height;
$thumb_width = ceil(($width * $thumb_height)/$height);
}
} else {
$thumb_width = $width;
$thumb_height = $height;
}
imagesavealpha($img,true);
$thumb = imagecreatetruecolor($thumb_width,$thumb_height);
imagesavealpha($thumb,true);
imagealphablending($thumb,false);
imagecopyresampled($thumb,$img,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
$return = imagepng($thumb,$output);
imagedestroy($img);
imagedestroy($thumb);
return $return;
}