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.


resource imagecrop ($image, $rect)


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.


   // It will create an image from the given image
   $img = imagecreatefrompng('C:\xampp\htdocs\Images\img34.png');
   // This will find the size of the image
   $size = min(imagesx($img), imagesy($img));
   //This will set the size of the cropped image.
   $img2 = imagecrop($img, ['x' => 0, 'y' => 0, 'width' => 500, 'height' => 320]);
   if($img2 !== FALSE) {
      imagepng($img2, 'C:\xampp\htdocs\pic_cropped.png');


Input image before using imagecrop() function

Output image after using imagecrop() function

Example 2

   //load an image from the local drive folder.
   $filename = 'C:\xampp\htdocs\Images\img34.png';
   $img = imagecreatefrompng($filename );

   $ini_x_size = getimagesize($filename)[0];
   $ini_y_size = getimagesize($filename )[1];

   //the minimum of xlength and ylength to crop.
   $crop_measure = min($ini_x_size, $ini_y_size);
   // Set the content-type header
   //header('Content-Type: image/png');
   $crop_array = array('x' =>0 , 'y' => 0, 'width' => $crop_measure, 'height'=>
   $thumb_img = imagecrop($img, $crop_array);
   imagejpeg($thumb_img, 'thumb.png', 100);


Updated on: 09-Aug-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started