Using ASP.NET and Jcrop to crop images online

Cropping images in ASP.NET is easy task to do if you use right tools. In this posting I will introduce how to crop images using Jcrop and System.Drawing namespace classes. What we are building is simple and user-friendly image cropping interface that also demonstrates some simple features of Jcrop. Believe me, your users will love it!

Jcrop is jQuery based library that brings crop margins selection to client side. Before starting you need two (free) JavaScript libraries:

After downloading them create new ASP.NET Web Application project and unpack those libraries to js directory. Also copy file js/Jcrop/css/Jcrop.gif to root folder of your project and add image you want to crop to same folder.

Expected result

As a first thing we will show image to user and some informative labels under image. And, of course, there is button for cropping.

Image before crop

You can see those values changing under image when you change the size or location of cropping are box.

When user clicks crop button then image will be cropped and shown to user. In our current case the result will be something like shown on following screenshot.

Image after crop

You can crop image again and again and again until you get the result you like.

Code

This is my ASP.NET form. I have to warn you that my JavaScript is written just to make it work and it needs some more cosmetics if you plan to use this code in real development. So, no hard feelings, okay?

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Crop.aspx.cs" Inherits="BlogExamples.Crop" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" 
>
<
head id="Head1" runat="server">
    <title></title>
    <link rel="Stylesheet" type="text/css" href="js/Jcrop/css/jquery.Jcrop.css" />
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="js/Jcrop/js/jquery.Jcrop.min.js"></script>
    <script type="text/javascript">
        var editorID = '<%= _imageEditor.ClientID %>'
;
        jQuery(
function
() {
            jQuery(
'#'
+ editorID).Jcrop({
                onChange: showCoords,
                onSelect: showCoords
            });
        });

       
function
showCoords(c) {
           
var tdX = document.getElementById('tdX'
);
           
var tdY = document.getElementById('tdY'
);
           
var tdWidth = document.getElementById('tdWidth'
);
           
var tdHeight = document.getElementById('tdHeight'
);

            tdX.innerHTML = c.x;
            tdY.innerHTML = c.y;
            tdWidth.innerHTML = c.w;
            tdHeight.innerHTML = c.h;

           
var xField = document.getElementById('<%= _xField.ClientID %>'
);
           
var yField = document.getElementById('<%= _yField.ClientID %>'
);
           
var widthField = document.getElementById('<%= _widthField.ClientID %>'
);
           
var heightField = document.getElementById('<%= _heightField.ClientID %>'
);

            xField.value = c.x;
            yField.value = c.y;
            widthField.value = c.w;
            heightField.value = c.h;
        }
   
</script
>
</
head
>
<
body>
    <form id="form2" runat="server">
    <div>
    <asp:Image runat="server" ID="_imageEditor" ImageUrl="MY_FILE.JPG" />
    </div>
    <table border="0" cellpadding="2" cellspacing="0">
    <tr>
    <td>x:</td>
    <td id="tdX">-</td>
    <td>y:</td>
    <td id="tdY">-</td>
    <td>width:</td>
    <td id="tdWidth">-</td>
    <td>height:</td>
    <td id="tdHeight">-</td>
    <td><asp:Button runat="server" ID="_cropCommand" onclick="_cropCommand_Click" Text="Crop" /></td>
    </tr>
    </table>
 
   
<input type="hidden" runat="server" id="_xField" />
    <input type="hidden" runat="server" id="_yField" />
    <input type="hidden" runat="server" id="_widthField" />
    <input type="hidden" runat="server" id="_heightField" />
 
   
</form
>
</
body
>
</
html
>

And here is code-behind file of my form. If you plan to use this code in real development then you must validate values of crop margins before using them with drawing methods. Also you need error handling and you have to make sure that all objects will be disposed correctly.

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using
System.Web.UI;
 

namespace
BlogExamples
{
   
public partial class Crop : Page
    {
       
protected void _cropCommand_Click(object sender, EventArgs
e)
        {
           
var x = int
.Parse(_xField.Value);
           
var y = int
.Parse(_yField.Value);
           
var width = int
.Parse(_widthField.Value);
           
var height = int
.Parse(_heightField.Value);
 
           
using(var photo = Image.FromFile(Server.MapPath("MY_IMAGE.JPG"
)))
           
using (var result = new Bitmap
(width, height, photo.PixelFormat))
            {
                result.SetResolution(
                        photo.HorizontalResolution, 
                        photo.VerticalResolution);
 
               
using (var g = Graphics
.FromImage(result))
                {
                    g.InterpolationMode = 
                        
InterpolationMode
.HighQualityBicubic;
                    g.DrawImage(photo,
                        
new
Rectangle(0, 0, width, height),
                        
new
Rectangle(x, y, width, height),
                        
GraphicsUnit
.Pixel);
                    photo.Dispose();
                    result.Save(Server.MapPath(
"MY_IMAGE.JPG"));
                }
            }
        }
    }
}

Well, that’s it. If you have any troubles running this code then please drop me a comment here and I will try to help you.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    16 thoughts on “Using ASP.NET and Jcrop to crop images online

    • November 3, 2009 at 8:10 am
      Permalink

      lol !

      I’m writing a toturial like this, but you are faster than me :)

      thanks for sharing ;)

    • November 3, 2009 at 8:12 am
      Permalink

      why you are using : document.getElementById

      you can use jQuery selectors.that make your code faster.

      use this :

      var tdX = $(‘#tdX’);
      var tdY = $(‘#tdY’);
      var tdWidth = $(‘#tdWidth’);
      var tdHeight = $(‘#tdHeight’);

    • November 3, 2009 at 2:24 pm
      Permalink

      From MSDN:

      “Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions.”

    • November 3, 2009 at 4:42 pm
      Permalink

      Thanks for feedback, guys :)

      David, I am not creating ASP.NET service here but ASP.NET web application. I have read from some sources that System.Drawing namespace is not supported (by Microsoft) under ASP.NET but this far world practice has shown that you can use this namespace as long as you use resources reasonably.

    • November 11, 2009 at 9:00 pm
      Permalink

      Hi abhishek!

      What is the format of file you are trying to crop?
      Do you get exceptions?
      Have you made modifications to code?

    • March 19, 2010 at 6:14 pm
      Permalink

      Thats was useful. I want to put validation that image size cannot go beyond specified range, also it cannot shrink beyond specified range. Any idea, how can i do that?

    • April 11, 2010 at 9:26 am
      Permalink

      Nice one.. it worked for me as well.. Thanks do writing such good articles… :)

    • July 11, 2010 at 4:22 am
      Permalink

      Thanks for the very nice story

    • August 12, 2010 at 5:07 am
      Permalink

      This line var x = int.Parse(_xField.Value);
      is giving error “input string was not in a correct format”
      also pls tell me from where jQuery(function() and
      function showCoords(c) functions are called.

    • September 5, 2010 at 10:41 am
      Permalink

      ‘Image’ is an ambiguous reference between ‘System.Web.UI.WebControls.Image’ and ‘System.Drawing.Image’

    • November 17, 2010 at 11:09 am
      Permalink

      thanks thanks and thanks a lot………….

    • January 17, 2011 at 8:33 pm
      Permalink

      You are a star , thnx sir :)

    • May 25, 2011 at 10:41 am
      Permalink

      it’s not working in the deployed sever whichis 2003 server. But it’s working fine in local machine..

    • September 8, 2011 at 8:50 am
      Permalink

      can i use it in mit licence?

    • December 16, 2011 at 10:03 am
      Permalink

      Thank u for the code

    Leave a Reply

    Your email address will not be published. Required fields are marked *