Upload and Crop Images with jQuery, JCrop and ASP.NET

I got given jQuery In Action for Christmas. By nature, I'm kind of a late adopter, and I'm already regretting this fact. jQuery has been around for some time, and I wished I had looked at it sooner. It's a fantastic library that really simplifies Javascript development, and is already attracting a goodly number of plug-ins. JCrop is one such, and while it hasn't yet reached version 1.0, it is remarkably easy to use as a web based image cropper. Here's how to put jQuery, JCrop and a FileUpload control together to allow users to upload images and crop them.

If you haven't already done so, you will need to download the jQuery library. The current version, and therefore the one that is used in this sample is 1.2.6. Then you need to get hold of the files for JCrop. The download also includes a number of samples which show the features offered by JCrop, such as specifying a fixed aspect or minimum and maximum sizes etc, but this sample uses the default out-of-the-box settings. Be sure to get version 0.9.8 or later, as previous versions had trouble working with IE8 when compatability mode is switched off. Finally you could probably do with making sure that your VS 2008 or VWD 2008 has SP1 applied together with this hotfix which enables Intellisense on javascript files, including jQuery and JCrop. You need to get hold of the vsdoc.js file too.

This example consists of a single page. It caters for three actions: first, the user is presented with an Upload control to locate and upload their image; second, they will be presented with their uploaded image ready for cropping; and finally, they are presented with the cropped result. To accommodate this, three Panel controls are added to the page. The first, pnlUpload contains the FileUpload control and a button linked to an event handler for its click event. The second, pnlCrop contains an Image control and a button - again, linked to an event handler for its Click event. It also contains 4 HiddenField controls. They will be explained shortly. The Panel's Visibility is set to false. The final Panel, pnlCropped contains an Image control, and its Visibility is also set to false.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadAndCrop.aspx.cs" Inherits="UploadAndCrop" %>

 

<!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>

 

</head>

<body>

  <form id="form1" runat="server">

  <div>

    <asp:Panel ID="pnlUpload" runat="server">

      <asp:FileUpload ID="Upload" runat="server" />

      <br />

      <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />

      <asp:Label ID="lblError" runat="server" Visible="false" />

    </asp:Panel>

    <asp:Panel ID="pnlCrop" runat="server" Visible="false">

      <asp:Image ID="imgCrop" runat="server" />

      <br />

      <asp:HiddenField ID="X" runat="server" />

      <asp:HiddenField ID="Y" runat="server" />

      <asp:HiddenField ID="W" runat="server" />

      <asp:HiddenField ID="H" runat="server" />

      <asp:Button ID="btnCrop" runat="server" Text="Crop" OnClick="btnCrop_Click" />

    </asp:Panel>

    <asp:Panel ID="pnlCropped" runat="server" Visible="false">

      <asp:Image ID="imgCropped" runat="server" />

    </asp:Panel>

  </div>

  </form>
</body>
</html>

 

Some Javascript is required. If you were starting this kind of application from scratch, it would need an awful lot of javascript. However, jQuery's real power is illustrated by just how little javascript this page actually needs. To make use of both jQuery and JCrop, they need to be linked to in the head section of the page, along with the css file that comes as part of the JCrop download. The link to jQuery makes use of the copy available from the Google Ajax API Library for better caching and faster downloading:

 

<link href="css/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="script/jquery.Jcrop.pack.js"></script>

 

All that's now needed to activate JCrop is a handful of lines of Javascript, which go within <script> that's in the head of the document below the previous lines:

 

<script type="text/javascript">

  jQuery(document).ready(function() {

    jQuery('#imgCrop').Jcrop({

      onSelect: storeCoords

    });

  });

 

  function storeCoords(c) {

    jQuery('#X').val(c.x);

    jQuery('#Y').val(c.y);

    jQuery('#W').val(c.w);

    jQuery('#H').val(c.h);

  };

 

</script>

 

