I\'m wanting to write some PHP code which automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I\'m a relative PHP novice
Here is an extended version of the answer @Ian Atkin' gave. I found it worked extremely well. For larger images that is :). You can actually make smaller images larger if you're not careful. Changes: - Supports jpg,jpeg,png,gif,bmp files - Preserves transparency for .png and .gif - Double checks if the the size of the original isnt already smaller - Overrides the image given directly (Its what I needed)
So here it is. The default values of the function are the "golden rule"
function resize_image($file, $w = 1200, $h = 741, $crop = false)
{
try {
$ext = pathinfo(storage_path() . $file, PATHINFO_EXTENSION);
list($width, $height) = getimagesize($file);
// if the image is smaller we dont resize
if ($w > $width && $h > $height) {
return true;
}
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width - ($width * abs($r - $w / $h)));
} else {
$height = ceil($height - ($height * abs($r - $w / $h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w / $h > $r) {
$newwidth = $h * $r;
$newheight = $h;
} else {
$newheight = $w / $r;
$newwidth = $w;
}
}
$dst = imagecreatetruecolor($newwidth, $newheight);
switch ($ext) {
case 'jpg':
case 'jpeg':
$src = imagecreatefromjpeg($file);
break;
case 'png':
$src = imagecreatefrompng($file);
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
break;
case 'gif':
$src = imagecreatefromgif($file);
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
break;
case 'bmp':
$src = imagecreatefrombmp($file);
break;
default:
throw new Exception('Unsupported image extension found: ' . $ext);
break;
}
$result = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
switch ($ext) {
case 'bmp':
imagewbmp($dst, $file);
break;
case 'gif':
imagegif($dst, $file);
break;
case 'jpg':
case 'jpeg':
imagejpeg($dst, $file);
break;
case 'png':
imagepng($dst, $file);
break;
}
return true;
} catch (Exception $err) {
// LOG THE ERROR HERE
return false;
}
}