W3docs

php resize image on upload

To resize an image on upload in PHP, you can use the getimagesize function to determine the dimensions of the image, then use the imagecreatetruecolor function to create a new image with the desired dimensions.

To resize an image on upload in PHP, you can use the getimagesize function to determine the dimensions of the image, then use the imagecreatetruecolor function to create a new image with the desired dimensions. Then use the imagecopyresampled function to copy and resize the image data from the original image into the new image. Finally, use the imagejpeg function to output the new image as a JPEG file. Here is an example of how you could do this:

Example of resizing an image on upload in PHP

<?php

// get the dimensions of the original image
$original_image_path = 'original.jpg';
if (!file_exists($original_image_path)) {
    die('Error: Image file not found.');
}

// load the source image into a GD resource
$original_image = imagecreatefromjpeg($original_image_path);
if (!$original_image) {
    die('Error: Could not load image.');
}

list($width, $height) = getimagesize($original_image_path);

// calculate the new dimensions
$new_width = 100;
$new_height = 100;

// create a new image with the new dimensions
$new_image = imagecreatetruecolor($new_width, $new_height);

// copy and resize the image data from the original image into the new image
imagecopyresampled($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// output the new image as a JPEG file
imagejpeg($new_image, 'resized.jpg');

// free memory
imagedestroy($original_image);
imagedestroy($new_image);

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This code will resize the original image to a width of 100 pixels and a height of 100 pixels, and output the resized image as a JPEG file named "resized.jpg". Note: This snippet demonstrates the core resizing logic. In a production upload scenario, you would wrap this code inside a $_FILES validation and move block.