Crop Uploaded Image using JQuery in Asp.Net

In this tutorial i am going to explain how to Crop and Resize image and then upload it with the form in Asp.Nethow to validate image extension of image file or we can say the type of file, image size and upload image through asp.net file-upload control and then crop the image using jQuery/JavaScript plugin and save cropped image to an folder.

Crop Uploaded Image using JQuery in Asp.Net


So, Let's Start with an Example.
 First you need to create one simple webpage Default.aspx.

Now, After create Webpage you need to write html script.

HTML Source Code:


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
   
    <script src="Scripts/jquery.Jcrop.js" type="text/javascript"></script>
    <link href="CSS/jquery.Jcrop.css" rel="stylesheet" />
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $('#<%=imgToCrop.ClientID%>').Jcrop({
                onSelect: getAreaToCrop
            });
        });
        function getAreaToCrop(c) {
            $('#XCoordinate').val(parseInt(c.x));
            $('#YCoordinate').val(parseInt(c.y));
            $('#Width').val(parseInt(c.w));
            $('#Height').val(parseInt(c.h));
        }
    </script>
    <style type="text/css">
        .auto-style1 {
            color#CC3300;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <center>
    <div style="width540px">
        <fieldset>
            <legend>Upload, crop and save image in asp.net</legend>
            <center><h1 class="auto-style1">www.asppoint.com</h1></center>
            <table>
                <tr>
                    <td>
                        Select image to upload :
                    </td>
                    <td>
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                    </td>
                    <td>
                        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
                        <asp:Image ID="imgCropped" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
                        <asp:Label ID="lblMsg" runat="server" ForeColor="Red" />
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
                        <asp:Button ID="btnReset" runat="server" Text="Reset" Visible="false" OnClick="btnReset_Click" />
                    </td>
                </tr>
            </table>
            <asp:Panel ID="pnlCrop" runat="server" Visible="false">
                <table>
                    <tr>
                        <td>
                            <asp:Image ID="imgToCrop" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Button ID="btnCrop" runat="server" Text="Crop & Save" OnClick="btnCrop_Click" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input id="X" type="hidden" runat="server" />
                            <input id="Y" type="hidden" runat="server" />
                            <input id="Width" type="hidden" runat="server" />
                            <input id="Height" type="hidden" runat="server" />
                        </td>
                    </tr>
                </table>
            </asp:Panel>
        </fieldset>
        <center>
            <p class="auto-style1">Designed & Developed by Nikunj Satasiya</p>
        </center>
    </div>
  </center>
    </form>
</body>
</html>
After Complete User Interface You Need yo write C# code if you use C#.
For that open your aspx.cs file and write this code.

C# Source Code:


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 System.Drawing;
 
public partial class CropAndSaveImageCSharp : System.Web.UI.Page
{
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string fileName = string.Empty;
        string filePath = string.Empty;
        string extension = string.Empty;
        try
        {
            if (FileUpload1.HasFile)
            {
                extension = Path.GetExtension(FileUpload1.FileName).ToLower();
               
                if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
                {
                    fileName = Guid.NewGuid().ToString() + extension;              
                    filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
                    FileUpload1.SaveAs(filePath);
                    pnlCrop.Visible = true;
                    imgToCrop.ImageUrl = "~/Images/" + fileName;
                }
                else
                {
                    lblMsg.Text = "Please select jpg, jpeg, png, gif or bmp file only";
                }
            }
            else
            {
                lblMsg.Text = "Please select file to upload";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = "Oops!! error occured : " + ex.Message.ToString();
        }
        finally
        {
            extension = string.Empty;
            fileName = string.Empty;
            filePath = string.Empty;
        }
    }
 
    protected void btnCrop_Click(object sender, EventArgs e)
    {
        string croppedFileName = string.Empty;
        string croppedFilePath = string.Empty;
        string fileName = Path.GetFileName(imgToCrop.ImageUrl);
        string filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
        if (File.Exists(filePath))
        {
            System.Drawing.Image orgImg = System.Drawing.Image.FromFile(filePath);
            Rectangle areaToCrop = new Rectangle(
                Convert.ToInt32(X.Value),
                Convert.ToInt32(Y.Value),
                Convert.ToInt32(Width.Value),
                Convert.ToInt32(Height.Value));
            try
            {
 
                Bitmap bitMap = new Bitmap(areaToCrop.Width, areaToCrop.Height);
                using (Graphics g = Graphics.FromImage(bitMap))
                {
                    g.DrawImage(orgImg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), areaToCrop, GraphicsUnit.Pixel);
                }
                croppedFileName = "crop_" + fileName;
                croppedFilePath = Path.Combine(Server.MapPath("~/Images"), croppedFileName);
                bitMap.Save(croppedFilePath);
                orgImg.Dispose();
                bitMap = null;              
                File.Delete(filePath);
                pnlCrop.Visible = false;
                lblMsg.ForeColor = Color.Green;
                lblMsg.Text = "Image cropped and saved successfully";
                imgCropped.ImageUrl = "~/Images/" + croppedFileName;
                btnReset.Visible = true;
            }
            catch (Exception ex)
            {
                lblMsg.Text = "Oho!! error occurred Please try Again...! : " + ex.Message.ToString();
            }
            finally
            {
                fileName = string.Empty;
                filePath = string.Empty;
                croppedFileName = string.Empty;
                croppedFilePath = string.Empty;
            }
        }
 
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        imgCropped.ImageUrl = "";
        lblMsg.Text = string.Empty;
        btnReset.Visible = false;
    }
}

