How Can I Resize Image With PHP

18 June 2023 429 Reading time: 1 minute

To resize an image using PHP, you can use the GD library, which is a built-in library for image manipulation in PHP. Here's an example code that demonstrates how to resize an image:

<?php
// Set the path to the source image
$sourceImagePath = 'path/to/source/image.jpg';
// Set the path to the resized image
$resizedImagePath = 'path/to/resized/image.jpg';

// Set the desired width and height for the resized image
$desiredWidth = 800;
$desiredHeight = 600;

// Get the original image dimensions
list($width, $height) = getimagesize($sourceImagePath);

// Calculate the aspect ratio
$aspectRatio = $width / $height;

// Calculate the new dimensions while maintaining the aspect ratio
if ($desiredWidth / $desiredHeight > $aspectRatio) {
    $newWidth = $desiredHeight * $aspectRatio;
    $newHeight = $desiredHeight;
} else {
    $newWidth = $desiredWidth;
    $newHeight = $desiredWidth / $aspectRatio;
}

// Create a new image resource based on the source image
$sourceImage = imagecreatefromjpeg($sourceImagePath);

// Create a new blank image with the desired dimensions
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);

// Resize the source image to the new dimensions
imagecopyresampled($resizedImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Save the resized image to the specified path
imagejpeg($resizedImage, $resizedImagePath);

// Free up memory by destroying the image resources
imagedestroy($sourceImage);
imagedestroy($resizedImage);

echo "Image resized successfully!";
?>

Make sure you replace 'path/to/source/image.jpg' and 'path/to/resized/image.jpg' with the actual paths to your source image and the desired resized image respectively. Also, adjust the $desiredWidth and $desiredHeight variables to the dimensions you want for the resized image.

This example assumes you are working with JPEG images. If you are working with a different image format, you'll need to use the appropriate functions (imagecreatefrompng(), imagepng(), etc.) for that format.

Similar articles