PHP Example | Crop an Image

This php example code shows us how to crop an image in php.

<?php
// CREATE IMAGE OBJECT
$img = imagecreatefromjpeg("cate.jpg");

// CROP AREA
$area = [
  // STARTING POSITON - 0,0 IS TOP LEFT CORNER
  "x" => 0, "y" => 0,
  // NUMBER OF PIXELS TO CROP
  "width" => 500, "height" => 300
];

// CROP IMAGE
$crop = imagecrop($img, $area);
 
// SAVE CROPPED IMAGE
imagejpeg($crop, "demo-A.jpg", 50);

// RECOMMENDED CLEANUP - DESTROY IMAGE OBJECTS
imagedestroy($img);
imagedestroy($crop);
?>

Here cate.jpg is an image we want to crop.