Crop Image Using JCrop in Asp.net C#


This tutorial will explain you how to crop an image using JCROP (library built in jquery) in ASP.NET C#(c sharp). We have used JCROP library to set size & coordinates of the area selected while cropping an image.


You can download project from here which includes JCROP library as well: CropImage

Below is the code for cropping image in ASP.net (Default.aspx):

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Image Crop Tutorial - Programmerclubhouse.com</title>
    <style>
      body{ font-family:Arial;}
    </style>
    <link href="scripts/jcrop/css/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
    <script src="scripts/jcrop/js/jquery.min.js" type="text/javascript"></script>
    <script src="scripts/jcrop/js/jquery.Jcrop.js" type="text/javascript"></script>
    <script type="text/javascript">
      jQuery(document).ready(function() {
      jQuery('#<%=imgCrop.ClientID %>').Jcrop({
          onSelect: storeCoords,
          //Set Image Box Height & Width
          boxWidth: 800, boxHeight: 600
        });
      });

  //Function to store coordinates
  function storeCoords(c) {
    jQuery('#<%=hdnX.ClientID %>').val(c.x);
    jQuery('#<%=hdnY.ClientID %>').val(c.y);
    jQuery('#<%=hdnW.ClientID %>').val(c.w);
    jQuery('#<%=hdnH.ClientID %>').val(c.h);
  };

</script>
</head>
<body>
    <form id="form1" runat="server">
      <table width="100%" cellpadding="0" cellspacing="0">
        <tr><td colspan="3"><h2>Image Cropping using Jcrop - Programmerclubhouse.com</h2></td></tr>

        <asp:Panel ID="pnlUpload" runat="server">
          <tr>
            <td align="left" width="20%">Upload Image:</td>
            <td></td>
            <td>
              <asp:FileUpload ID="fuImage" runat="server" />
            </td>
          </tr>
          <tr><td> </td></tr>
          <tr><td colspan="3">
            <asp:Button ID="btnSave" runat="server" Text="Save Image" onclick="btnSave_Click" />
          </td></tr>
        </asp:Panel>

        <asp:Panel ID="pnlCrop" runat="server" Visible="false">
          <tr>
            <td colspan="3" align="left"><b>Please select an area to crop from image below</b></td>
          </tr>
          <tr><td> </td></tr>
          <tr><td colspan="3" align="left">
            <asp:Image ID="imgCrop" runat="server" />
            <asp:HiddenField ID="hdnX" runat="server" />
            <asp:HiddenField ID="hdnY" runat="server" />
            <asp:HiddenField ID="hdnW" runat="server" />
            <asp:HiddenField ID="hdnH" runat="server" />
            <asp:Button ID="btnCrop" runat="server" Text="Crop & Save" onclick="btnCrop_Click" />
          </td></tr>
          <tr><td> </td></tr>
        </asp:Panel>

        <asp:Panel ID="pnlCroppedImage" runat="server" Visible="false">
          <tr><td colspan="3"><asp:Image ID="imgCropped" runat="server" /></td></tr>
        </asp:Panel>

        <tr><td colspan="3">
          <asp:Literal ID="ltrMsg" EnableViewState="false"  runat="server"></asp:Literal>
        </td></tr>
      </table>
    </form>
</body>
</html>

Below is the code behind for cropping image in ASP.net (Default.aspx.cs):

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

