Announcement: V2 plans & fund raising
Please take a moment to read my plans for version 2 of the cropper and how you can support it.
Details
| Version | 1.2.0 |
|---|---|
| Last updated | 30th October 2006 |
| Requirements |
|
| Demo | View demo page |
| Links | |
| License | BSD License |
| Changelog |
|
About
The JavaScript image cropper UI allows the user to crop an image using an interface with the same features and styling as found in commercial image editing software, and is is based on the Prototype JavaScript framework and script.aculo.us.
Initially I performed quite a lot of searching for some ready made solutions to meet my requirements, but found none that had the complete feature set that I required or any complete versions based on Prototype.
So after a week and a half of work, I present the JavaScript image cropper UI, built on Prototype & script.aculo.us.
Features
![]()
- Un-obtrusive
- Based on Prototype and script.aculo.us
- Image editing package styling & functionality, the crop area functions and looks like those found in popular image editing software
- Dynamic inclusion of required styles
- Drag to draw areas
- Shift drag to draw/resize areas as squares
- Selection area can be moved
- Selection area can be resized using resize handles
- Allows dimension ratio limited crop areas
- Allows minimum dimension crop areas
- Allows maximum dimensions crop areas, if both min & max set as the same value then we'll get a fixed cropper size on the axes as appropriate and the resize handles will not be displayed as appropriate
- Allows dynamic preview of resultant crop (if minimum width & height are provided), this is implemented as a subclass so can be removed if not required
- Movement of selection area by arrow keys (shift + arrow key will move selection area by 10 pixels)
- All operations stay within bounds of image
- All functionality & display compatible with most popular browsers supported by Prototype, tested in:
- PC: IE 6 & 5.5, Firefox 1.5, Opera 8.5 (see known issues) & 9.0b
- MAC: Camino 1.0, Firefox 1.5, Safari 2.0
Usage
Extract to a directory of your choosing e.g. 'scripts/cropper/' and include the script and the required Prototype & script.aculo.us scripts:
-
<script type="text/javascript" src="scripts/cropper/lib/prototype.js" language="javascript"></script>
-
<script type="text/javascript" src="scripts/cropper/lib/scriptaculous.js?load=builder,dragdrop" language="javascript"></script>
-
<script type="text/javascript" src="scripts/cropper/cropper.js" language="javascript"></script>
Options
- ratioDim obj
- The pixel dimensions to apply as a restrictive ratio, with properties x & y.
- minWidth int
- The minimum width for the select area in pixels.
- minHeight int
- The mimimum height for the select area in pixels.
- maxWidth int
- The maximum width for the select areas in pixels (if both minWidth & maxWidth set to same the width of the cropper will be fixed)
- maxHeight int
- The maximum height for the select areas in pixels (if both minHeight & maxHeight set to same the height of the cropper will be fixed)
- displayOnInit int
- Whether to display the select area on initialisation, only used when providing minimum width & height or ratio.
- onEndCrop func
- The callback function to provide the crop details to on end of a crop.
- captureKeys boolean
- Whether to capture the keys for moving the select area, as these can cause some problems at the moment.
- onloadCoords obj
- A coordinates object with properties x1, y1, x2 & y2; for the coordinates of the select area to display onload
The callback function
The callback function is a function that allows you to capture the crop co-ordinates when the user finished a crop movement, it is passed two arguments:
- coords, obj, coordinates object with properties x1, y1, x2 & y2; for the coordinates of the select area.
- dimensions, obj, dimensions object with properities width & height; for the dimensions of the select area.
An example function which outputs the crop values to form fields:
-
function onEndCrop( coords, dimensions ) {
-
$( 'x1' ).value = coords.x1;
-
$( 'y1' ).value = coords.y1;
-
$( 'x2' ).value = coords.x2;
-
$( 'y2' ).value = coords.y2;
-
$( 'width' ).value = dimensions.width;
-
$( 'height' ).value = dimensions.height;
-
}
Basic interface
This basic example will attach the cropper UI to the test image and return crop results to the provided callback function.
Minimum dimensions
You can apply minimum dimensions to a single axis or both, this example applies minimum dimensions to both axis.
Select area ratio
You can apply a ratio to the selection area, this example applies a 4:3 ratio to the select area.
-
<img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
-
-
<script type="text/javascript" language="javascript">
-
Event.observe( window, 'load', function() {
-
new Cropper.Img(
-
'testImage',
-
{
-
ratioDim: {
-
x: 220,
-
y: 165
-
},
-
displayOnInit: true,
-
onEndCrop: onEndCrop
-
}
-
);
-
} );
-
</script>
With crop preview
You can display a dynamically produced preview of the resulting crop by using the ImgWithPreview subclass, a preview can only be displayed when we have a fixed size (set via minWidth & minHeight options). Note that the displayOnInit option is not required as this is the default behaviour when displaying a crop preview.
-
<img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
-
<div id="previewWrap"></div>
-
-
<script type="text/javascript" language="javascript">
-
Event.observe( window, 'load', function() {
-
new Cropper.ImgWithPreview(
-
'testImage',
-
{
-
previewWrap: 'previewWrap',
-
minWidth: 120,
-
minHeight: 120,
-
ratioDim: { x: 200, y: 120 },
-
onEndCrop: onEndCrop
-
}
-
);
-
} );
-
</script>
Known Issues
- Safari animated gifs, only one of each will animate, this seems to be a known Safari issue.
- After drawing an area and then clicking to start a new drag in IE 5.5 the rendered height appears as the last height until the user drags, this appears to be the related to another IE error (which has been fixed) where IE does not always redraw the select area properly.
- Lack of CSS opacity support in Opera before version 9 mean we disable those style rules, if Opera 8 support is important you & you want the overlay to work then you can use the Opera rules in the CSS to apply a black PNG with 50% alpha transparency to replicate the effect.
- Styling & borders on image, any CSS styling applied directly to the image itself (floats, borders, padding, margin, etc.) will cause problems with the cropper. The use of a wrapper element to apply these styles to is recommended.
- overflow: auto or overflow: scroll on parent will cause cropper to burst out of parent in IE and Opera when applied (maybe Mac browsers too) I'm not sure why yet.
Related Link: SEO Agency advanced JavaScript experience can enhance your site functionality. Adding the JavaScript Image Cropper is a good way to improve the user experience.
Next Steps
Feature Requests & Bug Reports
Please check the existing list of feature requests & bugs and the discussion list before posting requests or reporting bugs.
Leave a Tip
If you find this code useful you can leave a donation towards the continued development & support.
Announcement: V2 plans & fund raising
Please take a moment to read my plans for version 2 of the cropper and how you can support it.

