How to crop an image automatically using imagecropauto() function in PHP?

PHPServer Side ProgrammingProgramming

imagecropauto() is an inbuilt function in PHP that is used to crop an image automatically using one of the available modes.

Syntax

resource imagecropauto(resource $image, int $mode, float $threshold, int $color)

Parameters

imagecropauto() takes four different parameters − $image, $mode, $threshold and $color.

  • $image − Specifies the image resource to be cropped.

  • $mode − It is an optional parameter and it is used to specify an integer corresponding to a crop mode, below is the list of crop modes.

    • IMG_CROP_DEFAULT − The IMG_CROP_DEFAULT works just like the IMG_CROP_TRANSPARENT mode.

    • IMG_CROP_TRANSPARENT − This mode is used to crop out a transparent background.

    • IMG_CROP_BLACK − This mode is used to crop out a black background.

    • IMG_CROP_WHITE − This mode is used to crop out a white background.

    • IMG_CROP_SIDES − This mode uses the four corners of the image to attempt to detect the background to crop.

    • IMG_CROP_THRESHOLD − This mode is used to crop an image using the given threshold and color.

  • $threshold − Optional parameter, it is used to specify the tolerance in percent to be used while comparing the image color and the color to crop.

  • $color − Optional parameter, it is used to specify either an RGB (Red, Green, and Blue) color value or a palette index.

Return Values

imagecropauto() returns a cropped image resource on success or false on failure. The imagecrop() function returns false if the complete image is the crop.

Example 1

<?php
   // Load the png image from the local drive folder
   $img = imagecreatefromjpeg('C:\xampp\htdocs\Images\img33.jpg');

   // Crop the extra white area of an image
   $cropped = imagecropauto($img,IMG_CROP_WHITE);

   // Convert it to a gif file
   header('Content-type: image/gif');
   imagepng($cropped);
?>

Output

Image with white side area before using the IMG_CROP_WHITE mode parameter.

Crop white color area from the side after using IMG_CROP_WHITE mode of the parameter.

Note − We can use the different given modes of parameters to crop an image. For example, we can use IMG_CROP_BLACK, which will crop the black part of the image.

raja
Published on 09-Aug-2021 10:09:15
Advertisements