Monday, November 24, 2014

Learn How to Crop an Image in PHP – First Part

With newly PHP 5.5.0 two functions, image cropauto and imagecrop, have been added for latest image resizing. Here, You will get a detail about imagecropauto function.

This function is helpful to remove borders as well as background area of a photo. The mode parameter explains the border to be removed. For e.g :- IMG_CROP_BLACK will remove black borders. IMG_CROP_WHITE will remove white borders, etc.

To remove, multi-colored borders, we need to use the IMG_CROP_THRESHOLD mode, It is little hard but definitely, help in PHP Application Development.

How to Crop Image in PHP

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);

10746029 decimal is equivalent to A3F8AD Hex in the above code – the outermost light green color in the below the test image.

Find an original image in the left and cropped image in the right.

Original and Cropped Image

Click Here to find the second part of this tutorial..

0 comments:

Post a Comment