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!

15 Comments

Comments have been disabled for this content.