
Jcrop Home • Download • Manual • Examples
Jcrop creates an interface to crop an image. However, actually creating a new, cropped image file is obviously beyond the scope of a client-side plugin. It may also be the most challenging part of implementing such a process in your web application (now that you've found Jcrop).
This article covers the server-side process in theory, and provides some PHP example code.
A typical workflow for cropping functionality in a web application looks like this:
If you've read the manual and looked at the example code, you already know how to integrate the selection values into form fields. (For a quick refresher, study the source here.)
This example form builds on the file tutorial2.html with the following modifications:
Simple cropping code for PHP (requires the gd extension)
<?php
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'demo_files/flowers.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r, null, $jpeg_quality);
?>
Here we've loaded the source image, and created a true color working space to copy the cropped image into. The imagecopyresampled() function does most of the work (this is where we plug in the values from Jcrop).
To write the file instead of display it, change the last two lines like this:
// Comment out the header() call
// header('Content-type: image/jpeg');
imagejpeg($dst_r, $output_filename, $jpeg_quality);
See this example in action here
See Also: Image Processing in PHP (using gd)
Obviously this script has some limitations. First of all, it only works with jpeg images, while the gd library functions support many common file formats. For now, improvements are left as an exercise to the reader. However, if you're still following along, congratulations! You're well on your way to implementing image cropping into your web application.