jCrop and ASP.NET server-side image resizing combined

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.


Mixing instructions

  1. In Visual Studio, right click your project and choose "Add reference". Browse to ImageResizer.dlll and click "Add".
  2. Add ImageResizer.InterceptModule to the <modules> and/or <httpModules> section of web.config. This allows the ImageResizer to handle image requests that have a querystring.
          <!-- this is for Classic mode and Cassini -->
          <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
        <validation validateIntegratedModeConfiguration="false"/>
          <!-- This is for Integrated mode-->
          <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
  3. 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.
  1. Include the script files  jquery.min.js, jquery.Jcrop.js,  and the CSS file jquery.Jcrop.js in the head section.
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <script src="js/jquery.Jcrop.js" type="text/javascript"></script>
    <link href="css/jquery.Jcrop.css" type="text/css" rel="stylesheet" />
  2. In the body, insert a <div> containing an <img> and an <a> element.
    <div class="image-cropper">
        <img src="fountain-small.jpg?width=400" class="image" />
        <a class="result">View the result</a>
    Note the '?width=400' in the image URL. This instructs the ImageResizer to shrink the image before sending it to the client.
  3. Now for the fun part. Create a <script type="text/javascript"></script> section inside <head>, below the references we added in step #1.
  4. Add the following code inside the <script> tags.
    $(function () { //On DOM ready
        //Using the 'each' pattern allows multiple cropping image/link pairs per page.
    	$('.image-cropper').each(function(unusedIndex, container) {
    	    container = $(container); //We were passed a DOM reference, convert it to a jquery object
    	    //Find the image inside 'container' by class ("image")
    	    var image = container.find("img.image");
    	    //Trim the querystring off the image URL.
    	    var path = image.attr('src'); if (path.indexOf('?') > 0) path = path.substr(0, path.indexOf('?'));
    	    //Define a function to execute when the cropping rectangle changes.
    	    var update = function (coords) {
    	        if (parseInt(coords.w) <= 0 || parseInt(coords.h) <= 0) return; //Require valid width and height
    	        //Build the URL based on the coordiantes. The resizing module will handle everything else.
    	        var url = path + '?crop=(' + coords.x + ',' + coords.y + ',' + coords.x2 + ',' + coords.y2 +
                ')&cropxunits=' + image.width() + '&cropyunits=' + image.height()
    	        //Now, update the link 'href' (you could update a hidden field just as easily)
    	        container.find('a.result').attr('href', url);
    	    //Start up jCrop on the image, specifying our function be called when the selection rectangle changes,
            // and that a 60% black shadow should cover the cropped regions.
    	    image.Jcrop({ onChange: update, onSelect: update, bgColor: 'black', bgOpacity: 0.6 });

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!

Published on

About Nathanael

Nathanael Jones is a software engineer, father, consultant, and computer linguist with unreasonably high expectations of inanimate objects. He refines .NET, ruby, and javascript libraries full-time at Imazen, but can often be found on stack overflow or participating in W3C community groups.


If you develop websites, and those websites have images, ImageResizer can make your life much eaiser. Find out more at imageresizing.net.


I run Imazen, a tiny software company that specializes in web-based image processing and other difficult engineering problems. I spend most of my time writing image-processing code in C#, web apps in Ruby, and documentation in Markdown. Check out some of my current projects.

More articles