It really is that simple. Jcrop has been applied to the image that has the id of imgCrop (the one in pnlCrop), and an event handler has been added to the select event of the cropper. This will happen when the user has completed selecting the area of the image they want to keep. The handler makes use of the storeCoords function, which sets the values of the HiddenFields, passing them the x and y coordinates of the top left of the selection relative to the image, and the width and height of the selection. That's all ASP.NET needs to know in order to process the image on the server. Now on to the server-side code.

There are 4 namespaces that need to be referenced in additional to the default ones that a new Web Form brings in:

 

using System.IO;

using SD = System.Drawing;

using System.Drawing.Imaging;

using System.Drawing.Drawing2D;

 

Since we will be working with instances of System.Drawing.Image as well as System.Web.UI.WebControls, which also has an Image class, I have aliased System.Drawing.Image, which will permit me to use a shorthand to reference the System.Drawing.Image classes. The first four lines of the code-behind simply set a variable to point to the file system path of the directory in which uploaded images will be stored, and show an empty Page_Load method:

 

String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";

 

protected void Page_Load(object sender, EventArgs e)

{}

 

The next section covers the event handler for the Upload button click:

 

protected void btnUpload_Click(object sender, EventArgs e)

{

  Boolean FileOK = false;

  Boolean FileSaved = false;

 

  if (Upload.HasFile)

  {

    Session["WorkingImage"] = Upload.FileName;

    String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();

    String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };

    for (int i = 0; i < allowedExtensions.Length; i++)

    {

      if (FileExtension == allowedExtensions[i])

      {

        FileOK = true;

      }

    }

  }

 

  if (FileOK)

  {

    try

    {

      Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);

      FileSaved = true;

    }

    catch (Exception ex)

    {

      lblError.Text = "File could not be uploaded." + ex.Message.ToString();

      lblError.Visible = true;

      FileSaved = false;

    }

  }

  else

  {

    lblError.Text = "Cannot accept files of this type.";

    lblError.Visible = true;

  }

 

  if (FileSaved)

  {

    pnlUpload.Visible = false;

    pnlCrop.Visible = true;

    imgCrop.ImageUrl = "images/" + Session["WorkingImage"].ToString();

  }

}

 

This code should be pretty familiar to anyone who has worked with the FileUpload control before. It simply checks to see if a file has been submitted, and ensures that it is of the right type. Then it saves the file to disk and the name of the file to a Session variable. Once the image has been saved, it is set as the ImageUrl of the Image control which has been targeted by JCrop and makes the containing Panel visible.

The next section covers the event handler for the Crop button:

 

protected void btnCrop_Click(object sender, EventArgs e)

{

  string ImageName = Session["WorkingImage"].ToString();

  int w = Convert.ToInt32(W.Value);

  int h = Convert.ToInt32(H.Value);

  int x = Convert.ToInt32(X.Value);

  int y = Convert.ToInt32(Y.Value);

 

  byte[] CropImage = Crop(path + ImageName, w, h, x, y);

  using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))

  {

    ms.Write(CropImage, 0, CropImage.Length);

    using(SD.Image CroppedImage = SD.Image.FromStream(ms, true))

    {

      string SaveTo = path + "crop" + ImageName;

      CroppedImage.Save(SaveTo, CroppedImage.RawFormat);

      pnlCrop.Visible = false;

      pnlCropped.Visible = true;

      imgCropped.ImageUrl = "images/crop" + ImageName;

    }

  }

}

 

This section references the image name from the Session variable, and then declares a number of integers that get their values from the HiddenFields that JCrop wrote to when the user selected the area they wanted to keep.

It then calls a method called Crop() to perform the actual cropping of the image (more of which soon). Crop() returns a byte array, which is written to a MemoryStream so that it can be used and converted back to an Image. This is then prefixed with the word "crop" in its name before being saved to disk and displayed to the user.

The Crop() method is below:

 

static byte[] Crop(string Img, int Width, int Height, int X, int Y)

{

  try

  {

    using (SD.Image OriginalImage = SD.Image.FromFile(Img))

    {

      using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))

      {

        bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);

        using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))

        {

          Graphic.SmoothingMode = SmoothingMode.AntiAlias;

          Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

          Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

          Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel);

          MemoryStream ms = new MemoryStream();

          bmp.Save(ms, OriginalImage.RawFormat);

          return ms.GetBuffer();

        }

      }

    }

  }

  catch (Exception Ex)

  {

    throw (Ex);

  }

}

 

