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.

Click here to lend your support to: JavaScript Image Cropper V2 fund raising and make a donation at www.pledgie.com !

Details

Version 1.2.0
Last updated 30th October 2006
Requirements
Demo View demo page
Links
License BSD License
Changelog
1.2.0
  • Added id to the preview image element using 'imgCrop_[originalImageID]'
  • #00001 - Fixed bug: Doesn't account for scroll offsets
  • #00009 - Fixed bug: Placing the cropper inside differently positioned elements causes incorrect co-ordinates and display
  • #00013 - Fixed bug: I-bar cursor appears on drag plane
  • #00014 - Fixed bug: If ID for image tag is not found in document script throws error
  • Fixed bug with drag start co-ordinates if wrapper element has moved in browser (e.g. dragged to a new position)
  • Fixed bug with drag start co-ordinates if image contained in a wrapper with scrolling - this may be buggy if image has other ancestors with scrolling applied (except the body)
  • #00015 - Fixed bug: When cropper removed and then reapplied onEndCrop callback gets called multiple times, solution suggestion from Bill Smith
  • Various speed increases & code cleanup which meant improved performance in Mac - which allowed removal of different overlay methods for IE and all other browsers, which led to a fix for:
  • #00010 - Fixed bug: Select area doesn't adhere to image size when image resized using img attributes
  • #00006 - Removed default behaviour of automatically setting a ratio when both min width & height passed, the ratioDimensions must be passed in
  • #00005 - Added ability to set maximum crop dimensions, 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
  • Switched keydown for keypress for moving select area with cursor keys (makes for nicer action) - doesn't appear to work in Safari
1.1.3
  • Fixed wrong cursor on western handle in CSS
  • #00008 & #00003 - Added feature: Allow to set dimensions & position for cropper on load
  • #00002 - Fixed bug: Pressing 'remove cropper' twice removes image in IE
1.1.2
  • Fixed bugs with ratios when GCD is low (patch submitted by Andy Skelton)
1.1.1
  • Fixed bug with rendering issues fix in IE 5.5
  • Fixed bug with endCrop callback issues once cropper had been removed & reset in IE
1.1.0
  • Fixed bug with IE constantly trying to reload select area background image
  • Applied more robust fix to Safari & IE rendering issues
  • Added method to reset parameters - useful for when dynamically changing img the cropper is attached to
  • Added method to remove cropper from image
1.0.0
  • Initial verison

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

Screen shot of cropper in action

  • 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:

HTML:
  1. <script type="text/javascript" src="scripts/cropper/lib/prototype.js" language="javascript"></script>
  2. <script type="text/javascript" src="scripts/cropper/lib/scriptaculous.js?load=builder,dragdrop" language="javascript"></script>
  3. <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:

JavaScript:
  1. function onEndCrop( coords, dimensions ) {
  2.     $( 'x1' ).value = coords.x1;
  3.     $( 'y1' ).value = coords.y1;
  4.     $( 'x2' ).value = coords.x2;
  5.     $( 'y2' ).value = coords.y2;
  6.     $( 'width' ).value = dimensions.width;
  7.     $( 'height' ).value = dimensions.height;
  8. }

Basic interface

This basic example will attach the cropper UI to the test image and return crop results to the provided callback function.

HTML:
  1. <img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
  2.  
  3.     <script type="text/javascript" language="javascript">
  4.     Event.observe( window, 'load', function() {
  5.         new Cropper.Img(
  6.             'testImage',
  7.             { onEndCrop: onEndCrop }
  8.         );
  9.     } );
  10. </script>

Minimum dimensions

You can apply minimum dimensions to a single axis or both, this example applies minimum dimensions to both axis.

HTML:
  1. <img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
  2.  
  3. <script type="text/javascript" language="javascript">
  4.     Event.observe( window, 'load', function() {
  5.         new Cropper.Img(
  6.             'testImage',
  7.             {
  8.                 minWidth: 220,
  9.                 minHeight: 120,
  10.                 onEndCrop: onEndCrop
  11.             }
  12.         );
  13.     } );
  14. </script>

Select area ratio

You can apply a ratio to the selection area, this example applies a 4:3 ratio to the select area.

HTML:
  1. <img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
  2.  
  3. <script type="text/javascript" language="javascript">
  4.     Event.observe( window, 'load', function() {
  5.         new Cropper.Img(
  6.             'testImage',
  7.             {
  8.                 ratioDim: {
  9.                     x: 220,
  10.                     y: 165
  11.                 },
  12.                 displayOnInit: true,
  13.                 onEndCrop: onEndCrop
  14.             }
  15.         );
  16.     } );
  17. </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.

