Jcrop Implementation Theory


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:

  • Upload or select an image to crop
  • Display page with cropping interface
  • Capture selected coordinates as form values
  • On form submission, server performs image crop
  • Resultant image is saved, replaced, updated, displayed, etc

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

Example Code

This example form builds on the file tutorial2.html with the following modifications:

Changed text inputs to hidden inputs
Since we're using hidden inputs, we've also removed the onChange handler. This helps the performance but it would also be silly to use it, since there is no benefit to constantly writing the values, if it causes no visible behavior.
Added option aspectRatio: 1 
For simplicity, our demo will output a 150x150 square image directly to the browser. For this reason, we add a 1/1 (equals 1) aspectRatio setting to the Jcrop widget so that the selected area is not distorted when the server script crops it.
Form tag points to our new script
The action value links to the PHP script below.

Simple cropping code for PHP (requires the gd extension)


$targ_w = $targ_h = 150;
$jpeg_quality = 90;

$src = 'demo_files/flowers.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_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.