This might at first glance look a little daunting to beginners, but most of the code just sets properties that affect the quality and appearance of the resulting image. What it does is to simply use the original image as a base from which a new image is drawn, and then save it to a MemoryStream object, which is returned as a byte array to be consumed by the calling code above. You should take note of the using blocks that are employed in this method. They ensure that Image, Bitmap and Graphics objects are all disposed of when the method is done. There's nothing worse than finding that your busy web app has slowed to a crawl through unreleased resources.

Oh, and thanks go to my cat, Alfie, for kindly agreeing to model for this exercise.

Shout it

 

Date Posted: Monday, January 5, 2009 1:54 PM
Last Updated: Wednesday, November 18, 2009 7:37 PM
Posted by: Mikesdotnetting
Total Views to date: 225664

113 Comments

Friday, February 20, 2009 7:43 PM - Jorge Salinas

Nice article man, Jquery rocks!

Friday, February 20, 2009 11:06 PM - Siraj

can i am able to do resige and crop or crop and resige Image?

Saturday, February 21, 2009 1:43 PM - pizimiao

thanks

Saturday, February 21, 2009 6:07 PM - Mike

@Siraj

???

Sunday, February 22, 2009 4:59 AM - Asif

Good article, Thanks

Sunday, February 22, 2009 4:45 PM - hoanghieu

Thank. Content VeryGood. Thanks....

Monday, February 23, 2009 10:17 AM - Tung

Thanks a lot. Very helpful article :)

Tuesday, February 24, 2009 9:28 AM - Anas

very good article thanks

Tuesday, February 24, 2009 10:58 AM - ntnikolov

Thanks man. Very useful article -:)

Wednesday, February 25, 2009 12:53 AM - Kaypee

Great article, a must read ^_^

Wednesday, February 25, 2009 8:17 AM - Jigar

Thanks, very useful article

Thursday, February 26, 2009 5:56 AM - Pushkar

Hey hey man...thanks its very useful for the asp.net developer who really seeking Image Scrop functionality whille uploading image...Thanks man..i have checked its working properly in FireFox but not in IE..I hope you will lookafter for the IE issue..Thanks again.

Thursday, February 26, 2009 6:54 PM - Mike

@Pushkar

It works fine in IE for me.

Thursday, February 26, 2009 8:34 PM - Siraj

I want to do resize of image and then to do crop or to do crop and then resize cropped image

Thursday, February 26, 2009 9:00 PM - Mike

@Siraj,

That's fine. Just change the order of the code to what you need.

Saturday, February 28, 2009 5:27 PM - Sandy

nice article men..

Wednesday, March 4, 2009 5:25 AM - Ashish

Hi, Good Article but if if upload a big image the image cover the whole page

Wednesday, March 4, 2009 7:37 AM - Mike

@Ashish

Yes - if you try to display a big image, it will appear ermmm.... Big. If you want to reduce the image dimensions, you can do this before uploading, or you can do so as you initially save the image to the file system, but before you display it for cropping.

Monday, March 16, 2009 7:49 AM - Minhaj Mansuri

Thanks A Lot , Nice Article
If You Want To Crop Default Selected Portion Without Touching The Crop Portion Then It Give Error

Tuesday, March 17, 2009 7:36 AM - Mike

@Minhaj

The reason that you get an error is that there are no default values in the hidden fields when the page first loads. Either set some, or handle the exception in your server-side code.

Wednesday, March 18, 2009 1:16 PM - venkatesh

hi!
it is very code but it is not work in my site i am using master page

Wednesday, March 18, 2009 1:53 PM - Mike

@venkatesh,

I suspect you have done something wrong. My guess would be that you are trying to reference controls that have had their names changed by INamingContainer (Google it - or put it in the search box at the top of the page), but I could be wrong. If you can't work it out, post a question to the forums at www.asp.net.

Friday, March 20, 2009 5:25 AM - jithu

Very nice article.. image quality is superb after cropping.. !!!!