public partial class _Default : System.Web.UI.Page 
{
    private string m_sImageNameUserUpload = "";
    private string m_sImageNameGenerated = "";

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
      //Below is the code to save image in images directory
      string sImageName = "";
      string sImagePathImages = Server.MapPath("images/");
      if (fuImage.HasFile)
      {
        //Save image to images folder
        sImageName = Guid.NewGuid().ToString().Substring(0, 8);
        string sFileExt = Path.GetExtension(fuImage.FileName);
        m_sImageNameUserUpload = sImageName + sFileExt;
        m_sImageNameGenerated = Path.Combine(sImagePathImages, m_sImageNameUserUpload);
        fuImage.PostedFile.SaveAs(m_sImageNameGenerated);
      }
      if (m_sImageNameUserUpload != "")
      {
        pnlUpload.Visible = false;
        pnlCrop.Visible = true;
        imgCrop.ImageUrl = "images/" + m_sImageNameUserUpload;
        Session["ImageName"] = m_sImageNameUserUpload;
      }
      else
      {
        ltrMsg.Text = "<font color='red'><b>Please select an image to crop.</b></font>";
      }
    }

    protected void btnCrop_Click(object sender, EventArgs e)
    {
      if (hdnW.Value != "")
      {
        string sImagePathImages = Server.MapPath("images/");
        m_sImageNameUserUpload = Session["ImageName"].ToString();
        // Get Width, Height, X & Y coordinates from hidden field which gets value when you select an area to crop.
        int iWidth = Convert.ToInt32(hdnW.Value);
        int iHeight = Convert.ToInt32(hdnH.Value);
        int iXCoord = Convert.ToInt32(hdnX.Value);
        int iYCoord = Convert.ToInt32(hdnY.Value);
        //Call CropImage method defined below
        byte[] byt_CropImage = CropImage(sImagePathImages + m_sImageNameUserUpload, iWidth, iHeight, iXCoord, iYCoord);
        using (MemoryStream oMemoryStream = new MemoryStream(byt_CropImage, 0, byt_CropImage.Length))
        {
          oMemoryStream.Write(byt_CropImage, 0, byt_CropImage.Length);
          using (System.Drawing.Image oCroppedImage = System.Drawing.Image.FromStream(oMemoryStream, true))
          {
            string sSaveTo = sImagePathImages + m_sImageNameUserUpload;
            oCroppedImage.Save(sSaveTo, oCroppedImage.RawFormat);
          }
        }
        pnlUpload.Visible = false;
        pnlCrop.Visible = false;
        pnlCroppedImage.Visible = true;
        imgCropped.ImageUrl = "images/" + m_sImageNameUserUpload;
        ltrMsg.Text = "<font color='green'><b>Image cropped successfully.</b></font>";
      }
      else
      {
        ltrMsg.Text = "<font color='red'><b>Please select area to crop.</b></font>";
      }
    }

    static byte[] CropImage(string sImagePath, int iWidth, int iHeight, int iX, int iY)
    {
      try
      {
        using (System.Drawing.Image oOriginalImage = System.Drawing.Image.FromFile(sImagePath))
        {
          using (System.Drawing.Bitmap oBitmap = new System.Drawing.Bitmap(iWidth, iHeight))
          {
            oBitmap.SetResolution(oOriginalImage.HorizontalResolution, oOriginalImage.VerticalResolution);
            using (System.Drawing.Graphics Graphic = System.Drawing.Graphics.FromImage(oBitmap))
            {
              Graphic.SmoothingMode = SmoothingMode.AntiAlias;
              Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
              Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
              Graphic.DrawImage(oOriginalImage, new System.Drawing.Rectangle(0, 0, iWidth, iHeight), iX, iY, iWidth, iHeight, System.Drawing.GraphicsUnit.Pixel);
              MemoryStream oMemoryStream = new MemoryStream();
              oBitmap.Save(oMemoryStream, oOriginalImage.RawFormat);
              return oMemoryStream.GetBuffer();
            }
          }
        }
      }
      catch (Exception Ex)
      {
        throw (Ex);
      }
    }
}

You can download project from here which includes JCROP library as well: CropImage

To know more about JCROP visit DeepLiquid.com

JCROP is developed by Kelly Hallman and Deep Liquid Group.

Tags: , , , , , ,

Comments & Responses

2 Responses so far.

  1. deepika says:

    its very nice code…thanks

  2. animesh says:

    Awesome code… really appreciable… Thanks a lot….

Leave a Reply

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

*


× 5 = 5

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>