Tag Archives: imagecrop php

Image Cropping in PHP – Part 2

Here is the second part of the article “Image Cropping in PHP”. The first part is here

This part describes the function imagecrop introduced in PHP 5.5.0 for cropping images. imagecrop can be used to crop an image based on a start and end point/co-ordinate and dimensions. (It doesn’t take into account any color like imagecropauto )
It is a relatively simpler and easier to use.

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

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 left is the original image and right is the cropped image (using the above example).

Untitled2

final2