Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to crop an image to the given rectangle using imagecrop() function using PHP?
imagecrop() is an inbuilt function in PHP that is used to crop an image to the given rectangle. It crops the image from the given rectangle area and returns the output image. The given image is not modified.
Syntax
resource imagecrop ($image, $rect)
Parameters
imagecrop() takes two parameters, $image and $rect.
$image − It is the parameter returned by the image creation functions, such as imagecreatetruecolor(). It is used to create the size of an image.
$rect − The cropping rectangle is an array with keys x, y, width, and height.
Return Values
imagecrop() returns the cropped image resource on success or it returns false on failure.
Example 1: Basic Image Cropping
The following example demonstrates how to crop an image to specific dimensions ?
<?php
// Create an image from the given image
$img = imagecreatefrompng('/path/to/input/image.png');
// Set the size of the cropped image
$img2 = imagecrop($img, ['x' => 0, 'y' => 0, 'width' => 500, 'height' => 320]);
if($img2 !== FALSE) {
imagepng($img2, '/path/to/output/cropped.png');
imagedestroy($img2);
}
imagedestroy($img);
?>
Example 2: Dynamic Square Cropping
This example creates a square crop using the minimum dimension of the original image ?
<?php
// Load an image from the local drive folder
$filename = '/path/to/input/image.png';
$img = imagecreatefrompng($filename);
$ini_x_size = getimagesize($filename)[0];
$ini_y_size = getimagesize($filename)[1];
// The minimum of x length and y length to crop
$crop_measure = min($ini_x_size, $ini_y_size);
$crop_array = array(
'x' => 0,
'y' => 0,
'width' => $crop_measure,
'height' => $crop_measure
);
$thumb_img = imagecrop($img, $crop_array);
imagejpeg($thumb_img, '/path/to/output/thumb.jpg', 100);
imagedestroy($thumb_img);
imagedestroy($img);
?>
Installation: This function requires the GD extension to be enabled in PHP. Install via:
sudo apt-get install php-gd(Ubuntu) or enable in php.ini:extension=gd
Key Points
The original image remains unchanged after cropping
Always check if the crop operation returns FALSE to handle failures
Remember to call imagedestroy() to free up memory
The crop rectangle coordinates start from the top-left corner (0,0)
Conclusion
The imagecrop() function provides an efficient way to extract specific portions of images in PHP. Use it for creating thumbnails, removing unwanted areas, or preparing images for specific display requirements.
