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.
Other Resources: 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 494 comments so far, join the discussion.
Pages: « 25 … 21 20 19 18 17 [16] 15 14 13 12 11 … 1 » Show All
320. Thomas - 15th Sep 2007 - 6:51 pm
MAN you are crazy. This thing is 200 KB big! I am not willing to add 200kb to a page that is supposed to be no more than 50 KB. You need to make this shit smaller.
319. Jeff - 13th Sep 2007 - 12:53 pm
How to copy or save the preview exactly as a square? I’ve tryed, but the image is the same as the original.
318. James MacFarlane - 12th Sep 2007 - 7:06 pm
I hacked together this .NET script that will generate the cropped image as a file. The code currently generates “small” and “thumbnail” files. You can edit the paths and parameters as needed. Be sure to enable write permissions for the output folder on your server.
[lang]
private void Page_Load(object sender, System.EventArgs e) {
GenerateThumbNailImagesForFolder(“Images”);
}
public void GenerateThumbNailImagesForFolder(string FolderName) {
string sPhysicalPath=””;
string sFileName=RequestObject(“image”);
string sThumbName = sFileName.Replace(”.”, ”_t.”);
string sSmallName = sFileName.Replace(”.”, ”_c.”);
sPhysicalPath = Server.MapPath(FolderName);
try {
this.GenerateThumbNail(100,80,sPhysicalPath,sFileName,sThumbName,ImageFormat.Jpeg);
this.GenerateThumbNail(40,50,sPhysicalPath,sFileName,sSmallName,ImageFormat.Jpeg);
}
catch (Exception) { }
}
public void GenerateThumbNail(int maxHeight, int maxWidth, string sPhysicalPath,string sOrgFileName,string sThumbNailFileName,ImageFormat oFormat) {
try {
System.Drawing.Image oImg = System.Drawing.Image.FromFile(sPhysicalPath + @”\” + sOrgFileName);
string dispRatio = “”;
int x1=Convert.ToInt16(RequestObject(“x1”));
int y1=Convert.ToInt16(RequestObject(“y1”));
int w1=Convert.ToInt16(RequestObject(“width”));
int h1=Convert.ToInt16(RequestObject(“height”));
int w2 = w1;
int h2 = h1;
long myRatio = (oImg.Height/maxHeight);
int newWidth = Convert.ToInt32((oImg.Width / myRatio));
if(w1>maxWidth) {
long myRatioW = (oImg.Width/newWidth);
dispRatio=Convert.ToString(myRatioW);
h2 = Convert.ToInt16((oImg.Height / myRatioW));
w2 = newWidth;
}
System.Drawing.Image oThumbNail = new Bitmap(w2, h2, oImg.PixelFormat);
Graphics oGraphic = Graphics.FromImage(oThumbNail);
oGraphic.CompositingQuality = CompositingQuality.HighQuality ;
oGraphic.SmoothingMode = SmoothingMode.HighQuality ;
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic ;
oGraphic.DrawImage(oImg, new Rectangle(0, 0, w2, h2), x1, y1, w1, h1, GraphicsUnit.Pixel);
Response.Write(“”);
//Response.Write(“w: “w1” h:”h1” w2:”w2” h2:”h2” x:”x1” y:”y1” r:” +Convert.ToString(dispRatio));
oThumbNail.Save(sPhysicalPath + @”\” + sThumbNailFileName,oFormat);
oImg.Dispose();
}
catch (Exception ex) {
Response.Write(ex.Message);Response.Write(“Error writing file: ” + sPhysicalPath + @”\” + sThumbNailFileName+””);
}
}
public string RequestObject(string sName) {
string sRet=””;
try { sRet = Request[sName].ToString().Trim(); }
catch (Exception) { sRet = “”;}
return sRet;
}
[/lang]
317. GhostGambler - 12th Sep 2007 - 12:34 pm
Well… it seems to be necessary to add an !important to both options, otherwise it won’t work~
316. GhostGambler - 11th Sep 2007 - 1:46 pm
hm…
IE7 and FF use the images too, which slows the cropper down in those two browsers as well.
Little change:
Leave original CSS as is and add to the bottom of the file (or after the already mentioned blocks):
The holy star attack limits the extra CSS to IE6 and lesser versions~
315. kral oyun - 11th Sep 2007 - 7:30 am
thank you.
314. GhostGambler - 10th Sep 2007 - 10:23 am
cropper.css
replace this one with background-image and a transparent gif dotted with black pixels (I use this one http://ghostgambler.mangacarta.de/cropper/transBlack.gif)
replace this one with a totally transparent gif (sth. like that http://ghostgambler.mangacarta.de/cropper/trans.gif)
This is slow in IE6, but it works shrug
313. GhostGambler - 10th Sep 2007 - 8:44 am
Sure, but those do not use prototype~
http://www.dhtmlgoodies.com/index.html?whichScript=image-crop
http://www.ajaxprogrammer.com/?p=9
(and I don’t know about the licenses)
312. Chris - 9th Sep 2007 - 8:58 pm
Thanks Ghost. I played with the IE adjustments but still couldn’t get the
results you mentioned.
Any pointers to the alternative lib?
311. GhostGambler - 8th Sep 2007 - 9:45 am
Hi
@Mike
Yes, your solutions seems similar to mine.
This was a fix in case someone did not use onload or observer, but just wrote a script-tag under the image and loaded the cropper there~ because that resulted in problems.
@Chris
I encounter the same problem on both pages, local and remote – no difference.
The problem seems to be a “fix” for IE – If you “remove” the fix, the image is displayed properly – but you can’t crop :D
Had not had enough time yet to play around with it a lot – just poked the code a little bit yesterday evening~
If I find something useful I’ll report it here, if I don’t, I’ve switched to another lib :P
310. Chris - 7th Sep 2007 - 11:05 pm
I’ve got a couple of relatively simple test cases:
http://www.firecoral.com/local.html
and
http://www.firecoral.com/remote.html
The only difference in them is that local.html pulls it’s cropper.js from the
local machine while remote.html pulls all it’s files from this site (defusion.org.uk).
Try reloading each of them a few times in IE7.
Here’s what I see.
The first time I load local.html, it kind of works (I’m guessing because
the image is not cached). The second and other time, there’s no
sign of the image in the (top) table version. local.html remains broken
after that.
When I load remote.html, it usually appears to work through reloads although
the top image has some solid black bars above and below the crop box.
What’s the difference? Only one line – where cropper.js is served from.
All of this leads me believe that it’s some subtle timing issue. The idea
of using window.onload() would hint at this (although my application does
load dynamically and that doesn’t fix it).
Thanks much for the ideas though.
309. Mike - 7th Sep 2007 - 9:35 pm
In IE7 cropper appears WHITE with Images NOT LOADING under the divs! Eeeeeeek!!
It however DOES WORK upon F5 (refresh) ... very strange ‘eh?
Anyone gots a work around for these?
PS: GhostG – Can you please elaborate on your solution, as it doesn’t make sense to me… Doesn’t the code execute onload anyway (example):
[lang]
Event.observe(
window,
‘load’,
function() {
new Cropper.ImgWithPreview(
‘cropImage’,
{ }
)
}
);[/lang]
308. GhostGambler - 7th Sep 2007 - 4:51 pm
Hey Chris
I maybe had the same issue (trying to find the reason of the one I ran into), and maybe found a bugfix for yours: (I hope I can post the code here oO?)
instead of
try
this worked for me~
307. Chris - 6th Sep 2007 - 3:57 pm
Well, I’ve been struggling with bug/issue 027 – The cropper doesn’t work
correctly in a table cell in IE7. It seems to come down to a timing issue,
since it occasionally works, but most of the time the image fails to appear
under the cropping divs.
Has anyone found a fix or work-around for this? It’s pretty much a show-stopper
for me.
Thanks!
306. Matt - 30th Aug 2007 - 10:37 pm
Using IE6 here I’m also getting black images with a white box where the cropper should be, works fine in FF and IE7 though. I’m guessing this is a transpanrency issue with IE6?
Any solutions?
305. GhostGambler - 29th Aug 2007 - 12:33 pm
Hi
The text says the script would work with IE6 – I tried the demo page (http://www.defusion.org.uk/demos/060519/cropper.php), but the image turns completely black and the crop rectangle is just white … this is useless as you cannot see what you are cropping oO
Help? ;
Bye, GhostGambler
304. Mike M - 28th Aug 2007 - 4:26 am
Great script! I have one question. I’m using the preview example. Is there a way to change the previewWrap div after the page is loaded, as to move the position of the preview image? I’ve tried to access previewWrap and change it’s value, but either it’s only used when the Cropper object is created or, more likely, my knowledge of OOP is less than stellar.
Thanks,
Mike
303. Alvaro - 27th Aug 2007 - 1:15 am
Hi Dave, it is a great work, congratulations. But i have some questions.
How i could get the cropper image and make a new image for upload it.
Because for example i need use it for the user can upload his picture and crop his face, like gmail do it when in configuration you upload a picture and you can crop you picture for get you face and it image is show it.
I hope that you could understand my bad english.
Thanks a lot for you work.
302. Dave - 26th Aug 2007 - 8:44 am
Caio:
You need to hold a reference to the cropper so that you can call the remove method on it, so basically you just need to do: var myCropper = new Cropper.Img( ... ) and then later on do myCropper.remove();
Hope that helps.
301. Caio Brentano - 24th Aug 2007 - 2:29 pm
Hi… is there a way to Remove Cropper? I found it on example-DynamicImage.htm, but I don’t want to use CropImageManager. I just do this to get cropper:
Event.observe(
‘id_img’,
‘click’,
function(){
new Cropper.Img(
‘id_img’,
{ minWidth: 10,
minHeight: 10,
onEndCrop: onEndCrop
});
});
So, when I click on imagem with id=’id_img’, Cropper is attched. How can I remove it?
Regards.
Leave a comment
No HTML please, only textile. For code please use [lang]...[/lang] tags (e.g. [html]...[/html] for HTML)