HTML:
  1. <img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
  2. <div id="previewWrap"></div>
  3.  
  4. <script type="text/javascript" language="javascript">
  5.     Event.observe( window, 'load', function() {
  6.         new Cropper.ImgWithPreview(
  7.             'testImage',
  8.             {
  9.                 previewWrap: 'previewWrap',
  10.                 minWidth: 120,
  11.                 minHeight: 120,
  12.                 ratioDim: { x: 200, y: 120 },
  13.                 onEndCrop: onEndCrop
  14.             }
  15.         );
  16.     } );
  17. </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.

Links of Interest: 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.

Click here to lend your support to: JavaScript Image Cropper V2 fund raising and make a donation at www.pledgie.com !

Discussion

Note: Please only use the comments for general comments and the discussion list to discuss this code project (e.g. implementation queries, change suggestions etc.).

Comments

There have been 513 comments so far, join the discussion.

Pages: « 2611 10 9 8 7 6 5 4 [3] 2 1 » Show All

60. Dave - 14th Aug 2006 - 7:07 pm

Adam:
For your first question “I’d like to set another callback when I double click on the cropping area”, I don’t see that as being functionality I plan to add. As for the lightbox style presentation of the cropper my guess is that it relates to the issues the cropper currently has when within differently positioned wrapper elements, which is on the list of bugs.

Jason:
I’m having trouble trying to replicate your problem, everything is working fine for me in IE with the callback. Can you provide a test case to me via email that demonstrates the problem.

Nate:
Thanks for the ASP code that integrates with the cropper, do you have a link to this code that I can use in the code details. If not am I OK to package it myself and release it on this page?

Ash:
Thanks for the kind words. I haven’t taken much of a look at this script, or tried it in conjunction with the cropper UI, but you should be able to use this to crop the image server side in PHP.

Matthew:
Those styles are only part of the test cases & examples, all the class names used for the cropper itself are isolated with the imgCrop_ prefix.

Uberdoer:
Thanks a lot for your kind words and very kind donation, it is my second so far and is great. Thanks again.

59. Uberdoer - 13th Aug 2006 - 9:12 am

Finally got around to sending that paypal payment. Well done on a very good bit of coding.

I have to say that your cropperui has added panache to an almost completed www.paint-that.com. Thanks!

58. Matthew - 12th Aug 2006 - 10:24 pm

If you use CakePHP you will notice that including this in your script will break the CSS layout. This is due to the CSS rule

form div{
vertical-align: text-top;
margin-left: 1em;
margin-bottom:2em;
overflow: auto;
}

A simple workaround is to add another rule directly after this like so:

form div.no_cake, form div.no_cake div {
margin:0;
overflow:hidden;
}

and then in your code surround the img tag with a div with the class name of no_cake.

Cheers

57. Ash - 10th Aug 2006 - 10:25 pm

Hi! Firstly I’d like to say what an absolutely fantastic piece of coding. You truly are amazing at what you do!

Could someone point me in the right direction about what to research to learn how to get this to save the cropped image on my server after hitting a crop button? I don’t really have the first idea, but i’m pretty good at learning if someone can tell me where to look for a starting point. Although at the same time the easiest and fastest method would be better as if someone has already made a cropping script then theres no point in me recreating it (and badly as i don’t really know what i’m doing).

Am i right in guessing that i can feed in the ingoing_filename, ingoing_width, ingoing_height, crop_topleft, crop_botright, outgoing_width, outgoing_height, outgoing_filename to some kind of PHP script (that possibly uses GD library or something) to save the cropped version of the picture. I know i’m probably insulting all of you guys intelligence but am i along the right lines at least?

Any help is greatly appreciated, but i’m not looking for someone to hold my hand. And if you guys are all too busy then thats no problem – i’ll completely understand and i’m sorry for wasting your time reading this.

Oh keep up the good work Dave. If i end up using this for any of my projects at all then i will definately donate.

Cheers

56. Nate - 4th Aug 2006 - 1:36 pm

This is an excellent script, exactly what I was looking for.
Here is an ASP function I just wrote that works with this. Grabbing the variables is handled elsewhere, but should be easy enough to figure out.

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
// img is defined earlier in the Picture class
// I created, and is just a System.Drawing.Image
// x/y1 and width/height are the same as in
// cropper resWidth/Height are the resulting
// image dimensions, so I can resize the crop too.
// You probably just want to remove the Picture
// types and just use Image or Bitmap types
public Picture crop(int x1, int y1, int resWidth, int resHeight, int width, int height)