Friday, March 20, 2009 11:08 AM - mark

Is there a sample download for this post at all? Cheers...

Friday, March 20, 2009 7:44 PM - Mike

@Mark

I don't do downloads as a rule. However, all the code you need is in the article.

Monday, March 23, 2009 5:31 PM - mark

OK Mike. No problem. Thanks for the repsonse anyway. :-)

Tuesday, March 24, 2009 1:27 PM - Dan Sylvester

Thanks for the link to the google api library. I might use it.

Thursday, March 26, 2009 5:48 AM - anjan

plz anyone help me .when i applied this code , i hav an error of uploading an image ..the error is-------

**File could not be uploaded.Could not find a part of the path 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\UploadAndCrop\images\cropped.jpg'.

can anyone fix the problem???

Sunday, March 29, 2009 4:20 AM - Hamid

Please write article with code which take the images from the folder or database and then display those images using jquery

Monday, March 30, 2009 4:34 PM - mansoor

Nice article.ver useful.
If possible palace a small article like a project.
It will help more(i think)

Friday, April 3, 2009 6:02 PM - Marleny Nunez

Excellent article and great usage of the JCrop plug-in. I must add for the newbies that the code is not all complete for just copy/pasting. It requires at least basic understanding of dot net applications.
This is what is missing on the explanation for the uninitiated:
1. Save the first block of code as UploadAndCrop.aspx
2. Add the second and third blocks of code to the head section of the aspx file. this is explained in the article.
3. Save the rest of the code as UploadAndCrop.aspx.cs
4. On the .cs file, replace the lines
using System.IO;
using SD = System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

with this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using SD = System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

public partial class UploadAndCrop : System.Web.UI.Page
{


5. Add a closing bracket "}" at the end of the .cs file to wrap the class we just added.
}

Good luck and happy programming!

Sunday, April 5, 2009 9:40 AM - Warren Tan TL

i realized that the value is empty... aikz

Wednesday, April 8, 2009 4:39 PM - Mark Brown

Hi,

I was just wondering if there is a way to set the crop area to a set width and height, so that the user just moves a square of 250 x 250 px but doesn't have the option the resize it?

Thanks,

Mark

Friday, April 10, 2009 6:00 PM - Mike

@Mark Brown

The options that you need to set this are detailed in the JCrop manual: http://deepliquid.com/content/Jcrop_Manual.html#Setting_Options

Saturday, April 11, 2009 1:23 PM - Vinicius

Nice article but can you give us a 'download this project' link ? :)
Thanks!

Sunday, April 12, 2009 10:42 AM - sourav

.every thing is al rite but plz clear me the CSS AND JAVAscript part(second block of code) it does not work..

Sunday, April 12, 2009 12:16 PM - Mike

@Sourav

Yes it works. I tested it before posting it in this article. What I think you mean is that *your* implementation of the code doesn't work. If you want quick help, I suggest you go to the forums at www.asp.net and post a question there.

Monday, April 13, 2009 10:25 AM - Umesh

Hello Mike

Its really nice article ..

But how to reset the cropper. (i.e., If i provide one more reset button and i want it reset the cropper by clicking on this button ).

Tuesday, April 14, 2009 7:12 AM - Mike

@Umesh

I refer you to the link I gave Mark Brown in my reply to his question which details the options you can set. The one you want is setSelect.

Monday, April 20, 2009 3:47 PM - George Grubar

Very cool Mike.....jquery is super-rich in functionality. Client-side scripting kicks butt these days.

I developed a similar crop image solution using Classic ASP and Javascript (might be of use to others)

http://www.imagecowboy.com/articles/how_to_crop_images_using_asp_and_javascript.asp

Monday, April 20, 2009 7:09 PM - Mike

@George

That's exactly the same javascript cropper I used in an old classic ASP application before I came across jQuery. I even recognise the sample image of the castle!

Friday, May 1, 2009 6:15 PM - Nikolaj

@Mikesdotnetting
The problem mentioned by Pushkar on 26 February 2009 05:56, does happend on some version of IE - so it probably haven't occurred to you :)

