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 Website: 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: « 2612 11 10 9 8 [7] 6 5 4 3 21 » Show All

140. John Aldridge - 14th Dec 2006 - 3:16 pm

Just made a quick function for PHP to crop a stored image and save it to a new path. Might be helpfull, hopefully!

HTML:

  1. function CropImage($imagePath, $sizes) {
  2.     $originalPath = $imagePath; // location of image to be cropped
  3.     $newPath = "/new/".$imagePath; // where to put cropped image
  4.     @unlink($newPath); // unlink destination image if possible
  5.     $originalImage = imagecreatefromjpeg($originalPath); // create image from original
  6.     $thumbImage = imagecreatetruecolor($sizes[‘width’], $sizes[‘height’]); // create thumbnail image
  7.     // perform crop (modified from code posted here, eg. this one doesn’t stretch the image)
  8.     imagecopyresampled($thumbImage, $originalImage, 0, 0, $sizes[‘x1’], $sizes[‘y1’], $sizes[‘width’], $sizes[‘height’], $sizes[‘x2’]-$sizes[‘x1’], $sizes[‘y2’]-$sizes[‘y1’]);
  9.     imagedestroy($originalImage); // destroy image resource
  10.     imagejpeg($thumbImage, $newPath, 100); // save thumbnail to newPath
  11.     imagedestroy($thumbImage); // destroy thumbnail resource
  12. }
  13.  
  14. /* Usage:
  15. $sizes[‘x1’] = $_POST[‘x1’];
  16. $sizes[‘y1’] = $_POST[‘y1’];
  17. $sizes[‘x2’] = $_POST[‘x2’];
  18. $sizes[‘y2’] = $_POST[‘y2’];
  19. $sizes[‘width’] = $_POST[‘width’];
  20. $sizes[‘height’] = $_POST[‘height’];
  21. CropImage("/path/to/image.jpg", $sizes);
  22. */

139. Luis Bolson - 7th Dec 2006 - 1:02 pm

Hi. First of all, Great Work! People like you make the web easier.

About question #125, how can I put multiple croppers in the same page?

I’ve tested with two images, it works fine, except by the fact that one of them actually is not calling the callback function, which is the same for both images. Only the last image calls it.

Thank you.

138. jurciks - 5th Dec 2006 - 10:34 am

I guess you have a small glych with roundings (ImgWithPreview).
Example.
I add image 800×600 and specify width 500px (to fit in page), and use JS – new Cropper.ImgWithPreview(‘testImage’, {
previewWrap: ‘previewWrap’,
minWidth: 175,
minHeight: 140,
ratioDim: {
x: 750,
y: 600},
onEndCrop: onEndCrop
});
(I need to resize with ratio 1.25)
Then I get new coords :

[x1] => 32
[y1] => 0
[x2] => 500
[y2] => 375
[w] => 468
[h] => 375
But actually x1 should be 31.25 or rounded to 31.
Besides this, preview area is displayed 187×140 but it should be 175×140

137. Ant - 3rd Dec 2006 - 10:16 pm

Awesome work Guys!!

I was wondering if there is a way to add snapping to the selection area. As in as the user selects the desired area, it snaps to either 10 pixel increments or some other predefined value.

again, awesome work. Best of the web as far as image tools I’ve seen.

136. Me - 15th Nov 2006 - 5:45 pm

seems like I’am dumb
no question at all ;)
thank you again

135. Me - 15th Nov 2006 - 5:30 pm

that’s great!
script works perfectly but what about loading the page WITH MY coordinates of cropping box?

(i want to save a crop result for future demonstration when page is opened again)

thank you and wish a lot of success

134. Ben Kittrell - 13th Nov 2006 - 6:51 pm

Very cool, Thank you very much.

I was able to get this working easily with Rails.

133. Hessner - 9th Nov 2006 - 12:21 am

Ups, here are the lines:

“Bad”:
!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.0 Transitional//EN”

“Good”:
!DOCTYPE HTML PUBLIC ”-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”

132. Hessner - 9th Nov 2006 - 12:17 am

I used the “good old”:

But it turned out that the lines below are very important for the cropper to work correct:

(my picture disappeared now and again)

Just a tip :-)

131. Dale - 7th Nov 2006 - 8:51 pm

