Home > ASP.Net, Csharp, DotNet, JQuery > How to crop image using ASP.Net/C# OR Cropping image in C# before upload

How to crop image using ASP.Net/C# OR Cropping image in C# before upload


Crop images before upload to the server in C#/ASP.Net

In our previous post we demonstrate how we can re size image using C# or Create thumbnail image using ASP.Net. Here we are demonstrating how we can crop images using ASP.Net application using Jquery and C#. In some applications we need to upload images and we need only some portion of the images to get clear picture on the photo. In this case we need to give an option to users to crop image before they are uploading the image.

Include Jquery file/CSS files to the application. 

First of all we need to include following jquery/CSS files to the application.

1.       jquery.min.js     –    You can download from here

2.       jquery.Jcrop.js   –    You can download from here

3.       jquery.Jcrop.css   –    You can download from here 

Simple steps to crop image using ASP.Net,C#,Jquery

In this application we are having a browse option for selecting an image. Once we selected a image it will display int the screen.

Crop image using ASP.net C#

Select an image to crop using ASP.Net C# Jquery

In the next step we will have the option to select an area to crop the image. Once we selected an area we can click crop button on the screen.

Crop image using ASP.Net C#

Select image area to crop

Then the selected area will be cropped and displayed in the screen.

Crop image using ASP.Net C#

Cropped area of the image