Anyhow, the problem is that (some versions of) IE sends the entire filepath (ie.: "C:\Pictures\mypicture.jpg") - not only the filename (ie.: "mypicture.jpg"), as one expects. Therefore you will get an invalid path in the end (ie.: "{PhysicalApplicationPath}images\C:\Pictures\mypicture.jpg"), then trying to save the image.

@Pushkar + @Mikesdotnetting
Try change the line:
Session["WorkingImage"] = Upload.FileName;
to:
Session["WorkingImage"] = Path.GetFileName(Upload.FileName);

Then the problem should be solved :)

Monday, May 4, 2009 7:29 PM - Mike

@Nikolaj,

Thanks for the clarification of the issue, and the solution.

Friday, May 8, 2009 8:58 AM - Rajeev

Thnks,
It's Great

Friday, May 15, 2009 7:21 AM - Rajesh

This is a great code man. It help me a lot and saves my time.

Thnk Mikesdotnetting.

Tuesday, May 19, 2009 10:17 PM - Python

Hi, I keep getting "input string format" error below. The only difference between this example is that I have this in a subfolder of my application.

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:

Line 111: string ImageName = Session["WorkingImage"].ToString();
Line 112:
Line 113: int w = Convert.ToInt32(W.Value);


Wednesday, May 20, 2009 9:40 PM - Mike

@Python

You need ot find out what value W is at that point. Setting a breakpoint will help you.

Monday, May 25, 2009 4:57 AM - Ramona

Hi, I am having the same problem as @Python.

I keep getting "input string formati" error below. I am using Internet Explorer 8. Is that an issue?

Exception Details: System.FormatException: Input string was not in correct format.

Source Error:

Line 111: string ImageName = Session["WorkingImage"].ToString();
Line 112:
Line 113: int w = Convert.ToInt32(W.value);

I have tried putting Labels on the aspx page and changing the text. It changes as I move the box or change the selection. However, when I click the button crop, those values don't get passed to the event handler?

What am I not doing?

Monday, May 25, 2009 8:13 PM - Mike

@Ramona

I can only repeat what I suggested to Python. Some simple debugging will help you, becaise you need to find out what value W is passing at the moment that causes the error. ?Use the VS/VWD debugger or use FireFox and install Firebug and look at the values that are being passed.

Tuesday, May 26, 2009 7:15 PM - Ramona

Hi! Thanks for the feedback. Actually the issue was that I am using a MasterPage format, so the Hidden TextBox ID's were getting munged. I had to use the <%= X.ClientID %> workaround to get the values.

Next issue is that I am using shared hosting, and can't yet save the file to the FileSystem. Works great on localhost and production equipment.

Is there code to save the first image to a database, and then read it back from there, instead. I am using Visual Studio 2008 Professional and C#.

Thank you for all of your great work!

Wednesday, May 27, 2009 8:55 AM - Mike

@Ramona

Thanks for clarifying your issue and providing the solution. I'll amend the article to point this out. As far as saving the image to the database instead of the filesystem is concerned, there are thousands of samples all over the web. Here's one:

http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=414

Thursday, June 4, 2009 12:03 PM - Mahesh Chavda

Great article man!!...

It's really really helpful.

Thanks

Saturday, June 6, 2009 4:41 PM - Jon Stranger

A very helpful article. In my case, however, I am using a dynamic image (using the Microsoft.Web.GeneratedImage.dll) inside an ASP.NET AJAX UpdatePanel. This works fine the first time, but after a partial update Jcrop no longer works - seemingly gets 'unwired'! I know this is not an issue for your code but would be interested to hear if you or any one else has tried using Jcrop in combination with an UpdatePanel. Or if there is a recommended way of 'rewiring' Jcrop (or any other Jquery plugin for that matter).

Jon

Friday, June 26, 2009 12:44 PM - santhosh kumar

Its a nice article. In my point of view if you upload a image with the file name having spaces means its not working and also some works to do.
But its very very useful thing for upload and crop image in ,net

Wednesday, August 12, 2009 5:50 AM - Felipe Lima

