Ruby on Rails
JavaScript, XHTML, CSS
Java, Distributed Systems
<you_name_it>
Cropping Images with JavaScript
Imagine you have an image on your web page. And you want to crop an area from that image and display it with a given size. And you want to do that, without the server having to do the heavy work. Well then, read on, here's a solution.
First, check out the example.
I'm using prototype for this - it comes with loads of nice functions that make your life much easier. The following code snippets assume that you included prototype to your page.
The markup is pretty simple, it contains an image tag with an ID and a DIV which will later on contain the cropped image, with the width and height set via CSS styles:
<p>The cropped image</p> <div id="crop" style="width:80px; height:80px;"></div> <p>Cropped from this one</p> <img id="img" src="bond.jpg" />
The markup will be enriched by the following JavaScript function, which does all the cropping and resizing:
function crop(img_id, crop_id, x, y, width, height) {
$(crop_id).update('<img id="' + crop_id + '_img" src="' +
$(img_id).getAttribute('src') + '" style="display:none" />');
var scale_x = $(crop_id).getWidth() / width;
var scale_y = $(crop_id).getHeight() / height;
$(crop_id).setStyle({
position: 'relative',
overflow: 'hidden'
});
$(crop_id + '_img').setStyle({
position: 'absolute',
display: 'block',
left: (-x * scale_x) + 'px',
top: (-y * scale_y) + 'px',
width: ($(img_id).getWidth() * scale_x) + 'px',
height: ($(img_id).getHeight() * scale_y) + 'px'
});
}
It takes six parameters:
- img_id: The ID of the IMG tag that contains the original image
- crop_id: The ID of the DIV that will contain the cropped image
- x, y: The left, top position of the area to crop in the original image
- width, height: The size of that area
In order to crop an area from an image, just call "crop" with your parameters of choice. In the example above I'm using body.onload to do the trick:
<body onload="crop('img', 'crop', 160, 140, 60, 60)">
That's it...

External images
One work around for that is having a hidden (style=display:none) image that you load from an external source - that should do the trick.
This code doesn't work on images
This code doesn't work on images requiring a path; i.e. to display ONLY a cropped portion of an image from another site. Often, only a certain portion of another image is of interest. This code doesn't display any cropped image at all in such case.
hi, this working fine but i want to
hi,
this working fine
but i want to save cropped image in my server with server side control.
please help me
thanks
in advenced
AJAX
That's possible with AJAX, when you want cropping on the client side. You need a JavaScript application (for example this: http://www.defusion.org.uk/demos/060519/cropper.php?demoType=preview&ima...), then need post the cropped part to a server-side script which saves it. More scripts: http://www.hotscripts.com/blog/javascript-image-cropping-scripts/