How to resize images in PHP

Updated: January 12, 2024 By: Guest Contributor Post a comment

Understanding Image Processing in PHP

Resizing images is a common requirement for web applications, whether it’s for reducing the file size for quicker loading or simply to fit images into a specific design layout. In this guide, you will learn how to perform image resizing in PHP.

PHP offers several libraries for image processing, such as GD and Imagick. GD is a standard library that is more commonly available in PHP installations, while Imagick is a wrapper for the ImageMagick library that provides advanced image manipulation capabilities. This article focuses on using the GD library as it’s typically enabled by default in most PHP installations (there is also an advanced code example that uses Imagick).

Setting up Your Environment

Before you begin, make sure that the GD library is installed and enabled on your server. To check, you can create a phpinfo.php file and look for the GD section:

<?php
phpinfo();
?>

If GD is not installed, you may need to install or enable it through your server’s software management system or ask your hosting provider for assistance.

Resizing Images in PHP Using GD

To resize an image with GD, follow these steps:

Step 1 – Load the Original Image

The first step is to load the image you want to resize. You can do this using the imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromgif(), or a similar function depending on the image type:

$originalImage = imagecreatefromjpeg('path/to/your/image.jpg');

Step 2 – Create a New Image Canvas

Next, create a true color image canvas with the desired dimensions using the imagecreatetruecolor() function:

$width = 200; // desired image width
$height = 150; // desired image height
$newImage = imagecreatetruecolor($width, $height);

Step 3 – Copy and Resize the Image

Use imagecopyresampled() to resize and copy a portion of the original image onto the true color canvas:

imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $width, $height, imagesx($originalImage), imagesy($originalImage));

Step 4 – Save the Resized Image

To save the resized image, use a function like imagejpeg() or imagepng() depending on your image’s original format:

imagejpeg($newImage, 'path/to/resized/image.jpg', 90); // 90 is the quality setting

Step 5 – Clean Up

Remember to free any memory associated with your images by destroying them once they’re saved:

imagedestroy($originalImage);
imagedestroy($newImage);

Handling Different Image Types and Aspect Ratios

Image Types: Ensure you’re using the correct function for loading and saving your images based on their file types. For instance, imagecreatefrompng() for PNG files and imagepng() for saving them.

Aspect Ratios: To maintain the aspect ratio, you should calculate the new width or height proportionally to the original dimensions:

$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);
$newWidth = $width; // desired width
$newHeight = ($originalHeight / $originalWidth) * $newWidth;

Advanced Techniques

For more advanced control, explore:

  • Imagick: If you need more features, consider using Imagick, which provides robust image manipulation capabilities.
  • Resizing Algorithms: Experiment with different algorithms in imagecopyresampled() to fine-tune the quality.

Example:

<?php

function resizeImageWithImagick($imagePath, $newWidth, $newHeight) {
    try {
        // Create an Imagick object
        $imagick = new Imagick($imagePath);

        // Set the resize algorithm - Imagick::FILTER_LANCZOS is a good choice for quality
        $filterType = Imagick::FILTER_LANCZOS;

        // Resize the image
        $imagick->resizeImage($newWidth, $newHeight, $filterType, 1);

        // Set to use jpeg compression
        $imagick->setImageFormat('jpeg');

        // Send the headers and output the image
        header('Content-Type: image/jpeg');
        echo $imagick;

        // Clear Imagick resources
        $imagick->clear();
        $imagick->destroy();
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage();
    }
}

$imagePath = 'path/to/your/image.jpg';
$newWidth = 800;  // Set the new width
$newHeight = 600; // Set the new height

resizeImageWithImagick($imagePath, $newWidth, $newHeight);

?>

Explanation:

  • The resizeImageWithImagick function takes the path to an image, a new width, and a new height as parameters.
  • The Imagick object is created from the image file.
  • The resizeImage method is used to resize the image. The Imagick::FILTER_LANCZOS filter is a good general-purpose choice for quality resizing.
  • The image format is set to JPEG, but you can change it based on your requirements.
  • The image is output directly to the browser.
  • Imagick’s resources are cleared after use.

Notes:

  • Make sure the Imagick extension is installed and enabled in your PHP setup.
  • The $newWidth and $newHeight parameters should be set according to your desired output size.
  • The resize algorithm ($filterType) can be changed to other Imagick::FILTER_* constants depending on your quality and performance requirements.
  • Exception handling is used to catch and display any errors that occur during the process.

Conclusion

Image resizing in PHP with the GD library is straightforward. By following these steps, you can incorporate image resizing functionality into your PHP applications with ease.