Hello,
I found your code of great value and actually used it to accomplish something similar using jCrop and ASP.NET and ModalPopupExtender.
I blogged about it at http://blog.felipel.com/post/Upload-and-Crop-Images-with-ASPNET-and-jCrop-Revisited!.aspx

Also, I'd like to make a comment about the method that actually crops the image. I believe you can return the image stream directly, instead of transfering the whole byte array into memory and then returning it, which might be an expensive operation, depending on the image size. I'm using the streamed version of your method. The only difference is that it returns "ms" itself, instead of "ms.GetBuffer()".

Thanks for sharing!
Felipe

Friday, August 28, 2009 2:19 AM - Nestcn

Thanks!
Nestcn

Saturday, August 29, 2009 10:54 AM - Damodharan

All of your coding was working properly. If i include my master page to my application it doesn't working how configure that javascript files.

Please Help Me!

Thanks in Advance

Saturday, August 29, 2009 8:32 PM - Mike

@Damodharan

Read Ramona's comment.

Wednesday, September 2, 2009 6:52 AM - stanly

Input string was not in a correct format.. I'm getting this error.. help me

Saturday, October 3, 2009 11:33 AM - Nageswaran

Hi Mikes,
I am using this coding, after uploading the image. I was unable to crop that image. So please tell me where i am going wrong.

Saturday, October 3, 2009 11:20 PM - Mike

@Nageswaran

There could be a million reasons why you are experiencing problems. Post a question to the www.asp.net forums and please provide a full description of your problem. For example, what exactly do you mean by "unable to crop the image"? Does it fail to appear? Do you get an error message? If so, what is it and what line causes it?

Monday, October 5, 2009 1:41 PM - raaz

ya it's look nice

Tuesday, October 6, 2009 8:59 AM - gtaure

Hi,

Do you have any way of resizing/cropping it in proportional size?

Thanks for the code BTW.

Tuesday, October 6, 2009 10:15 AM - Mike

@gtaure

The actual size of the cropped image is taken from the selected area and passed in here:

using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))

If you want to change the Width and Height values, you can do so by intercepting them before they are passed into the Bitmap() constructor. If, for example, you decide that Width must be 200, then you would calculate what 200 is as a proportion of the actual width of the selected area, and use that proportion to alter the height. Something like this:

float newWidth = 200;
float ratio = newWidth / Width;
float newHeight = Height * ratio;

Then you can pass the new values into the Bitmap() constructor:

using (SD.Bitmap bmp = new SD.Bitmap(Convert.ToInt32(newWidth), Convert.ToInt32(newHeight)))


Wednesday, November 18, 2009 12:22 PM - sam

i have checked its working properly in FireFox but not in IE..I hope you will lookafter for the IE issue..its urgent
Thanks

Wednesday, November 18, 2009 7:33 PM - Mike

@sam

Thanks for pointing that out to me. During testing, I had IE8 compatability mode switched on. You are correct in that it doesn't work with JCrop 0.9.7 or earlier when Compatability Mode is switched off. A patch was released by the authors of JCrop and version 0.9.8 fixes the problem.

Go here: http://code.google.com/p/jcrop/downloads/list to get the latest version.

Thursday, December 10, 2009 7:38 AM - Varun Anand

you rock Mikesdotnetting. i wish someday i will also be able to do coding like you.
cheers

Wednesday, January 20, 2010 3:12 PM - Gaston

Here is a plugin that can be useful
http://www.cropzoom.com.ar

Wednesday, March 3, 2010 12:25 PM - vamsi

Hi

how to download js files i have able to upload image then java script is not working. how to download this "script/jquery.Jcrop.pack.js" ?

Tuesday, April 6, 2010 2:10 PM - silpa

Thanks! Nice and simple code.

Monday, May 3, 2010 2:12 PM - Ahmed

when i used a masterpage then use a page thats inhiret from it .
its told me that the hidden field dosen't contain value
could you plz tell us how we work with masterpage method

Friday, May 7, 2010 7:17 PM - mark

Fantastic article. This is just what I was looking for. If I could buy you a drink through the comment form, I'd do it!

