How to resize image before upload in PHP?

by darrion.kuhn , in category: PHP General , 9 months ago

How to resize image before upload in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 4 months ago

@darrion.kuhn 

To resize an image in PHP, you can use the GD library, which is built into PHP. You can use the imagecreatetruecolor() function to create a new image with the desired dimensions, and then use the imagecopyresampled() function to copy and resize the original image onto the new image.

Here is an example of how you can resize an image in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// Open the original image
$original_image = imagecreatefromjpeg('original.jpg');

// Create a new blank image with the desired dimensions
$new_width = 200;
$new_height = 150;
$new_image = imagecreatetruecolor($new_width, $new_height);

// Copy and resize the original image onto the new image
imagecopyresampled($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

// Save the resized image to a new file
imagejpeg($new_image, 'resized.jpg');

// Destroy the original and resized images to free up memory
imagedestroy($original_image);
imagedestroy($new_image);

In this example, the original image is opened and stored in the $original_image variable. Then, a new image is created with the desired dimensions and stored in the $new_image variable. The imagecopyresampled() function is used to copy and resize the original image onto the new image. Finally, the resized image is saved to a new file and the original and resized images are destroyed to free up memory.

Keep in mind that this is just one way to resize an image in PHP, and there are many other possible approaches you can take.