{
Picture res;
Bitmap bm = new Bitmap(resWidth, resHeight, PixelFormat.Format24bppRgb);
bm.SetResolution(img.HorizontalResolution, img.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bm);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(img,
new Rectangle(0, 0, resWidth, resHeight),
new Rectangle(x1, y1, width, height),
GraphicsUnit.Pixel);
grPhoto.Dispose();
res = new Picture((System.Drawing.Image)bm);

return res;
}

55. Chris - 4th Aug 2006 - 1:36 pm

On the dynamically changable image demo the layout isn’t udpated between image selections.

[...] Ben Forta posted a link to an interview with Dave Spurr today. I know Dave quite well and even linked to some excellent work of his a few months ago. The first reason I’m blogging about this is that I’m quite impressed that his name showed up on Forta’s blog but also to point out that the post on WebWire doesn’t include a link to his excellent blog. [...]

53. Jason - 3rd Aug 2006 - 4:35 am

I’m still having trouble with IE’s callback… after the first crop the coordinates are always 0. I’ve attempted to do a cropper.remove(); cropper.reset(); in 100 different orders and then re-initializing a cropper object on demand… with no success. How does your IE fix work??

52. Adam Roth - 2nd Aug 2006 - 11:13 pm

New issue…

I’m using the cropper in a lightbox-style POP-up (absolutely positioned). If the page is scrolled (that is, the veritcal scrollbar is not at the top) then the crop selection is off by the height of the scroll.

I’m getting around this by scrolling the window back to 0,0 when the lightbox is displayed, and then back to the correct position after the crop. It’d be cool if the cropper could be aware of this, however.

50. Adam Roth - 31st Jul 2006 - 9:10 pm

I’d like to set another callback when I double click on the cropping area (which would then make the AJAX call to the server). Does the cropper currently support this functionality? Might it?

[...] Se trata solo de una demo, pero no deja a nadie indiferente el poder de prototype y lo que podemos llegar a hacer usando una librería tan completa como pesada como script.aculo.us. Sin duda las aplicaciones web están cambiando y cada día más y pasos más agigantados. Esto es una muestra de ello.  [...]

48. Skylog » Blog Archive » links for 2006-07-27 - 27th Jul 2006 - 6:28 am

[...] JavaScript Image Cropper UI, using Prototype & script.aculo.us (tags: javascript) [...]

47. bala - 25th Jul 2006 - 8:26 pm

Can you tell me how to upload that cropped image into the server in ASP?

46. Dave - 24th Jul 2006 - 7:24 pm

Just a quick note to say that I’ve added a link to the list of feature requests & bugs for the image cropper. These are all areas I intend to address at some point, note they are not in priority order.

45. Reynold - 24th Jul 2006 - 3:54 am

Hey this is a great script. Just wondering when the image gets so large (say above 2000), it would be nice if I could instead crop a zoomed version of the image. I just tried with this cropper and , however, it doesn’t seem like the zoomed one. Instead, the script displays the original size image in the cropper window.

44. Dave - 19th Jul 2006 - 8:05 pm

Nation-x:

Thanks, that script looks quite good, some of it I’ve seen before and am already using in some areas. Your other request has been added to the feature/bug list.

Bane:

I’ve added the ability to set minimum dimensions without applying a ratio constraint to the feature request list.

Adam:

That error sounds like you are trying to call the methods before the cropper has been attached. It should work for you once it’s attached, I’ve added your request of being able to set cropper dimensions & position on init to the feature request list.

Neil:

The wrapper needs to have a relative position as the select area etc. are all then positioned absolutely within that container, I’ve added extra testing of things like placing other wrappers around the cropper with different positioning, margins & padding etc. the bug list.

43. Neil - 18th Jul 2006 - 3:00 pm

After playing a bit more it seems that the wrapper’s position: relative is giving the cropper the most problems.

42. Neil - 18th Jul 2006 - 2:51 pm

I’ve taken the example and thrown a wrapper div around it, gave it a width, relative position and margins and the selector goes a bit wacky.

http://www.susan-deaux.com/z/cropper/tests/example-Preview.htm

41. Adam Roth - 17th Jul 2006 - 4:28 am

...or better yet, can I pass in starting coordinates for the cropping box when creating the cropping obj?

Pages:« 2611 10 9 8 7 6 5 4 [3] 2 1 » Show All

Leave a comment

No HTML please, only textile. For code please use [lang]...[/lang] tags (e.g. [html]...[/html] for HTML)