Sunday, June 13, 2010 3:24 PM - ayan

It worked well in a web page but failed when used in content page of master page.

Monday, June 14, 2010 4:52 PM - Mike

@ayan

Read ramona's comment above.

Monday, June 14, 2010 8:11 PM - ayan

Hi, Actually I have implemented your code while saving an image file in the sql server 2008 database, retrieved it and then used cropping and saved it in the database using asp .net. It worked well.
But when using with master page that has total sitemap based menu and security(not asp .net default security) save the image, retrieve it from database but the cropping panel not showing.

Monday, June 14, 2010 8:28 PM - Mike

@ayan

I can't begin to guess where your problem lies. I suggest you post a question to the forums at www.asp.net with details of what you have done and what the problem is.

Saturday, July 3, 2010 7:42 PM - Guarav

its working 100% and such a great thought for me.............

Thanks

Thursday, July 8, 2010 3:03 PM - Hennie

Working for me... but....

Does anyone have an example on how I can resize the image to a max of 600 x 480 before uploading a photo to the server?



Thursday, July 8, 2010 6:40 PM - Mike

@Hennie

Resizing images on the user's PC is the jobn of a client side application. There's nothing that ASP.NET, the browser or javascript can do for you.

Thursday, July 15, 2010 1:21 PM - Peddiraju

Hi Great article it is really help alot me to finish My Task .but sme Logic required to apply this Article Code.

thanks

Wednesday, August 4, 2010 11:25 AM - Dharmesh

Hi

can i use this under masterpage .......
how to use crop image under masterpage

please help me

Tuesday, August 17, 2010 3:14 PM - kavitha

Image crop is working in fire fox but its not working in IE browsers as per above comments i downloaded jquery.Jcrop-0.9.8 but i dont how to use this or integrate with the above code. please help us

Tuesday, August 17, 2010 5:55 PM - Mike

@kavitha

Just replace the old Jcrop file with the new one. Nothing else is needed. You might have to refresh the page so that your temp cache is cleared out and the file updated.

Monday, September 27, 2010 7:31 AM - manjay kumar

thanks

it is to good for beginner

Thursday, September 30, 2010 10:38 AM - Ibrahim Sidat

Great article! I got a PHP version of JCop but no ASP. This article was very helpful to me.

Monday, November 15, 2010 1:40 PM - Dhanunjai

How to implement this is master page.............

Wednesday, December 1, 2010 4:26 PM - Ravi

Thanks, you did a great job.

Friday, December 3, 2010 1:43 PM - Eduardo Elarrat

Great article. But what if the image has a fixed size? I mean, in this example, the image can take over the whole page if its big enough, so I thought of having the image sizes a limit (ie. Width 640px, Height 480px). When i do this, the jcrop starts missing the cropping bounds, so that the cropped image is different from my crop selection. Is there a way to do this as I expect?

Friday, December 3, 2010 1:56 PM - Mike

@Eduardo

I suppose it depends on how you are applying you limit.

Tuesday, January 11, 2011 1:36 PM - Rahul Khakse

it amazing thank you for adding sir

Friday, February 11, 2011 4:12 AM - Kanagaraj

It's Working Fine....Thanks.....You given great Article...

Monday, April 4, 2011 12:52 PM - Antonio

Hi this don't work under masterpage. The same code on a simple page works ok. Any help?
Thanks for that good work

Wednesday, April 6, 2011 10:34 AM - elie

Hey Guys, I implemented your code and it looks great.
But I am getting an error, in case I clicked "Crop" button without selecting part of the image
Please advise

Wednesday, April 6, 2011 3:39 PM - Mike

@elie

Look at previous comments. Your issue is covered there - you need to check that the HiddenFields have values in them.

Wednesday, April 6, 2011 3:45 PM - Mike

@Antonio

Your issue is also covered in previous comments. You need to use Control.ClientID to work with MasterPages

Saturday, August 6, 2011 4:47 PM - Santosh

It's very nice Working Fine....Thanks.....

Monday, May 7, 2012 12:11 PM - sandy

