Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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.

ASP.NET + Jcrop: Selecting cropping area

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.

ASP.NET + Jcrop: Image after cropping

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 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="form1" 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.


kick it on DotNetKicks.com pimp it 顶 Progg it Shout it
vote it on WebDevVote.com Shout it!

Comments

Masoud said:

lol !

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

thanks for sharing ;)

# November 3, 2009 3:10 AM

Masoud said:

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 3:12 AM

David Douglass said:

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 9:24 AM

DigiMortal said:

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 3, 2009 11:42 AM

DigiMortal said:

Hi abhishek!

What is the format of file you are trying to crop?

Do you get exceptions?

Have you made modifications to code?

# November 11, 2009 4:00 AM

dotnetguts said:

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?

# March 19, 2010 2:14 PM

Sangeeta J said:

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

# April 11, 2010 5:26 AM

Supriyo Chakraborty said:

Thanks for the very nice story

# July 11, 2010 12:22 AM

Shweta said:

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.  

# August 12, 2010 1:07 AM

vd said:

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

# September 5, 2010 6:41 AM

krishna said:

thanks thanks and thanks a lot.............

# November 17, 2010 6:09 AM

Mahmoud said:

You are a star , thnx sir :)

# January 17, 2011 3:33 PM

Buddanna said:

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

# May 25, 2011 6:41 AM

秦仕川 said:

can i use it  in mit licence?

# September 8, 2011 4:50 AM

priyanka said:

Thank u for the code

# December 16, 2011 5:03 AM