ASPX Page for crop images using Jquery 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CropImage.aspx.cs" 
Inherits="ExperimentLab.CropImage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Crop Image</title>
 <link href="Styles/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" 
 <script type="text/javascript" src="Scripts/jquery.Jcrop.js"></script>
 <script type="text/javascript">
 jQuery(document).ready(function () {
 onSelect: storeCoords
function storeCoords(c) {
 <form id="form1" runat="server">
 <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 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 ID="pnlCropped" runat="server" Visible="false">
 <asp:Image ID="imgCropped" runat="server" />

Code Behind of the ASPX page for Crop image using ASP.Net/C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SD = System.Drawing;
using System.Drawing.Drawing2D;
namespace ExperimentLab
public partial class CropImage : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
protected void btnUpload_Click(object sender, EventArgs e)
Boolean FileOK = false;
Boolean FileSaved = false; 
if (Upload.HasFile)
Session["WorkingImage"] = Upload.FileName;
String FileExtension =
String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
for (int i = 0; i < allowedExtensions.Length; i++)
if (FileExtension == allowedExtensions[i])
 FileOK = true;
if (FileOK)
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;
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();
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;
static byte[] Crop(string Img, int Width, int Height, int X, int Y)
using (SD.Image OriginalImage = SD.Image.FromFile(Img))
using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
 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);

  1. Dorababu
    May 30, 2012 at 9:46 pm

    Good one.. Is it possible to paste the cropped image where ever required on the form

  2. May 31, 2012 at 4:29 pm

    Sure. You can put img tag wherever you need to display image. Then u can give the source as crpped image

  3. June 19, 2012 at 8:14 pm

    what is ExperimentLab.CropImage in inherits=” ” . it give error.

  4. June 30, 2012 at 7:26 pm

    Hi Satyakrshr,
    “ExperimentLab” is namesapce name in the above example. You have to replace this name with your namespace name. Please try and let me know if you have any other issues.

  5. mukund
    August 13, 2012 at 5:15 pm

    where i found jquery files

  6. September 13, 2012 at 3:19 pm

    Is this possible to do in ASP MVC?

  7. September 13, 2012 at 7:52 pm

    Hi Nikos,
    Thank you for visiting my blog.
    I didnt try with MVC yet and I will check and let you know.

  8. fazal
    September 14, 2012 at 10:39 am

    From where i can get these jquery files….
    1. jquery.min.js
    2. jquery.Jcrop.js
    3. jquery.Jcrop.css

  9. September 14, 2012 at 11:17 am

    Hi fazal, Thank you for visting my blog. I will upload jquery files and will post the links today evening.

  10. fazal
    September 14, 2012 at 11:19 am

    got the jquery files by googling…but i’m unable to select the area for cropping after uploading the image…plz reply

  11. September 14, 2012 at 11:26 am

    Hi fazal,

    Can u share the error that you got. Please check any script error tracked in the browser also.

  12. fazal
    September 14, 2012 at 11:34 am

    Thanx tuvian…..M not getting any error….File is getting upload and after getting the saved image on my page m unable to select the area for cropping….

  13. September 14, 2012 at 12:12 pm

    Hi fazal,

    Please make sure that u copied entire section of codes in the post. Especially the lines that we included jquery files. Also check the path of the jquery file that u copoed and mapped is correct. Also verify no popup blocking or any other message is not coming from browser. Please try some other browsers also to track the issue.

  14. fazal
    September 14, 2012 at 12:27 pm

    Hi tuvian,
    I tried for mozilla n chrome getting same issue….I think the problem is with jquery files which m using might not b the one U specified….It would be helpfull if u send me the jquery files now instead in evening….
    Thanx n regard

  15. September 14, 2012 at 8:31 pm

    Awesome looking fwd to MVC code, I’ll end up doing it myself anyway next week!

  16. September 14, 2012 at 9:03 pm

    Hi Fazal,

    I Included links for downloading css and js files.
    Please download and try again.

  17. September 14, 2012 at 9:21 pm

    Hi Nikos,

    I didnt start with MVC yet. If you come across the solution first, please feel to share the same.

  18. raghava
    October 1, 2012 at 6:35 pm

    I have the uploaded image . Can I just crop the image using the crop code

  19. October 1, 2012 at 10:53 pm

    Hi raghava,

    Sure, You can crop the uploaded image using codes mentioned in the post.
    Please fee free to ask any queries.

    Thanks for visiting our blog

  20. raghava
    October 3, 2012 at 11:57 am

    Your post is very good in upload and crop point of view. But I need to save the path of the image in database.I have the code for that and i am in need of the crop code.So can you please help me in this aspect.

  21. October 3, 2012 at 9:10 pm

    Hi Raghava,

    You can use above codes for crop images. In your scenario you need to show uploaded image in asp image tag and then crop from there as mentioned in above post.

  22. shailesh singh
    October 4, 2012 at 1:08 pm

    dear sir your code is not running properly .It shows exception at runtime the error is
    Input string was not in a correct format. at crop event.please reply soon

  23. October 4, 2012 at 1:54 pm

    Hi shaliesh,
    The above code is working fine in my machine.
    Please send your email id so that I will send source code to you.

  24. Arnav
    October 4, 2012 at 10:30 pm

    how I replace Experiment.lab namespace…
    I m totally new in asp.net

  25. October 5, 2012 at 10:11 am

    Hi Arnav,
    You can replace ExperimentLab with your namespace name. As you are new to ASP.Net, you just copy after the namespace code from above post.
    Please try and let me know if you face any problem.

    Thank you for visiting blog.. 🙂

  26. October 5, 2012 at 10:48 pm

    Hi All,
    I posted a sample application with full source code in the above post.
    You can download and run application.


  27. Deepthi
    October 9, 2012 at 2:43 pm

    You have given an image control and you are uploading image to that control.
    If i Set width and height to that control cropping is not done properly.If i crop in center it is coming from left side.So finally i set height and width to image control cropping is not working properly.Please give me one solution.

  28. October 10, 2012 at 3:59 pm

    Hi Deepthi,
    I just tried your scenario and it is working fine here.

    1. Just download sample application from above post
    2. Open CropImage.aspx file and add Width and height attribute to the asp:Image ID=”imgCrop” (Width=”100″ Height=”100″)
    3. Run the application and able to crop the image.

    Just try it and let me know any issues you still face.


  29. Greeshma
    April 10, 2013 at 10:49 am

    this code worked with mvc

  30. Greeshma
    April 10, 2013 at 10:50 am

    whether this code worked with MVC?

  31. August 10, 2013 at 3:03 am

    awesome sample – any easy way to only allow a 2×3 ratio for selection? Haven’t dug into the plugin yet.

  32. Suman
    August 27, 2013 at 11:47 am

    Hi Tuvian.,

    Thanks for giving Awesome code i need code for saved the image to DB after Cropping was done Give any suggestions ASAP..


  33. Suman
    August 27, 2013 at 11:54 am

    Can any one Give a suggestions for imaged saved to db after cropping done.
    After press submit button the image saved to Db table.

  34. August 28, 2013 at 7:06 am

    Hi Suman,

    One way to achieve the requirement is, upload the cropped image into the server.
    Then save the URL of the uploaded image into the db as string.


  35. Suman
    August 28, 2013 at 6:39 pm

    Hi Tuvian Thanks for your suggestion I have one more Question After cropping was done the image displays in same window or new window it will be again cropped to depend upon user compatibility how to add that functionality to this Example plz give me sample code…


  36. November 9, 2013 at 1:26 pm

    I hope this article has given you some useful facts
    about roofs. Nash, who had received a gigantic claim in reward for his discovery,
    could possibly be seen nearly every day busily at work.

    As the atmosphere began to disintegrate around me, I felt a fresh
    strength forge into my thoughts.

    January 7, 2014 at 4:29 pm


  38. January 17, 2014 at 1:38 pm

    For example, being looking for film, it is possible to select files
    by limiting their size – applying this option you are going to except
    low-quality films (SAT-Rip, CAM-Rip, Telesync).
    As daylight broke from a miserable night a helicopter flew in, dropping a line to
    tug the man to safety. When Vista Service Pack 1 was within the beta phase, Microsoft included a little software utility called ‘recdisc.

  39. April 19, 2014 at 12:42 am

    If you try to create your individual torrent then a instructions on how to use torrents and how to
    make torrents are usually in the torrent program you have installed on
    your computer. Whether you use it in your own home, at college or at
    the office Ubuntu contains each of the applications
    you’ll ever need, from word processing and email applications,
    to web server software and programming tools. When Vista Service Pack 1 was inside
    the beta phase, Microsoft included a little software utility called ‘recdisc.

  40. April 20, 2014 at 2:13 am

    But during the last few years, IPTV has dwarfed the grade of DVD and
    Cable TV. I am not really a PC player, please anyone
    let me to remove Dell Inspiron password…” We usually hear such inquiry around us.

    We’ll start our tour at Marina Grande for the north shore from the
    island, about one third with the way in looking at the easternmost point.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: