Monday, November 24, 2014

How to Crop an Image in PHP – Second Part

Now It's time to go further. Here, You will find a second part of Image cropping. Click Here to refer first part of that.

In this tutorial, I will describe the function imagecrop which is introduced in PHP 5.5.0 for cropping images. Imagecrop can be used to cut an image based on a initial and end point, including dimensions. It is easy and simple to apply.

Syntax :-

$resource imagecrop ( resource $image , array $rect )

Parameters :-

$image
resource returned by any create image function like imagecreatefromjpeg or imagecreatetruecolor etc.

$rect
This will be an array that will hold the x, y co-ordinate and the dimensions. This will define the rectangular area of the image that will be kept.
The array keys must be “x”, “y”, “width” and “height”.

For example in the below image the light green border needs to be removed, so the rect will be array(“x”=>27, “y”=>26, “width”=>163, “height”=>142) (the values might not be pixel perfect – it is just for demonstration)

Example Code :-
....
$image_src = imagecreatefrompng($_FILES['image']['tmp_name']);

$croppedImage = imagecrop($image_src,array("x"=>27,"y"=>26,"width"=>163,"height"=>142));

header( 'Content-Type: image/png');

imagepng($croppedImage);

Below, Find out the original image and cropped image..

Crop an Image in PHP

0 comments:

Post a Comment