Today, I’m going to show you how to combine jQuery, jCrop, and ImageResizing.Net to create an AJAX cropping interface – in 11 lines of javascript. This produces true, cropped images that you can use anywhere on the site simply by referencing the generated URL. And all with free, mature, open-source software.
This technique works with .NET 2.0, 3.0, 3.5, 4.0, both MVC and WebForms.
If you’re one of those people who reads books backwards, you can skip to the basic demo, the advanced demo, or just ruin everything and download the sample project
If you’re using NuGet, you can just install the ImageResizer.Samples.Jcrop package into a Web Application project.
Ingredients
- jquery.min.js – from the /js/ folder of the jcrop download
- jquery.Jcrop.js – from /js/
- jquery.Jcrop.css – from /css/ (Provides CSS rules for styling the ‘rubber band’)
- Jcrop.gif – from /css
- ImageResizer.dll – from the /dlls/release of the ImageResizer download at imageresizing.net (Provides the server-side resizing and cropping).
Mixing instructions
- In Visual Studio, right click your project and choose “Add reference”. Browse to ImageResizer.dlll and click “Add”.
- Add ImageResizer.InterceptModuleto the <modules> and/or <httpModules> section of web.config. This allows the ImageResizer to handle image requests that have a querystring.
01.
<
configuration
>
02.
<
system.web
>
03.
<
httpModules
>
04.
<!-- this is for Classic mode and Cassini -->
05.
<
add
name
=
"ImageResizingModule"
type
=
"ImageResizer.InterceptModule"
/>
06.
</
httpModules
>
07.
</
system.web
>
08.
<
system.webServer
>
09.
<
validation
validateIntegratedModeConfiguration
=
"false"
/>
10.
<
modules
>
11.
<!-- This is for Integrated mode-->
12.
<
add
name
=
"ImageResizingModule"
type
=
"ImageResizer.InterceptModule"
/>
13.
</
modules
>
14.
</
system.webServer
>
15.
</
configuration
>
- Add the first 4 ingredients to the project. If you keep the same directory structure, you won’t have to modify the sample code below
The Code
This code is just HTML and javascript, so you can use it with WebForms, MVC, Razor – anything.
- Include the script files jquery.min.js, jquery.Jcrop.js, and the CSS file jquery.Jcrop.jsin the head section.
1.
<
script
src
=
"js/jquery.min.js"
type
=
"text/javascript"
></
script
>
2.
<
script
src
=
"js/jquery.Jcrop.js"
type
=
"text/javascript"
></
script
>
3.
<
link
href
=
"css/jquery.Jcrop.css"
type
=
"text/css"
rel
=
"stylesheet"
/>
- In the body, insert a <div> containing an <img> and an <a> element.
1.
<
div
class
=
"image-cropper"
>
2.
<
img
src
=
"fountain-small.jpg?width=400"
class
=
"image"
/>
3.
<
a
class
=
"result"
>View the result</
a
>
4.
</
div
>
Note the ‘?width=400′ in the image URL. This instructs the ImageResizer to shrink the image before sending it to the client.
- Now for the fun part. Create a <script type=”text/javascript”></script> section inside <head>, below the references we added in step #1.
- Add the following code inside the <script> tags.
01.
$(
function
() {
//On DOM ready
02.
//Using the 'each' pattern allows multiple cropping image/link pairs per page.
03.
$(
'.image-cropper'
).each(
function
(unusedIndex, container) {
04.
container = $(container);
//We were passed a DOM reference, convert it to a jquery object
05.
06.
//Find the image inside 'container' by class ("image")
07.
var
image = container.find(
"img.image"
);
08.
09.
//Trim the querystring off the image URL.
10.
var
path = image.attr(
'src'
);
if
(path.indexOf(
'?'
) > 0) path = path.substr(0, path.indexOf(
'?'
));
11.
12.
//Define a function to execute when the cropping rectangle changes.
13.
var
update =
function
(coords) {
14.
if
(parseInt(coords.w) <= 0 || parseInt(coords.h) <= 0)
return
;
//Require valid width and height
15.
16.
//Build the URL based on the coordiantes. The resizing module will handle everything else.
17.
var
url = path +
'?crop=('
+ coords.x +
','
+ coords.y +
','
+ coords.x2 +
','
+ coords.y2 +
18.
')&cropxunits='
+ image.width() +
'&cropyunits='
+ image.height()
19.
20.
//Now, update the link 'href' (you could update a hidden field just as easily)
21.
container.find(
'a.result'
).attr(
'href'
, url);
22.
}
23.
24.
//Start up jCrop on the image, specifying our function be called when the selection rectangle changes,
25.
// and that a 60% black shadow should cover the cropped regions.
26.
image.Jcrop({ onChange: update, onSelect: update, bgColor:
'black'
, bgOpacity: 0.6 });
27.
});
28.
});
The secret is in the ?crop=(x1,y1,x2,y2) querystring that is appended to the image. The ImageResizer HttpModule detects the command, intercepts the image request, crops the image, and sends the result back, all in milliseconds.
If you’re dealing with large images or high traffic volumes, you can enable disk caching so that duplicate requests are served from disk instead of wasting CPU and RAM resources. Disk caching eliminates 99% of the overhead associated with dynamic image resizing, making the ImageResizer scalable enough for even social networking sites.
Live demo and sample project download
You can download the complete sample project here.
Click here to view the live demo of what we just did, and here to see an advanced demo with live preview, width/height resizing, and aspect locking. The advanced demo also contains an example of how to send cropped images URLs to the server for storage in SQL, saving to disk, etc. Perhaps I’ll cover building that in a later post. In the meantime, code fun!
Oh, and dont forget to vote this post up on DZone!