For that open your aspx.vb file and write this code.After Complete User Interface You Need yo write VB.Net code if you use Visual Basic.

Vb.Net Source Code:


Imports System.Drawing
Imports System.IO
Partial Class CropAndSaveImageVB
    Inherits System.Web.UI.Page
 
    Protected Sub btnUpload_Click(sender As Object, e As System.EventArgsHandles btnUpload.Click
        Dim fileName As String = String.Empty
        Dim filePath As String = String.Empty
        Dim extension As String = String.Empty
        Try
            If FileUpload1.HasFile Then
                extension = Path.GetExtension(FileUpload1.FileName).ToLower()
                If extension = ".jpg" OrElse extension = ".jpeg" OrElse extension = ".png" OrElse extension = ".gif" OrElse extension = ".bmp" Then
                    fileName = Guid.NewGuid().ToString() & extension
                    filePath = Path.Combine(Server.MapPath("~/Images"), fileName)
                    FileUpload1.SaveAs(filePath)
                    pnlCrop.Visible = True
                    imgToCrop.ImageUrl = "~/Images/" & fileName
                Else
                    lblMsg.Text = "Please select jpg, jpeg, png, gif or bmp file only"
                End If
            Else
                lblMsg.Text = "Please select file to upload"
            End If
        Catch ex As Exception
            lblMsg.Text = "Oops!! error occurred Please try Again...! : " & ex.Message.ToString()
        Finally
            extension = String.Empty
            fileName = String.Empty
            filePath = String.Empty
        End Try
    End Sub
 
    Protected Sub btnCrop_Click(sender As Object, e As System.EventArgsHandles btnCrop.Click
        Dim croppedFileName As String = String.Empty
        Dim croppedFilePath As String = String.Empty
        Dim fileName As String = Path.GetFileName(imgToCrop.ImageUrl)
        Dim filePath As String = Path.Combine(Server.MapPath("~/Images"), fileName)
        If File.Exists(filePath) Then
            Dim orgImg As System.Drawing.Image = System.Drawing.Image.FromFile(filePath)
 
            Dim areaToCrop As New Rectangle(Convert.ToInt32(X.Value), Convert.ToInt32(Y.Value), Convert.ToInt32(Width.Value), Convert.ToInt32(Height.Value))
            Try
 
                Dim bitMap As New Bitmap(areaToCrop.Width, areaToCrop.Height)
                Using g As Graphics = Graphics.FromImage(bitMap)
                    g.DrawImage(orgImg, New Rectangle(0, 0, bitMap.Width, bitMap.Height), areaToCrop, GraphicsUnit.Pixel)
                End Using
                croppedFileName = "crop_" & fileName
                croppedFilePath = Path.Combine(Server.MapPath("~/Images"), croppedFileName)
                bitMap.Save(croppedFilePath)
                orgImg.Dispose()
                bitMap = Nothing               
                File.Delete(filePath)
                pnlCrop.Visible = False
                lblMsg.ForeColor = Color.Green
                lblMsg.Text = "Image cropped and saved successfully"
                imgCropped.ImageUrl = "~/Images/" & croppedFileName
                btnReset.Visible = True
            Catch ex As Exception
                lblMsg.Text = "Oho!! error occured : " & ex.Message.ToString()
            Finally
                fileName = String.Empty
                filePath = String.Empty
                croppedFileName = String.Empty
                croppedFilePath = String.Empty
            End Try
        End If
    End Sub
 
    Protected Sub btnReset_Click(sender As Object, e As System.EventArgsHandles btnReset.Click
        imgCropped.ImageUrl = ""
        lblMsg.Text = String.Empty
        btnReset.Visible = False
    End Sub
End Class
 
Previous
Next Post »

If you have any kind of question about any post, Feel free to ask.You can simply drop a comment below post. Your feedback and suggestions will be highly appreciated. ConversionConversion EmoticonEmoticon