HI,
Nice article to explain about crop image. But here your are storing image in a bitmap format. When you store a bitmap image it will take more size. But is it possible to store a JPEG image so that we can reduce the size.

Tuesday, May 8, 2012 8:52 PM - Gregory F.

Thank you very much sir. The most useful article about image cropping on the web using all the latest and greatest technologies out there now.

Friday, June 29, 2012 9:57 AM - Thuy

Thanks! Good article

Thursday, August 16, 2012 7:47 AM - TheDonSansone

sandy,
I think you are mistaken in the storing of the cropped image. The code uses 'InterpolationMode.HighQualityBicubic' after it is cropped and saves out the resulting image in the same format the client uploaded as long as it matches one of the format params earlier in the code.

The cropper itself uses bitmap format only whilst cropping.

I have tested this and originally optimized images uploaded - then cropped to full size of original image, are only marginally larger than the original image (due to the QualityBicubic setting above of HIGH).

Works a treat Mike, if a little clunky, but great proof of concept.

The above should be improved by creating two storage locations. A 'tmp' for the working image being cropped and a different folder for the cropped image, as currently the folder saves both original and cropped in the same folder.

Suggested:
String tmppath = HttpContext.Current.Request.PhysicalApplicationPath + "tmp\\";

String imgpath = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";

Then use 'tmppath' in the upload and crop methods instead of 'path'

Then use 'imgpath' to store the finished image.
This allows easy identification and removal if necessary of original uploads.

;) Martin.

Wednesday, October 17, 2012 10:46 AM - keyvan

thank is very good and usefull

Thursday, October 18, 2012 4:10 PM - Sakthi

Hi this is working good in mozila and google chrome perfectly but it should not work in IE.
I am using jquery 0.9.10 version only
can u please give whats the reason?

Saturday, October 20, 2012 7:58 AM - Mike

@Sakthi,

You need version 0.9.8 or later

Sunday, February 17, 2013 11:19 AM - Lijin John

sir I a beginner with asp.net.
My problem is that, When I use the following code I get an Error Message.
Let me paste the code for You
byte[] cropimage = Crop(path+image,a,b,c,d);
When i type this code I get a RED line mark stating the error under the word--- Crop-----.
can you please explain the reason why i get this type of error.
I use VS2010 and i have used all the namespaces that u have asked to mention

Thursday, March 7, 2013 1:17 PM - madhu

hello can you give download link

Sunday, March 31, 2013 9:58 PM - Garry

This is an excellent article! Nice one @Mikesdotnetting.

Wednesday, May 29, 2013 2:06 PM - Kürşat Vuruşan

Thanks! Nice and simple code.

Monday, July 29, 2013 6:10 AM - Windyyyy

Very nice article. It works great on Chrome, Firefox but not in IE. I am using Jcrop v0.9.12 (build: 20130202) and IE version is 10.0.9200.16635. Jcrop selection in image doesn't work in IE. Can you pls shed some light on this problem if you know any workarounds for IE. Your help is appreciated.

Monday, August 19, 2013 8:00 PM - djv

Thanks, works perfectly!!!! Also on IE version 10.0.9200.16660.
Question to the people having trouble here: are you using the most recent jquery version?

Tuesday, August 20, 2013 8:15 AM - djv

Yesterday I wrote the code was working properly on IE. Today, I am using another PC and the code did not work on IE. However, this could be solved by giving the image imgCrop a background color! See also for more information:
http://deepliquid.com/content/Jcrop_Internet_Explorer_Notes.html

Tuesday, August 20, 2013 8:20 AM - djv

correction to my post few minutes ago. Doesn't seem to work yet properly. Am working on it.

Friday, August 23, 2013 2:02 PM - khristian

Excellent article. COngratulation buddy.

Monday, September 23, 2013 8:01 AM - AlexP

Great article, gave me a great starting point, cheers for that mate!
A few things which I had to fix in order to fit into my project:
- avoid postbacks when actually cropping
- loading and reloading image without postbacks (i used uploadify plugin) and that led to some issues with JCrop.
I will post a quick article how to resolve those issues and will link back to your as the original source if you are okay with that.
Thanks again!
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.