Case Introduction
In PHP, you want to write some code to pass a form Any images uploaded are automatically resized to 147x147px. You want to reduce the file size by scaling the image.
Code Implementation
To accomplish this task, you can use PHP's ImageMagick or GD functions to process images.
Using GD, you can achieve the following functions:
function resize_image($file, $w, $h, $crop=FALSE) { list($width, $height) = getimagesize($file); $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; } } $src = imagecreatefromjpeg($file); $dst = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); return $dst; }
You can call this function as follows:
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
As a rule of thumb, image resampling by GD It does reduce file size significantly, especially when resampling raw digital camera images.
The above is the detailed content of How Can I Resize Uploaded Images to 147x147px in PHP Using GD?. For more information, please follow other related articles on the PHP Chinese website!