Mark Setchell's answer does not work on older Apple systems such as Snow Leopard and Lion, where you will receive this error:
Fatal error: Call to undefined function imagecrop() in Command line code on line 1
To check the version of your PHP installion run php -v
:
PHP 5.3.15 with Suhosin-Patch (cli) (built: Jul 31 2012 14:49:18)
My Lion machine has PHP 5.3.15 and its in-built GD (GIF/Graphics Draw) library does not have the imagecrop
function, which is only available with PHP 5.5.0 or greater. I have thus used the imagecopy()
function in place of imagecrop()
.
This solution should work with Linux and Unix machines that have the inbuilt PHP interpreter and GD library.
The key line in my image cropping PHP script is:
imagecopy($dest_image,$src_image,0,0,$new_x,$new_y,$new_width,$new_height);
Pass in the parameters of the cropping task to the script, where (x,y) is the starting point of the cropping rectangle:
php -f ./crop_image.php $infile $outfile $x $y $width $height
Example: Search for all files with the "png" extension in the current directory, crop each image from the top-left point (10,50) to the bottom-right point (730,1030) and then save all output files in the "cropped" folder.
j=1; for i in $(ls *.png); do php crop_image.php $i ./cropped/$j.png 10 50 720 980; ((j++)); done