Comments
There have been 508 comments so far, join the discussion.
Pages: « 26 … 13 12 11 10 9 [8] 7 6 5 4 3 … 1 » Show All
160. Stranger - 23rd Jan 2007 - 2:32 pm
Hi folks,
i changed my code but the croparea dosn’t change if i change the selectfield! Can someone check my syntax, please?
var CropImageManager = {
curCrop: null,
init: function() {
this.attachCropper2();
},
onChange: function( e ) {
this.attachCropper2( e );
},
attachCropper2: function( r ) {
if( this.curCrop null ) {
if( r “200×200fixed” ) {
this.curCrop = new Cropper.Img( ‘testImage’, { ratioDim: { x: 220, y: 200 }, minWidth: 220, minHeight: 200, maxWidth: 220, maxHeight: 200, displayOnInit: true, onEndCrop: onEndCrop } );
} else if( r "200x200" ) {
this.curCrop = new Cropper.Img( 'testImage', { ratioDim: { x: 220, y: 200 }, minWidth: 220, minHeight: 200, displayOnInit: true, onEndCrop: onEndCrop } );
} else if( r “4:3” ) {
this.curCrop = new Cropper.Img( ‘testImage’, { ratioDim: { x: 220, y: 165 }, displayOnInit: true, onEndCrop: onEndCrop } );
} else if( r == “16:9” ) {
this.curCrop = new Cropper.Img( ‘testImage’, { ratioDim: { x: 220, y: 124 }, displayOnInit: true, onEndCrop: onEndCrop } );
} else {
this.curCrop = new Cropper.Img( ‘testImage’, { displayOnInit: true, onEndCrop: onEndCrop, onloadCoords: { x1: 10, y1: 10, x2: 250, y2: 100 } } );
}
} else {
this.curCrop.reset();
}
}
};
function onEndCrop( coords, dimensions ) {
$( ‘x1’ ).value = coords.x1;
$( ‘y1’ ).value = coords.y1;
$( ‘x2’ ).value = coords.x2;
$( ‘y2’ ).value = coords.y2;
$( ‘width’ ).value = dimensions.width;
$( ‘height’ ).value = dimensions.height;
}
Event.observe( window, ‘load’, function() {
CropImageManager.init();
Event.observe( $(‘typ’), ‘change’, CropImageManager.onChange.bindAsEventListener( CropImageManager ), true );
} );
The selectfield has the id=typ name=typ!
159. Sangeetha S - 23rd Jan 2007 - 12:09 pm
The programs are very excellent.
I want to know abt moving the arrow keys over the image,in several .js files,in which file the movement of arrow keys have been mentioned.Thanks in advance.
158. Stranger - 23rd Jan 2007 - 9:05 am
Hi,
i found some cropper butthis one is great. I write some code to change the area dynamicaly via selectbox. If i select 200×200 (ratio) the croparea displayed on the image. If i select a second one (4:3), the new croparea displayed over the old one and the image goes darker.
How i can remove the old croparea?
here is some code ([ = ):
function onEndCrop( coords, dimensions ) {
$( ‘x1’ ).value = coords.x1;
$( ‘y1’ ).value = coords.y1;
$( ‘x2’ ).value = coords.x2;
$( ‘y2’ ).value = coords.y2;
$( ‘width’ ).value = dimensions.width;
$( ‘height’ ).value = dimensions.height;
}
function loadExample( type ) {
switch( type ) {
case( ‘200×200’ ) :
new Cropper.Img( ‘testImage’, { ratioDim: { x: 220, y: 200 }, minWidth: 220, minHeight: 200, displayOnInit: true, onEndCrop: onEndCrop } );
break;
case( ‘4:3’ ) :
new Cropper.Img( ‘testImage’, { ratioDim: { x: 220, y: 165 }, displayOnInit: true, onEndCrop: onEndCrop } );
break;
case( ‘basic’ ) :
default :
new Cropper.Img( ‘testImage’, { displayOnInit: true, onEndCrop: onEndCrop, onloadCoords: { x1: 10, y1: 10, x2: 250, y2: 100 } } );
}
}
[form action=”test.php” enctype=”multipart/form-data” method=”post” name=”form”][img src=”castle.jpg” alt=”testImage” id=”testImage” width=”800” height=”600”]
[input type=”hidden” name=”x1” id=”x1”]
[input type=”hidden” name=”y1” id=”y1”]
[input type=”hidden” name=”x2” id=”x2”]
[input type=”hidden” name=”y2” id=”y2”]
[input type=”hidden” name=”width” id=”width”]
[input type=”hidden” name=”height” id=”height”]
[select id=”type” name=”type” onchange=”loadExample( this.options[this.selectedIndex].value )”]
[option value=”—-” selected=”selected”]please select an ratio[/option]
[/select]
[input type=”submit” name=”submit” value=”cut it!”]
[/form]
157. Pete Frueh - 19th Jan 2007 - 6:03 pm
Like you, I couldn’t find a browser-based image editor when I needed one, so I ended up creating my own (http://www.ajaxprogrammer.com/?p=9).
I can’t wait to take a peek at your code :-)
Cheers,
Pete Frueh
156. fialik - 18th Jan 2007 - 12:03 pm
I solved the problem, in my case. I had another div layer with a oppacity of 40% (IE filter:alpha(opacity=40)). Before I created the croper object, I changed the class of this div to a class with no oppacity. I think that the IE then set the global alpha filter value back to 100 and so all other, already loaded, style settings are been overwritten. I now created a overlay div with an opacity of 40%, but I only switch the whole visibility value between “visible” and “hidden”. Ik works fine in IE6, IE7 and Firefox2 now.
155. fialik - 18th Jan 2007 - 11:14 am
I have the nearly the same problem as byarke and brian. If I directly call the cropper contstructor to create a cropper object, everything is working fine. Also in IE7. But if I set the constructor in a JavaScript-method and execute this method, the image is gettig white. It is also possible to crop a part out of the image, because alle the coordinates are working fine, but it’s a kind of difficult to crop out something of an image you can not see :)
154. Bryan - 10th Jan 2007 - 9:17 pm
Same problem as bjarke. Had it since 1.1. Works in FF, but not in IE6/7. The image loads, and then the cropper makes the image all white (like a non-transparent overlay). You can create a grey crop box.
153. bjarke - 10th Jan 2007 - 9:23 am
The problem only occurs in IE 7. In Firefox there is no problem! The flow is as follows:
I execute the LoadCropper-function, and the cropper works fine. I execute the LoadCropper-function again and picture goes all white. If I click inside the white area where the picture should be, it turns grey.
The Code:
var CropObject = null;
function LoadCropper()
{
if( CropObject == null )
{
CropObject = new Cropper.Img( ‘target-img’, { onEndCrop: onEndCrop } );
}
else
{
CropObject.remove();
CropObject = null;
CropObject = new Cropper.Img( ‘target-img’, { onEndCrop: onEndCrop } );
}
}
I hope this helps.
Best regards Bjarke
152. Dave - 9th Jan 2007 - 3:01 pm
bjarke:
The remove() method is the correct one to use, I’m guessing this could be a new bug, possibly a browser related issue. Does your example work in any browser? If you could provide some more information and possibly an example then I will be able to explore this further.
151. bjarke - 9th Jan 2007 - 2:40 pm
Hi Dave.
I use the remove() function. Is it not the one to use?
150. bjarke - 9th Jan 2007 - 2:37 pm
When I try to remove a cropper attached to a picture, and then attach a new cropper to the same picture, it looks funny. You can’t se the picture, only a grey box where the picture should be.
Everything else works as a charm :)
what to do??
149. Dave - 9th Jan 2007 - 2:21 pm
bjarke:
Since then the API has been updated to add a couple of new methods to allow this and you should use those.
148. bjarke - 9th Jan 2007 - 2:18 pm
“31st May 2006 – 7:28 pm” you wrote:
“It is possible to apply a new cropper to a new image (or the same image but replaced) but there are a couple of errors that are related to the fact that the HTML that was added to the DOM for the cropper isn’t been removed.”
When I try to remove a cropper, and attach a new cropper to a new picture, it looks strange. What can I do?
Please help.
147. Adam B - 8th Jan 2007 - 8:25 pm
here’s the PHP code, someone posted some half working code that distorted the images
this uses the castle demo image but will work with jpg or PNG.
$x1 = $_POST[‘x1’];
$y1 = $_POST[‘y1’];
$x2 = $_POST[‘x2’];
$y2 = $_POST[‘y2’];
$width = $_POST[‘width’];
$height = $_POST[‘height’];
//this must be the same as our basic aspect ratio used on the javascript, modify the js and this to make that dynamic.
$thumb_width = 200;
$thumb_height = 120;
// define image filename
$image_filename = “jscripts/cropper/tests/castle.jpg”;
// find out original width / height
list($ow, $oh) = getimagesize($image_filename);
// setup orig photo
$big = imagecreatefromjpeg($image_filename);
// setup cropped photo
$thumb = imagecreatetruecolor($thumb_width,$thumb_height);
imagecopyresampled($thumb, $big, 0, 0, $x1, $y1, 200, 120, $width, $height);
$imgname = “test1a.jpg”;
// save image to disk
imagejpeg($thumb, ’../photo_album/’.$imgname,100);
// free up resources
imagedestroy($big);
imagedestroy($thumb);
(repost. apaprently the comment system doesn’t like PHP code…)
146. Adam B - 8th Jan 2007 - 8:23 pm
here’s the PHP code, someone posted some half working code that distorted the images
this uses the castle demo image but will work with jpg or PNG.
cheers
-Adam
145. Dave - 31st Dec 2006 - 3:31 pm
djkaat:
That would be a custom piece of functionality, I’m pretty sure it would be fairly easy to fix the crop area to the centre of the image – but it’s not something I’m currently thinking of adding as a main feature.
Mikkel:
There are two public methods available via the API named remove() and reset() which remove or reset the cropper, note however the ImgWithPreview class does not implement these methods at the moment.
144. Mikkel - 30th Dec 2006 - 3:19 pm
Hi
Great script, but how do you reset/remove the crop tool?
What function should i call when i use a button onclick=”” ?
Best regards, Mikkel
143. djkaat - 21st Dec 2006 - 3:24 pm
Hi
Very nice cropper.
Is there a way I can make the crop area resize keeping the center of the area the same as the center of the image?
Thanks
142. pablitobs - 19th Dec 2006 - 10:41 am
for those who beside jpg also use PNG or gif this a modified version of some code posted here, this version overrides the original picture.
function CropImage($originalImage, $sizes, $imagetype) {
switch ( $imagetype) {
case “image/gif”:
$src = imageCreateFromGIF($originalImage);
break;
case “image/pjpeg” :
case “image/jpeg” :
$src = imageCreateFromJPEG($originalImage);
break;
case “image/x-PNG”:
case “image/png”:
$src = imageCreateFromPNG($originalImage);
break;
}
$newPath = $originalImage;
$thumbImage = imagecreatetruecolor($sizes[‘width’], $sizes[‘height’]); // create thumbnail image
@unlink($imagePath); // unlink destination image if possible
// perform crop (modified from code posted here, eg. this one doesn’t stretch the image)
imagecopyresampled($thumbImage, $src, 0, 0, $sizes[‘x1’], $sizes[‘y1’], $sizes[‘width’], $sizes[‘height’], $sizes[‘x2’]- $sizes[‘x1’], $sizes[‘y2’]- $sizes[‘y1’]);
imagedestroy($src); // destroy image resource
unlink($newPath);
if($imagetype "image/jpeg" || $imagetype “image/pjpeg”){
imagejpeg($thumbImage,$newPath,100);
}
if($imagetype "image/gif"){
imagegif($thumbImage,$newPath);
}
if($imagetype “image/png” || $imagetype == “image/x-PNG”){
imagepng($thumbImage,$newPath);
}
imagedestroy($thumbImage); // destroy thumbnail resource
}
141. Rainer Schleevoigt - 15th Dec 2006 - 7:52 pm
Excellent!
here is my realisation in combination with ‘convert -crop’ from Imagemagick.
http://familientagebuch.de/rainer/2006/50.html#5
I looking for a solution to generate USEMAPS.
Rainer
Leave a comment
No HTML please, only textile. For code please use [lang]...[/lang] tags (e.g. [html]...[/html] for HTML)