How to crop an image to the given rectangle using imagecrop() function using PHP?

PHPServer Side ProgrammingProgramming

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

<?php
   // 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');
      imagedestroy($img2);
   }
   imagedestroy($img);
?>

Output

Input image before using imagecrop() function

Output image after using imagecrop() function

Example 2

<?php
   //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'=>
   $crop_measure);
   $thumb_img = imagecrop($img, $crop_array);
   imagejpeg($thumb_img, 'thumb.png', 100);
?>

Output

raja
Published on 09-Aug-2021 10:19:31
Advertisements