The function imagecopyresampled is useful to generate a thumbnail or resize images, while keeping aspect ratio:
$fn = $_FILES['data']['tmp_name'];
$size = getimagesize($fn);
$width = $size[0];
$height = $size[1];
$ratio = $width / $height;
if ($ratio > 1 && $size[0] > 500) { $width = 500; $height = 500 / $ratio; }
else { if ($ratio <= 1 && $size[1] > 500) { $width = 500 * $ratio; $height = 500; }}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width, $height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
imagedestroy($src);
imagejpeg($dst, 'test.jpg');
imagedestroy($dst);
How can I select the resizing algorithm used by PHP?
Note: as stated in this question, setting imagesetinterpolation($dst, IMG_BILINEAR_FIXED);
or such things doesn't seem to work.
According to tests I did (in another language), "bilinear resizing" sometimes gives better result than bicubic, and sometimes it's the contrary (depends if it's downsizing or upsizing).
(source: dpchallenge.com)
An alternative is the imagescale()
function, that allows specifying the interpolation algorithm as a parameter:
imagescale($image, $new_width, $new_height, $algorithm);
According to the documentation $algorithm
can be:
One of
IMG_NEAREST_NEIGHBOUR
,IMG_BILINEAR_FIXED
,IMG_BICUBIC
,IMG_BICUBIC_FIXED
or anything else (will use two pass).
A test in PHP 7.0.15 (comparing file hash) shows that BICUBIC and BICUBIC_FIXED result in a different image, while BILINEAR_FIXED and NEAREST_NEIGHBOUR result in the same image.