How to Upload and Resize Images in PHP

19 Jul

When building web applications in PHP, handling image uploads and resizing them is a common task. In this tutorial, we will demonstrate how to create a simple PHP script to upload and resize images. This guide covers creating a file upload form and processing the uploaded file to resize it.

Creating the File Upload Form

First, we need to create a form that allows users to upload their images. We will create two files: index.php for the form and upload_file.php to handle the upload and resizing process.

index.php

This file contains the HTML form for users to upload their images.

<!DOCTYPE html>
<html>
<head>
    <title>Upload and Resize Image</title>
</head>
<body>
    <form action="upload_file.php" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="file" id="file"><br>
        <input type="submit" name="submit" value="Submit">
    </form>
</body>
</html>

The enctype="multipart/form-data" attribute is crucial for file uploads via POST. Without this, the file upload will not work.

Handling the File Upload and Resizing

When the form is submitted, the file data is sent to upload_file.php for processing. This file will handle the upload and resizing logic.

upload_file.php

<?php
if ($_FILES) {
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 2000000)
    && in_array($extension, $allowedExts)) {

        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        } else {
            $filename = "upload/" . $_FILES["file"]["name"];
            move_uploaded_file($_FILES["file"]["tmp_name"], $filename);
            
            $resized_filename = "upload/" . 'thumb-'.$_FILES["file"]["name"];
            resize_image($filename, $resized_filename, 150, 150);

            echo "Stored in: " . $filename;
        }
    } else {
        echo "Invalid file";
    }
}

function resize_image($file, $destination, $w, $h) {
    list($source_width, $source_height, $source_type) = getimagesize($file);
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));

    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            $source_gdim = imagecreatefromjpeg($file);
            break;
        case 'png':
            $source_gdim = imagecreatefrompng($file);
            break;
        case 'gif':
            $source_gdim = imagecreatefromgif($file);
            break;
        default:
            return;
    }

    $source_aspect_ratio = $source_width / $source_height;
    $desired_aspect_ratio = $w / $h;

    if ($source_aspect_ratio > $desired_aspect_ratio) {
        $temp_height = $h;
        $temp_width = (int)($h * $source_aspect_ratio);
    } else {
        $temp_width = $w;
        $temp_height = (int)($w / $source_aspect_ratio);
    }

    $temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
    imagecopyresampled($temp_gdim, $source_gdim, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height);

    $x0 = ($temp_width - $w) / 2;
    $y0 = ($temp_height - $h) / 2;
    $desired_gdim = imagecreatetruecolor($w, $h);
    imagecopy($desired_gdim, $temp_gdim, 0, 0, $x0, $y0, $w, $h);

    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($desired_gdim, $destination, 100);
            break;
        case 'png':
            imagepng($desired_gdim, $destination);
            break;
        case 'gif':
            imagegif($desired_gdim, $destination);
            break;
    }

    imagedestroy($desired_gdim);
}
?>

Explanation

  • File Validation: The script checks the file type and size to ensure it is an acceptable image.
  • File Upload: The move_uploaded_file function uploads the image to the upload directory.
  • Image Resizing: The resize_image function resizes the uploaded image to the specified dimensions and saves it with a new name.

Detailed Resizing Function

The resize_image function is responsible for resizing the uploaded image. It supports JPEG, PNG, and GIF formats. Here’s a breakdown of the function:

  • Get Image Dimensions and Type: The getimagesize function retrieves the width, height, and type of the image.
  • Create Image Resource: Based on the file extension, it creates an image resource using imagecreatefromjpeg, imagecreatefrompng, or imagecreatefromgif.
  • Calculate New Dimensions: The function calculates the new dimensions while maintaining the aspect ratio.
  • Resample Image: The imagecopyresampled function creates a new true color image with the specified dimensions.
  • Crop Image: If necessary, the image is cropped to the desired size.
  • Save Resized Image: Finally, the resized image is saved using imagejpeg, imagepng, or imagegif.

Conclusion

Uploading and resizing images in PHP is a straightforward process. By following the steps outlined in this tutorial, you can easily implement this functionality in your own projects. This guide provides the core code needed to upload and resize images, ensuring your application can handle images effectively.

For a complete working example, you can download the source code here.