Details
| Version | 1.2.1 |
|---|---|
| Last updated | 6th October 2009 |
| 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=effects,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.
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.
Comments
There have been 699 comments so far, join the discussion.
Pages: « 1 … 4 5 6 7 8 9 [10] 11 12 13 14 » Show All
451. Jimmy - 18th Mar 2008 - 5:05 pm
Also, the problem with using the CropImageManager object is that I also need to pass different “onloadCoords” and “ratioDim” values each time as well as the different imageID.
452. Dave - 18th Mar 2008 - 5:08 pm
Jimmy:
To me it sounds as though customizing the dynamic image example would be easiest, I’ve emailed you directly so we don’t fill up the comments discussing this.
453. prabhat singh - 19th Mar 2008 - 6:45 pm
Hi
I want to pass COORDS to asp.net to crop an image.
Please suggest for how to do it.
prabhat {at) gmail (dot} com
454. Jonny Muir - 20th Mar 2008 - 3:43 pm
To Sune Kjaergaard (regarding post – 1st Sep 2006).
Apologies if this has already been answered, there are lots of posts in this thread!
I recently came across the cropper transparency not working correct in ie6 when it was placed in a table (making it look like the image dissapears). I have found a fix as follows:
In cropper.cs
Remove the addition of the click area in the onLoad function.
i.e. the line:
this.dragArea.appendChild( Builder.node( ‘div’, { ‘class’: cNamePrefix + ‘clickArea’ } ) );
Then add it back after the imgWrap has been resized in the setParams functions:
i.e.
$( this.imgWrap ).setStyle( { ‘width’: this.imgW + ‘px’, ‘height’: this.imgH + ‘px’} ); // Existing line – set the size
var cNamePrefix = ‘imgCrop_’; // new inserted line
this.dragArea.appendChild( Builder.node( ‘div’, { ‘class’: cNamePrefix + ‘clickArea’ } )); // new inserted line
I can only assume this is a bug with ie6 as there is no reason why it shouldn’t work the original way.
455. Akhil Bansal - 26th Mar 2008 - 8:43 am
Hi,
This is really a good lib. I gave this a try. I found a problem which is because of line 507 which says:
Event.observe( document, ‘mouseup’, this.endCropBind );
Due to this callback function called each mouseup event, no matter where it occurred. Means click any portion of page this callback will be execute.
Instead you can replace this line with:
Event.observe( this.imgWrap, ‘mouseup’, this.endCropBind );
It works fine for me.
Akhil
456. Dave - 26th Mar 2008 - 10:05 am
Akhil:
The endCrop is meant to be called on any mouse up event as this is the only way to ensure that a user can select right to the very edge of the image without them having to hold their mouse over the very last pixel while letting go of the mouse.
I think your problem is that it is actually calling your callback every time the mouse is clicked, that’s the bug that needs fixing (it should really only fire your custom callback if we are currently drawing/changing the cropper), I’ve added this as a bug.
457. Daniels - 27th Mar 2008 - 7:54 pm
From POST 130.
DJ, just put form tags around those input fields from the cropper and put a submit button so that you can send them to the PHP page. After you get that working you can set them to hidden or whatever…
Sorry my ignorance, coul you be more specific please? How to put form tags on those vars. Thank you
458. Daniels - 28th Mar 2008 - 1:07 pm
I didn’t know that was enough to send the x1 data. I was asking for the input value.
459. Daniels - 28th Mar 2008 - 1:13 pm
If you want to crop and resize from image.jpg to obtain a 70px X 30pxthumb in php:
$tt1=”path_to_image/image.jpg”;
$tt2=”path_to_image/image70X30.jpg”;
$tama = getimagesize($tt1);
$wi = $tama0 ;
$he = $tama1 ;
$image_p = imagecreatetruecolor(70, 30);
$image = imagecreatefromjpeg($tt1);
imagecopyresized ( $image_p , $image , 0 , 0, $_POST[‘x1’] , $_POST[‘y1’] , 70, 30 , $wi , $he );
imagejpeg($image_p, $tt2);
imagedestroy($image_p);
imagedestroy($image);
460. Gökhan PUR - 29th Mar 2008 - 10:20 pm
thnx
461. Jonathan - 1st Apr 2008 - 1:19 pm
Absolutely fantastic code!! Will definitely be donating.
In reply to 454. Jonny Muir post – I get the same bug but the fix almost does it … just the mouse pointer and resize handles don’t match up.
Also it would be great for extra paramaters for the width/height of the preview window instead of min width/height as I may want to crop smaller than that but still have the preview window a certain size.
Thanks again!
Jonathan
462. ram - 2nd Apr 2008 - 1:50 pm
how can I save crop image?
463. TheIceman5 - 2nd Apr 2008 - 8:17 pm
@ram,
Your answer, SEARCH!!!!!! been answered here before.
464. Dave - 2nd Apr 2008 - 10:54 pm
All:
For all those who are subscribed to these comments I have just made some improvements to how I plan to maintain this code (this is part of the V2 phase) this evening they are as follows:
1. Setup a Google Code Project (http://code.google.com/p/javascript-image-cropper-ui/) to hold the issues (and allow reporting of issues) and to hold the documentation (which I’ve started off with an FAQ http://code.google.com/p/javascript-image-cropper-ui/wiki/FAQs).
2. Setup a Google Group for discussion of the project, this will allow new and current users to get help and find answers to previously asked questions etc. in a much better way than having things added to the comments.
The comments will remain open for general comments but I hope any future questions/improvement ideas/bugs/feature requests etc. come through via the group or the issues list on the Google Code project.
Hope this helps everyone a little bit.
-D
465. aaron - 7th Apr 2008 - 2:23 pm
How do I displayoninit without having the ratio defined? I need to do this because alot of the users don’t understand that they need to click on the picture to begin cropping so it will be better if i can specify a startcoords on the picture and then immediately load the overlay when the page finishes loading. It will be much easier if the user enters the page and then sees the handlers and he will understand he can just drag and then crop.
466. John - 11th Apr 2008 - 2:48 pm
This looks so great. I need it to run with multiple images, though.
The code that Dave Schlaegel posted is incomplete, unfortunately.
It is missing the initialization of the individual Cropper.img objects.
new Cropper.Img(
‘testImage’,
{
ratioDim: { x: 220, y: 124 },
displayOnInit: true,
//onEndCrop: onEndCrop
}
)
How can I adjust this code to show the cropper on multiple images?
I don’t know how to write that.
467. John - 11th Apr 2008 - 6:00 pm
Okay, so I found out that I can just repeat the quoted code and all the images get a cropping overlay.
So how do I need to adjust the x1 / x2 and y1 / y2 values in the script and the HTML, so that I can thumb multiple images?
468. Dave - 11th Apr 2008 - 6:07 pm
John:
Just give the onEndCrop a different callback for each of your images, then they can set different hidden form fields for each of your images.
469. Jimmy - 11th Apr 2008 - 6:12 pm
John:
I modified the onEndCrop (handler?) in “cropper.js” to return the imageID that the particular cropper instance is referring to as the first thing returned… look for the line with:
“this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});”
and change it to:
“this.options.onEndCrop(this.img.id,this.areaCoords,{width:this.calcW(),height:this.calcH()});”
So, when your crop ends, you know the image that the returned x1/x2/etc refers to.
With Dave’s help, I also have a “manager” to keep track of which items are being cropped: http://pastie.org/179269
Then, to add/remove croppers at will, its something like:
CropImageManager.attachCropper(theImageID,{ratioDim: {x: myX,y: myY}, onloadCoords:{x1:theX1,y1:theY1,x2:theX2,y2:theY2},displayOnInit:true, onEndCrop:onEndCrop});
Hope that helps!
470. John - 12th Apr 2008 - 8:09 pm
Jimmy:
When I add the img.id to the line in the cropper.js, the image cropper behaves strangely. The cropping area jumps to the border of the image when you try to increase the cropping area.
Also, just duplicating the “new Cropper.img { ... }” functions to have multiple cropping areas does not work in Internet Explorer. (I am using Opera)
471. Dave - 13th Apr 2008 - 9:52 am
John/Jimmy:
Could you please move this discussion regarding multiple croppers to the Google group as I’d like these kind of discussions to be held there from now on (with the aim of being easier for others to find answers on topics in the future—rather than searching through 100’s of disjointed comments). I’ve taken the liberty of setting up a thread within the group for this discussion and copied your relevant comments to get the thread started. Hope you don’t mind this request.
472. Don R - 16th Apr 2008 - 6:58 pm
Hi,
I am using the latest version of scriptaculous/Prototype (v1.8.1). Does Cropper work with the latest version?
(I apologize if the question has already been answered before. I was unable to search the full comments list).
thanks much.
Don.
473. TheIceman5 - 16th Apr 2008 - 10:35 pm
@Don R
Yes it has been asnwered before, search the entire list, i dont see why u cant, just hit Ctrl + F and it brings up a search box once the entire listing is bought up, thats what i do.
474. kacior - 22nd Apr 2008 - 10:19 pm
As it seems no one has posted a visible solution to the problem with the onEndCrop function always beeing called when mouse is clicked somewhere, I checked it myself. The solution is very simple, it’s just to change “document” to “this.dragArea” on line 116 and 118 in the compressed file, so it becomes:
116: Event.observe(this.dragArea,”mousemove”,this.onDragBind);
118: Event.observe(this.dragArea,”mouseup”,this.endCropBind);
instead of:
116: Event.observe(document,”mousemove”,this.onDragBind);
118: Event.observe(document,”mouseup”,this.endCropBind);
475. Dave - 22nd Apr 2008 - 10:53 pm
kacior:
Thanks for your solution and adding it to the issue on the Google code page, but for the reasons that I’ve mentioned in my comment on the issue I don’t think the solution is that, but only adding the onEndCrop listener when manipulating the crop area.
476. gatto - 23rd Apr 2008 - 12:45 am
kacior:
I disabled that in my implementation. See here:
http://gattomatto.net/work/jsCropperUI/
download the source here:
http://gattomatto.net/work/jsCropperUI.zip
var CropImageManager = {
curCrop: null,
init: function() {
this.attachCropper();
},
attachCropper: function() {
if (this.curCrop == null) {
this.curCrop = new Cropper.ImgWithPreview(
‘event_image’,
{
onEndCrop: onEndCrop,
(all the other args u choose)
}
);
}
else {
this.curCrop.reset();
}
}
};
// the cropper calls this function on the end of each resize or move
function onEndCrop( coords, dimensions ) {
$(‘cropForm’)[‘x1’].value = coords.x1;
$(‘cropForm’)[‘x2’].value = coords.x2;
$(‘cropForm’)[‘y1’].value = coords.y1;
$(‘cropForm’)[‘y2’].value = coords.y2;
}
function loadCropper() {
CropImageManager.init();
}
Event.observe( window, ‘load’, function() { loadCropper(); } );
477. gatto - 23rd Apr 2008 - 12:48 am
by the way you don’t have to save the coordinates like i’m doing. i do that to post to a PHP script which crops the image. you could just have an empty function which does nothing…
478. Corey - 27th Apr 2008 - 2:25 am
Awesome job on the cropper i love it!
I have a slight problem that popped up and searched some of the results but didn’t see a solution to it.
I have the script working on a page perfectly if i go directly to that page, but if i load that page via AJAX then I get 3 errors and it blanks the entire page.
var CropDraggable=Class.create();” – cropper.js
var Draggable = Class.create(); -dragdrop.js
Thanks again!
-Corey
479. Killer Bunny - 13th May 2008 - 11:17 am
I think i solved the table problem:
if you place the image in a div with a absolute height, it works.
So what you do is as follow:
480. shakeeb khan - 28th May 2008 - 4:28 pm
Well, i have read all the comments but my question is can i upload an image with one size and instead of cropping image on server side while uploading the images can i will be able to do upload original size of my image and display in different size like image gallery usually shows on the client side because recently i am facing problems while uploading images and then crop them on server side so it make server slow and if we talking about millions of people uploading bunch of file so server will kneel down can any body suggest me best possible approach i will be thank full to him
thank you all in advance :)
481. Dave - 28th May 2008 - 4:34 pm
Shakeeb:
I don’t quite understand your requirements, but it sounds like you want to change the point the image is uploaded? Can you clarify your requirements by giving a list of steps a user would take in your ideal setup e.g. normally it would be:
482. shakeeb - 29th May 2008 - 4:48 am
No,my scenario is different like
1.user upload images
2.server crop it and make a multiple copies in different sizes.
3.Then it will be shifted to amazon S3.
Now,i have a question which is , my server will be slow when dozens of people upload images so idea is can i able to upload images like normal and cropping process is done by client side by this Js library or any other way out so let me know like how facebook and orkut allow people to upload images on server and they do image processing and then display a photo gallery of users.same thing i want to implement at my site .Kindly advise me because now i am stuck at this stage
:) and thanks for your interest
483. Dave - 29th May 2008 - 12:47 pm
Shakeeb:
In my opinion doing the cropping client side (which would only be possible with Flash) and then uploading multiple sizes of an image would result in more traffic to your server (as you’re uploading more images) than one upload and then resize on the server.
If you truly have a user base which you expect to be uploading enough images to bring your server to it’s knees (and you’re using S3 already) why not look at dedicated EC2 instance(s) to handle your image uploading/resizing transfer to S3 etc.
484. shakeeb - 29th May 2008 - 1:39 pm
yes that i was thinking about but what you suggest how orkut,facebook application handles this kind of probleam are they having their own dedicated server for image processing or they are using EC2 service what you think because i have to justify these things to my CEO you know what i mean :)
485. Dave - 29th May 2008 - 1:43 pm
Shakeeb:
EC2 is probably the most cost effective solution, as far as I know (last I read anyway) Facebook has around 500 servers (following a similar model to Google). Hardware is cheap, but also expensive at these levels, you’ll just have to do some calculations on what EC2 would cost vs a dedicated server (or more depending on your projected traffic levels).
486. Russ - 17th Jun 2008 - 10:00 pm
Is there a way or does anyone have sample code on how to set the crop x, y, width and height from form fields in the cropperUI script? The onEndCrop() routine works great to update form fields. I want to go the other way and set the crop from entries in the form fields if possible.
487. dave - 20th Jun 2008 - 9:44 pm
how do you see the final cropped image and save it ?
please excuse my lack programing skill
488. Dave - 21st Jun 2008 - 3:33 pm
Dave:
See the FAQ’s, they are linked to in information section at the top of the page.
489. freak - 26th Jun 2008 - 2:31 pm
this is a great tool dave..but i’ve encountered a problem.
like westy, my cropper is returned from an ajax call so i also used new Cropper.ImgWithPreview(...) instead of calling it on load. it works fine in firefox but never in safari. i tried putting it inside a function but still it does not work. could you please help me? thank you
freak
490. Dan Kresler - 1st Jul 2008 - 10:38 pm
Does anyone have this working in IE7.0 with the latest version of prototype and scriptaculous? It works fine for me in FF3 but gives me a ‘Class’ is undefined error in IE.
491. Rob - 3rd Jul 2008 - 6:04 am
Hi,
Can I load the cropping area after window loading? Not after clicking on the image
Thanks
492. Dave - 3rd Jul 2008 - 7:26 am
Rob:
Yes I think there has been discussion on this within the Google group recently.
493. Chris - 3rd Jul 2008 - 9:18 pm
Hi,
First thanks for an awesome script! I’ve had it bookmarked for over a year, waiting for a chance to fiddle with it. I have now successfully implemented and customized the tutorial at:
http://mondaybynoon.com/2007/12/17/crop-and-resize-images-with-gd-or-imagemagick-v11/
I “customized” it by not giving an option for the crop type, but instead just including the “ratio.js” file only.
I modified the X and Y to 21/8, so images can be cropped and resized to 420×160px.
Unfortunately, the Cropper is stuck at a different ratio (one that, after cropped and resized to a width of 420, generates a 420×131px image).
So, is it possible that the CropperUI is messing up my ratio? If not, where might I look to find what’s causing the problem?
Thanks!
494. Dave - 3rd Jul 2008 - 9:51 pm
Chris:
Is there any chance you could share a live example/email me a test example that I can look at to see what your issue is?
It would also be better to discuss this on the Google group if possible.
Glad you like the cropper, I’ll do what I can to help you resolve your issues.
495. Shaki - 4th Jul 2008 - 8:15 pm
Can we crop and resize the image other then the side we use this script.
496. gktips - 4th Jul 2008 - 8:18 pm
Can we use crop tool for other site . Mean it will work only for the image of script site or for other site also.
497. Dave - 4th Jul 2008 - 9:11 pm
gktips/Shaki:
Can you please clarify your question, and can you please use the Google group for this question, it is linked above at the bottom of the code page (just before the comments)
498. Malwinder - 14th Jul 2008 - 10:05 am
I am trying to test this script but there is some issue with IE7.0. If I am moving the mouse in the browser area, it throws an error and automatically close. Please check and fix.
499. TheIceman5 - 14th Jul 2008 - 12:48 pm
@Malwinder, we aint got crystal balls, unless you give us a URL how are supose to check and fix YOUR coding problem?? we know it a problem with your site but unless we see it we cant see what you’ve stuffed up now can we??
500. shivakumari - 22nd Jul 2008 - 12:56 pm
Hi,
I want to crop the image and store it in a database.Can you explain me how to do it?clearly?
Leave a comment
No HTML please, only textile. For code please use [lang]...[/lang] tags (e.g. [html]...[/html] for HTML)