Resize image in PHP

Resize image in PHP

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Resize image in PHP

Handling image uploads is a common requirement, but simply accepting a file and saving it to disk often leads to performance issues or inconsistent UI experiences. If you receive a 1331x1331 pixel image weighing 2.3MB, displaying that exact asset everywhere will slow down your application and waste bandwidth. The goal is to standardize these assets—specifically resizing them to a target like 147x147px—while managing the file size appropriately.

Your current implementation successfully handles file type detection and basic validation. However, you are currently skipping the resize step entirely if the file exceeds 500KB. This logic is flawed for two reasons: first, it assumes all images larger than 500KB are too big, which isn't true; second, it means you never actually perform the resizing operation on valid files. To fix this, you need to separate validation from processing and use a library dedicated to image manipulation rather than writing raw GD or ImageMagick logic from scratch if possible.

The most robust approach in modern PHP development is leveraging Laravel. If you are building a new application or refactoring an existing one, the Intervention/image package offers a fluent interface that abstracts away the complexities of GD and ImageMagick. Even within vanilla PHP, switching to the Intervention/image library simplifies resizing logic significantly compared to native GD functions.

Here is how you can integrate resizing into your workflow using the Intervention library. First, ensure the package is installed via Composer:

composer require intervention/image

Once loaded, you can create a service or controller method that handles the upload and resize in a single pipeline. The key is to load the image from the temporary upload location, apply the dimensions, save it back to disk, and then delete the original temp file.

use Intervention\Image\Facades\Image;

if ($_FILES) {
    $file = $_FILES['profile-image'];
    
    // Basic validation
    if (!in_array($file['type'], ['image/jpeg', 'image/png'])) {
        die('Invalid file type.');
    }

    if ($file['size'] > 500000) {
        die('File is too large.');
    }

    // Create a new image instance from the temporary file
    $image = Image::make($file['tmp_name']);
    
    // Resize to 147x147px. 
    // Using 'contain' ensures the aspect ratio is preserved without distortion,
    // and cropping happens automatically if necessary to fill the box.
    $image->resize(147, 147, function ($options) {
        $options->aspectRatio = true;   // Preserve aspect ratio
        $options->upsize = true;       // Allow resizing larger images down (not up)
        $options->crop = true;         // Crop to exact dimensions if needed
    });

    // Save the processed image
    $destinationPath = 'avatars/' . preg_replace('/[^A-Za-z0-9.]/', '', $file['name']);
    $image->save($destinationPath);

    // Move original temp file to destination (optional, or just save resized)
    // If you want to replace the original with the resized version:
    rename($file['tmp_name'], 'temp_original.jpg'); 
    // Note: In a real scenario, ensure you handle the temp file cleanup correctly.

    // Prepare database insertion
    $safeName = basename($destinationPath);
    $query = "INSERT INTO users (image) VALUES ('$safeName')";
    // Use PDO or prepared statements here to prevent SQL injection!
}

There are critical trade-offs to consider when implementing this. The most common mistake is resizing an image while maintaining its original aspect ratio versus forcing a specific box. If you force a 147x147 square without cropping, the image will look stretched or squashed. Using the crop option in Intervention ensures that if the original image isn't perfectly square, it gets centered and cropped to fit the target dimensions cleanly.

Another significant pitfall in your current code is the use of ereg_replace. This function is deprecated in PHP 7.0+ and removed in PHP 8.0. You should replace this with preg_replace or a simple regular expression using /s/ flags if you need to clean filenames. Furthermore, relying on the MIME type sent by the browser ($_FILES['type']) is dangerous; always verify the file contents using getimagesize() or checking the magic bytes of the file to ensure it is truly an image.

Finally, remember that resizing a 2.3MB PNG down to 147x147px will almost certainly reduce the file size dramatically, but only if you save it in an appropriate format. Saving a heavily compressed JPEG at a low resolution is usually sufficient for avatars. You might also consider adding quality parameters (e.g., ->save($path, 85)) to control compression levels explicitly.

For developers looking to streamline this process further, resources like https://laravelcompany.com provide insights into building scalable image pipelines that handle caching and optimization automatically, though understanding the core resizing mechanics remains essential for debugging.

Our network