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.

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.

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 508 comments so far, join the discussion.

Pages: « 2617 16 15 14 13 [12] 11 10 9 8 71 » Show All

240. Dave - 30th May 2007 - 4:26 pm

Hi Marlon,

You should be able to change this by adding and removing the cropper, there is a rudimentary example in the demo which has a CropImageManager class which allows the cropper to be removed and then reapplied using different settings. You should be able to use that as a basis for what you want to achieve.

239. Marlon - 30th May 2007 - 3:52 pm

I have just downloaded ther cropper and it is great. just wondered if there is any way to change the ratio of the selection box, after the cropper has been initiated? IE, i have a selection box with different ratios in, and i need it to change without a page reload.

Many Thanks.

238. hamerhed - 29th May 2007 - 8:54 am

hmm I am seeing that code was removed from my last post Sammy I had the same problem under IE 6 My solution does not use scriptocoluos.js I am inluding all scripts directly into page
src=”/mim/wspolne/.js/cropper/lib/prototype.js” defer=”defer”>
src=”/mim/wspolne/.js/cropper/lib/builder.js” defer=”defer”>
src=”/mim/wspolne/.js/cropper/lib/dragdrop.js” defer=”defer”>
src=”/mim/wspolne/.js/cropper/cropper.js” defer=”defer”>
src=”/mim/wspolne/.js/cropper/onEndCrop_function.js” defer=”defer”>
The order is important.
The last one file consist of my implementation of onEndCrop and code used for creating Cropper object. I hope it helps :)

237. Sammy - 28th May 2007 - 7:05 pm

Wow! This script is something! Thank you so much for seeing the effort.

... But I also have a small problem, as I’m not that much of a javaScript developer. All of the test HTML scripts work just fine, but when I include the script to my site, it works quite randomly. So of course I’m a bit confused ‘cos I’ve ran out of knowledge here. I’m building a feature that users can upload an image if they want and its resized on the server side. Later on they can crop the image (just as an extra feature) on their browser. So the image data is read from a database blob, user can define the crop area on their browser and then the co-ordinates are sent to server and voila! If I’ve understood correctly, that Event.observe(‘load’ ...) should take care that the page and the image is loaded before the script is run. But I think 4 times out of five I’ll get 2 errors. a) Draggable is not defined (line19/cropper.js) and new Cropper.Img has no properties (on the HTML page). So it seems to me that the script is run before the image is loaded. Can someone give me a gentle push towards how to solve this problem? Like I wrote, I’m bit confused since sometimes the script works and sometimes it doesn’t… Tried all of the trick I know, but of course that is not a lot :)

But keep up the good work! This script is really something!!

236. hamerhed - 27th May 2007 - 12:51 am

hi
I have found the solution. I am including all needed .js files directly, without using scriptaculous.js.

and I am moving onEndDrop function from .html file to other .js file which is included to HTML file

that’s solved problem with using tools at IE 6.

235. hamerhed - 25th May 2007 - 11:22 pm

Hi all
I have problem with IE 6. I can’t load the page. The problem is with scriptoculous.js file. This script writes to the output only libraries given as script params and ended. :/ There is no following page code. When I am removing this file from code, all page is loaded. Under firefox 1.5 there is no problem Thanks for any help

234. Sergey Koksharov - 22nd May 2007 - 3:14 pm

I like your updates! They are very useful. Thanks.

233. ramon soler - 22nd May 2007 - 2:58 pm

i would like to use the selected image on a new image in order to zoom the selected image some ideas pls
to use in a state map
how to use the selected image as a new image
and how to avoid the darkening of the image is there an option fej same color and a rectangle with border to select
thanks

232. Yucel Kandemir - 22nd May 2007 - 11:02 am

AMAZİNG!!!!

231. Barton - 17th May 2007 - 4:14 pm

It doesn’t seem to work with Scriptaculous 1.6.5. Can anyone confirm?

230. zhuatu - 11th May 2007 - 2:12 am

pls improve:
add the function of zoom in/out,
input data directly to textfield

229. zhuatu - 6th May 2007 - 6:03 am

这几天一直在做这个,终于可以实际应用了:

http://www2.zhuatu.com/crop/index.asp?testImage=2.jpg

只是还有几个问题,一直无法解决:

1、图片放大缩小后,那个透明层没有随之放大缩小。找不到解药。
2、图片下那几个文本框,无法直接填数字。怎样改成直接填数字也可以?
3、裁减后为什么只能另存为bmp?我想另存为jpg。

228. CodeBit.cn - 5th May 2007 - 6:09 am

good job !
thanks !

227. zhuatu - 5th May 2007 - 1:03 am

http://www2.zhuatu.com/crop/1.htm

test2 error
help me

两个测试,试一下,可以发现,测试一没问题。因为图片不大。

但,测试二,问题来了。大图片,我虽然按比例缩小显示了,但裁减的时候,其实还是在原大小上裁减。所以造成定位不准。

我呼唤高手,怎样做到,让大图缩小显示,裁减的位置也是在缩小的图上进行的。

226. kaleemullah khan - 3rd May 2007 - 2:49 pm

Event.observe( window, ‘load’, function() {.......

show white overlay on some Internet Explorer 6, even after updating windows,

any suggestion

225. levi - 25th Apr 2007 - 6:36 am

For the problem in post 223(“2. When displaying an initial crop area on the image (onload), the arrow keys do not work. We first have to move the area a bit to make the arrows work.”) additionally: – if the ratio is set and the image is in the initial state, if the side of the image is dragged to the right, or up, the selection box jumps out of the image. If the image is moved a little then there are no problems. This seems to be some initialization problem, so isn’t there a way to set the fields of the image crop after the instantiation to simulate an image move without explicitely having to move the image by hand?

Thanks!

224. Gajendra Bang - 25th Apr 2007 - 2:58 am

Hi,

Can I save the cropped image using code ????

223. Dave - 24th Apr 2007 - 11:08 am

I implemented the cropper but found a few problems :

1. After using the arrows to move the crop area, the callback function OnEndCrop is not called. How to display the coordinates after each move with the arrows ?

2. When displaying an initial crop area on the image (onload), the arrow keys do not work. We first have to move the area a bit to make the arrows work.

Dave

222. Pradeep Kumar Mishra - 24th Apr 2007 - 5:41 am

For a given image I have used
//zoomWidth: Final image width after applying zoom(in/out)
//zoomHeight: Final image height after applying zoom(in/out)
//x1,y1, cropWidth and cropHeight are same as x1, y1 , w & h in above example

image = ScaleToFixedSize(image, zoomWidth, zoomHeight);
image = Crop(image, x1,y1,cropWidth,cropHeight);

private Image ScaleToFixedSize(Image imgPhoto, int Width, int Height)

{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);

//if we have to pad the height pad both the top and the bottom
//with the difference between the scaled height and the desired height
if (nPercentH

221. Dave - 21st Apr 2007 - 7:13 pm

I’m testing the component but I have a problem.
The image is displayed in an IFRAME. I added the code to the page that is displayed in the IFRAME. But nothing happends when I click on the image.

What’s wrong ?

Pages:« 2617 16 15 14 13 [12] 11 10 9 8 71 » Show All

Leave a comment

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