E.X.C.E.L.L.E.N.T.
thank you very much for this awesome piece of work

130. Justin - 6th Nov 2006 - 2:06 pm

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… Then for the PHP page use $_POST[‘var’], or $_GET[‘var’] for each of the variables depending on what method you chose for the form.

Thanks for the new version David!

Justin

129. DJ - 6th Nov 2006 - 8:11 am

Hi, can anyone provide me with the PHP code using this javascript GUI.. I saw the code here in PHP, but I don’t know how to implement it :D Like how do you past the variables from js to PHP?

email mastahswabe at gmail.com

128. Lucas Young - 30th Oct 2006 - 10:38 pm

Hi Dave, awesome work, it’s great in FF now.
I see the overflow: auto problem in IE is still there, what do you think might be causing that?
cheers

Lucas

127. Dave - 30th Oct 2006 - 8:55 pm

Firstly thankyou all for your kind comments, secondly sorry for not replying sooner to you… a lot has been going on, will you accept version 1.2.0 of the cropper as an apology?

Starting in reverse chronolgical order:
Dave Marks:
Rotating would be nice, but HTML doesn’t allow that, try doing it server side as per what it sounds like you’re doing with the flipping.

Andrea:
Thanks for the kind words.

Frank:
The image cropper UI is just the UI for gathering the cropping co-ordinates, the crop itself would have to be performed server side with your chosen language; see some of the other comments for PHP examples.

David Kingston:
As per Frank, there has been some discussion in these comments, if anyone wants to provide a solution or example file I’d be happy to post it and provide appropriate credits etc.

Jakob:
Do you mean when you submit an image to be cropped by some server-side script? If so then that’s nothing to do with the cropper UI, if not – then I have no idea, do you have an example URL?

Mike:
It is possible to have more than one cropper on a page, I had a test page running with about 5 but they did slow down a little.

John:
I don’t know of an issue with an image size, but the way the cropper is implemented in Firefox (and all browsers except IE) has changed in the latest version, so I suggest giving that a try and let me know if you’re still experiencing problems.

Once again, thank you all for your kind comments.

-D

126. John Walter - 30th Oct 2006 - 7:30 pm

David—
Thanks so much for posting a tool that hundreds of people have shown a need for. That’s a very generous gift of your talent…

There seems to be a limit of 640×480 for the images to be manipulated. Larger than that the auto-highlight-within-shadow turns off (at least in Mozilla 2). Is that a scriptaculous limitation?
—John

125. Mike - 26th Oct 2006 - 11:41 pm

Hi ,
Is it possible to have more than one cropper on a page?

Thank You

Mike

124. Jakob - 26th Oct 2006 - 8:28 am

Hello.

First off, this is a GREAT piece of code, and I’ve already had great use for it. Many thanks!

I just have a few questions:

1) I’ve had some problems with Internet Explorer timing out on crop requests, but not with anything else on the site. Could this be a problem with the Javascript?

2) Is there a way to change the size of the crop area by putting/changing the values in text boxes, without refreshing the page?

Again, thanks.

123. Chad - 25th Oct 2006 - 4:12 pm

Whoops:

imagecopyresampled($thumb, $big, 0, 0, $x1, $y1, $x2, $y2, $x2-$x1, $y2-$y1);

122. Chad - 24th Oct 2006 - 9:19 pm

Using the PHP code from post 21 I changed:

imagecopyresampled($thumb, $big, 0, 0, $x1, $y1, $x2, $y2, $ow, $oh);
to
imagecopyresampled($thumb, $big, 0, 0, $x1, $y1, $x2, $y2, $x2, $y2);

A typical image crop results in an image with new content (the selection) and a new width/height (the width and height of the selection). The original PHP code would stretch the crop to be as large as the original image and acted more like a ‘zoom’ effect. Changing $ow to $x2 and $oh to $y2 will create the new images’ width/height based off the selection which is atleast what I was looking for.

Thanks for the great script, it was exactly what I was looking for.

Chad

121. Jason - 23rd Oct 2006 - 7:56 pm

Dear me, I just saw the demo and that there is already a way to remove the cropper. I swear I didn’t see that before!!!

Thanks much.

Pages:« 2612 11 10 9 8 [7] 6 5 4 3 21 » Show All

Leave a comment

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