How to crop image before uploading in PHP?

Member

by samara , in category: PHP General , 8 months ago

How to crop image before uploading in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 3 months ago

@samara 

You can use the imagecopyresampled function in PHP to crop an image. Here's an example of how to use this function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php

// Load the image
$image = imagecreatefromjpeg('original.jpg');

// Crop the image
$cropped = imagecreatetruecolor(200, 200);
imagecopyresampled($cropped, $image, 0, 0, 0, 0, 200, 200, imagesx($image), imagesy($image));

// Save the cropped image
imagejpeg($cropped, 'cropped.jpg');

?>


This example will take an image called original.jpg, crop it to 200x200 pixels, and save the result as cropped.jpg.


You can also use the imagecopyresized function to crop an image. This function works in a similar way to imagecopyresampled, but it uses a faster algorithm that can result in lower quality images.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php

// Load the image
$image = imagecreatefromjpeg('original.jpg');

// Crop the image
$cropped = imagecreatetruecolor(200, 200);
imagecopyresized($cropped, $image, 0, 0, 0, 0, 200, 200, imagesx($image), imagesy($image));

// Save the cropped image
imagejpeg($cropped, 'cropped.jpg');

?>


You can also use the imagecrop function, which can automatically crop an image to a given width and height.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

// Load the image
$image = imagecreatefromjpeg('original.jpg');

// Crop the image
$cropped = imagecrop($image, ['x' => 0, 'y' => 0, 'width' => 200, 'height' => 200]);

// Save the cropped image
imagejpeg($cropped, 'cropped.jpg');

?>


This example will crop the top left corner of the image to 200x200 pixels. You can adjust the x, y, width, and height values to change the part of the image that is cropped.