How can one resize and save an uploaded image to a different directory using PHP?
To resize and save an uploaded image to a different directory using PHP, you can use the GD library functions to manipulate the image. First, upload the image using move_uploaded_file() function, then use imagecreatefromjpeg(), imagecreatefrompng() or imagecreatefromgif() to create an image resource. Resize the image using imagecopyresampled() function and save it to a different directory using imagejpeg(), imagepng() or imagegif().
$uploadDir = 'uploads/';
$resizeDir = 'resized/';
$filename = $_FILES['file']['name'];
$uploadFile = $uploadDir . $filename;
$resizeFile = $resizeDir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);
list($width, $height) = getimagesize($uploadFile);
$newWidth = 100; // Set new width
$newHeight = ($height / $width) * $newWidth;
$src = imagecreatefromjpeg($uploadFile);
$dst = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($dst, $resizeFile);
imagedestroy($src);
imagedestroy($dst);
Keywords
Related Questions
- Is it advisable to use json_encode() to store data in session variables in PHP?
- What are common pitfalls when using PHP for pagination functions like the one described in the forum thread?
- What are the implications of using external time sources, such as the atomic time from Leipzig, in PHP scripts to ensure accurate timekeeping?