With PHP 5.5.0 two functions, imagecropauto and imagecrop, have been added for advanced image resizing. This article describes the imagecropauto function.
The imagecropauto function is useful to remove borders or background/outer area of a photo. The mode parameter defines the border to be removed e.g. IMG_CROP_BLACK will remove black borders, IMG_CROP_WHITE will remove white borders etc.
Multicolored borders can be also be removed using the IMG_CROP_THRESHOLD mode, though it will be a bit tricky — couldn’t yet find a calculator to calculate the value of threshold.
Syntax:
resource imagecropauto ( resource $image [, int $mode = -1 [, float $threshold = .5 [, int $color = -1 ]]] )
Parameters:
$image
resource returned by any create image function like imagecreatefromjpeg or imagecreatetruecolor etc.
$modes
IMG_CROP_TRANSPARENT / IMG_CROP_BLACK / IMG_CROP_WHITE / IMG_CROP_SIDES / IMG_CROP_THRESHOLD / IMG_CROP_DEFAULT
$threshold
Applicable if IMG_CROP_THRESHOLD is used in mode. The value is based on the color distance in the RGB cube model.
$color
This code can be derived by converting the HEX value (of a color) to decimal value.
Example Code:
.... $image_src = imagecreatefrompng($_FILES['image']['tmp_name']); $croppedImage = imagecropauto($image_src,IMG_CROP_THRESHOLD,27.8,10746029); header( 'Content-Type: image/png'); imagepng($croppedImage);
In the above code 10746029 decimal is equivalent to A3F8AD Hex – the outermost light green color in the below test image.
Below left is the original image and right is the cropped image (using the above example).
Here is the second part of this article.