PHP | imagecropauto() Function

The imagecropauto() function is an inbuilt function in PHP which 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: This function accepts four parameters as mentioned above and described below:

  • $image: It specifies the image resource to be cropped.
  • $mode (Optional): It specifies an integer corresponding to a crop mode.

    List of CROP modes are given below:

    • IMG_CROP_DEFAULT (0)
    • IMG_CROP_TRANSPARENT (1)
    • IMG_CROP_BLACK (2)
    • IMG_CROP_WHITE (3)
    • IMG_CROP_SIDES (4)
    • IMG_CROP_THRESHOLD (5)
  • $threshold (Optional): It specifies the tolerance in percent to be used while comparing the image color and the color to crop.
  • $color (Optional): It specifies either an RGB color value or a palette index.

Return Value: This function returns TRUE on success.

Exceptions: This function throws Exception on error.

Below given programs illustrate the imagecropauto() function in PHP:

Program 1:




<?php
  
// Load the png image
$im = imagecreatefrompng(
'https://media.w3wiki.net/wp-content/uploads/w3wiki-13.png');
   
// Crop the extra white area
$cropped = imagecropauto($im, IMG_CROP_WHITE);
  
// Convert it to a png file
header('Content-type: image/png');  
imagepng($cropped);
?>


Output:

Program 2:




<?php
  
// Load the png image
$im = imagecreatefrompng(
'https://media.w3wiki.net/wp-content/uploads/20200123135210/w3wikiinverted.png');
   
// Crop the image
$cropped = imagecropauto($im, IMG_CROP_BLACK);
  
// Convert it to a png file
header('Content-type: image/png');  
imagepng($cropped);
?>


Output:

Reference: https://www.php.net/manual/en/function.imagecropauto.php



Contact Us