Friday, August 8, 2014

Upload and crop image in Asp.net using Jcrop jquery plugin

Introduction: In this article today I am going to explain how we can implement the functionality of Upload and crop image in Asp.net using Jcrop jquery plugin. 

Upload and crop image in Asp.net using Jcrop jquery plugin


Description:

Add a new webform to project. To implement this functionality follow the given steps:
Step 1: Add the below given script and style sheet between head section of page:

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

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

To download the Jcrop Jquery Plugin Click Here.

Step 2: Now copy and paste the below design in between <from> </form> tag of page:

<center>
      <fieldset style="width:auto;height:auto;">
      <legend>Crop Image Demo</legend>
     <asp:Panel ID="pnlUpload" runat="server">
      <asp:FileUpload ID="FileUpload1" runat="server" />
      <br />
      <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload Image" />
      <asp:Label ID="lblError" runat="server" />
    </asp:Panel>
    <asp:Panel ID="pnlCrop" runat="server" Visible="false" >
      <asp:Image ID="imgCrop" runat="server" Width="500px" Height="500px"/>
      <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 Image" OnClick="btnCrop_Click" />
    </asp:Panel>
    <asp:Panel ID="pnlCropped" runat="server" Visible="false">
      <asp:Image ID="imgCropped" runat="server" />
    </asp:Panel>
    </fieldset>
  </center>

Step 3: after that on Upload image button click write the given code:

In C#:

using System.Drawing;
using System.IO;
using Image = System.Drawing.Image;
using System.Drawing.Drawing2D;

protected void btnUpload_Click(object sender, EventArgs e)
    {
        string uploadFileName = "";
        string uploadFilePath = "";
        if (FileUpload1.HasFile)
        {
            string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
            if (ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".png")
            {
                uploadFileName = Guid.NewGuid().ToString() + ext;
                uploadFilePath = Path.Combine(Server.MapPath("~/images"), uploadFileName);
                try
                {
                    FileUpload1.SaveAs(uploadFilePath);
                    imgCrop.ImageUrl = "~/images/" + uploadFileName;
                    imgCrop.Width =500;
                    pnlCrop.Visible = true;
                    pnlCropped.Visible = false;
                }
                catch (Exception ex)
                {
                    lblError.Text = "Error! Please try again.";
                }
            }
            else
            {
                lblError.Text = "Selected file type not allowed!!! Upload only Jpeg, Png, Gif Files";
            }
        }
        else
        {
            lblError.Text = "Select file first!!!";
        }
    }


In VB:

Imports System.Drawing
Imports System.IO
Imports Image = System.Drawing.Image
Imports System.Drawing.Drawing2D


Protected Sub btnUpload_Click(ByVal sender As ObjectByVal e As System.EventArgs) Handles btnUpload.Click
        Dim uploadFileName As String = ""
        Dim uploadFilePath As String = ""
        If FileUpload1.HasFile Then
            Dim ext As String = Path.GetExtension(FileUpload1.FileName).ToLower()
            If ext = ".jpg" OrElse ext = ".jpeg" OrElse ext = ".gif" OrElse ext = ".png" Then
                uploadFileName = Guid.NewGuid().ToString() & ext
                uploadFilePath = Path.Combine(Server.MapPath("~/images"), uploadFileName)
                Try
                    FileUpload1.SaveAs(uploadFilePath)
                    imgCrop.ImageUrl = Convert.ToString("~/images/") & uploadFileName
                    imgCrop.Width = 500
                    pnlCrop.Visible = True
                    pnlCropped.Visible = False
                Catch ex As Exception
                    lblError.Text = "Error! Please try again."
                End Try
            Else
                lblError.Text = "Selected file type not allowed!!! Upload only Jpeg, Png, Gif Files"
            End If
        Else
            lblError.Text = "Select file first!!!"
        End If
    End Sub
Step 4: On Crop button Click write the code:

In C#:

    protected void btnCrop_Click(object sender, EventArgs e)
    {
        string fileName = Path.GetFileName(imgCrop.ImageUrl);
        string filePath = Path.Combine(Server.MapPath("~/images"), fileName);
        string cropFileName = "";
        string cropFilePath = "";
        if (File.Exists(filePath))
        {
            System.Drawing.Image orgImg = System.Drawing.Image.FromFile(filePath);
            Rectangle CropArea = new Rectangle(
                Convert.ToInt32(X.Value),
                Convert.ToInt32(Y.Value),
                Convert.ToInt32(W.Value),
                Convert.ToInt32(H.Value));
            try
            {
                Bitmap bitMap = new Bitmap(CropArea.Width, CropArea.Height);
                using (Graphics g = Graphics.FromImage(bitMap))
                {
                    g.DrawImage(orgImg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), CropArea, GraphicsUnit.Pixel);
                }
                cropFileName = "crop_" + fileName;
                cropFilePath = Path.Combine(Server.MapPath("~/images"), cropFileName);
                bitMap.Save(cropFilePath);
                // Response.Redirect("~/images/" + cropFileName, false);
                imgCropped.ImageUrl = "~/images/" + cropFileName;
                pnlCropped.Visible = true;
                pnlCrop.Visible = false;
            }
            catch (Exception ex)
            {

            }
        }
    }

In VB:

  Protected Sub btnCrop_Click(ByVal sender As ObjectByVal e As System.EventArgs) Handles btnCrop.Click
        Dim fileName As String = Path.GetFileName(imgCrop.ImageUrl)
        Dim filePath As String = Path.Combine(Server.MapPath("~/images"), fileName)
        Dim cropFileName As String = ""
        Dim cropFilePath As String = ""
        If File.Exists(filePath) Then
            Dim orgImg As System.Drawing.Image = System.Drawing.Image.FromFile(filePath)
            Dim CropArea As New Rectangle(Convert.ToInt32(X.Value), Convert.ToInt32(Y.Value), Convert.ToInt32(W.Value), Convert.ToInt32(H.Value))
            Try
                Dim bitMap As New Bitmap(CropArea.Width, CropArea.Height)
                Using g As Graphics = Graphics.FromImage(bitMap)
                    g.DrawImage(orgImg, New Rectangle(0, 0, bitMap.Width, bitMap.Height), CropArea, GraphicsUnit.Pixel)
                End Using
                cropFileName = Convert.ToString("crop_") & fileName
                cropFilePath = Path.Combine(Server.MapPath("~/images"), cropFileName)
                bitMap.Save(cropFilePath)
                ' Response.Redirect("~/images/" + cropFileName, false);
                imgCropped.ImageUrl = Convert.ToString("~/images/") & cropFileName
                pnlCropped.Visible = True
                pnlCrop.Visible = False
            Catch ex As Exception
            End Try
        End If
    End Sub


Build and run the project.

Download project:

download


4 comments:

  1. Thank you for sharing. if i want to crop image with fix dimensions and also with same aspect ration. what needs to be changed in above code?

    ReplyDelete