Please disable your adblock and script blockers to view this page
 

How to validate,upload,crop and store image in folder in asp.net using jQuery

Click on image to view enlarged demo
Introduction: In this article i am going to explain how to validate image type(extension) , upload image through asp.net fileupload control and then crop the image using jQuery plugin and save cropped image to folder.

Description: So basically this article covers the following:
  • How to validate image type before upload or we can say allowing only specified type of files to upload and restrict all other type of images.
  • How to upload image through file upload control.
  • How to crop uploaded image using jQuery
  • How to store cropped image in folder and display it.
In previous articles i explained How to Upload and store image in binary foramt into SQL server database and display it and Upload and resize image in Asp.net and  jQuery to validate file extension and upload image and Show image preview before uploading through asp.net fileupload control using jQuery and Bind,upload,download,delete image files from the GridView in asp.net and Save image in binary format in Sql server database and retrieve, bind to Gridview

Note: I have attached this sample project at the end of this article and you need to download this so that you can get the required jquery file(jquery.Jcrop.js)  and Css file(jquery.Jcrop.css) and check the live demo at your end.

Implementation:  Let's create a simple website page(default.aspx) and write the following :

<%@ 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 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>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width: 540px">
        <fieldset>
            <legend>Upload, crop and save image in asp.net</legend>
            <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="XCoordinate" type="hidden" runat="server" />
                            <input id="YCoordinate" type="hidden" runat="server" />
                            <input id="Width" type="hidden" runat="server" />
                            <input id="Height" type="hidden" runat="server" />
                        </td>
                    </tr>
                </table>
            </asp:Panel>
        </fieldset>
    </div>
    </form>
</body>
</html>

Asp.Net C# code  to validate,upload,crop and store image to folder

In the Code file(default.aspx.cs) write the code as:

First of all add following namespaces

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;

then write the code as:

protected void btnUpload_Click(object sender, EventArgs e)
    {
        string fileName = string.Empty;
        string filePath = string.Empty;
        string extension = string.Empty;
        try
        {
            //Check if Fileupload control has file in it
            if (FileUpload1.HasFile)
            {
                // Get selected image extension
                extension = Path.GetExtension(FileUpload1.FileName).ToLower();
                //Check image is of valid type or not
                if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
                {
                    //Create unique name for the file
                    fileName = Guid.NewGuid().ToString() + extension;
                    //Create path for the image to store
                    filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
                    //Save image in folder
                    FileUpload1.SaveAs(filePath);
                    //Show the panel and load the uploaded image in image control.
                    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;
        //get uploaded image name
        string fileName = Path.GetFileName(imgToCrop.ImageUrl);
        //get uploaded image path
        string filePath = Path.Combine(Server.MapPath("~/Images"), fileName);

        //Check if file exists on the path i.e. in the UploadedImages folder.
        if (File.Exists(filePath))
        {
            //Get the image from UploadedImages folder.
            System.Drawing.Image orgImg = System.Drawing.Image.FromFile(filePath);
            //Get user selected cropped area
            //Convert.ToInt32(String.Format("{0:0.##}", YCoordinate.Value)),

            Rectangle areaToCrop = new Rectangle(
                Convert.ToInt32(XCoordinate.Value),
                Convert.ToInt32(YCoordinate.Value),
                Convert.ToInt32(Width.Value),
                Convert.ToInt32(Height.Value));
            try
            {

                Bitmap bitMap = new Bitmap(areaToCrop.Width, areaToCrop.Height);
                //Create graphics object for alteration
                using (Graphics g = Graphics.FromImage(bitMap))
                {
                    //Draw image to screen
                    g.DrawImage(orgImg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), areaToCrop, GraphicsUnit.Pixel);
                }

                //name the cropped image
                croppedFileName = "crop_" + fileName;
                //Create path to store the cropped image
                croppedFilePath = Path.Combine(Server.MapPath("~/Images"), croppedFileName);
                //save cropped image in folder
                bitMap.Save(croppedFilePath);
                orgImg.Dispose();
                bitMap = null;
                //Now you can delete the original uploaded image from folder               
                File.Delete(filePath);
                //Hide the panel
                pnlCrop.Visible = false;
                //Show success message in label
                lblMsg.ForeColor = Color.Green;
                lblMsg.Text = "Image cropped and saved successfully";

                //Show cropped image
                imgCropped.ImageUrl = "~/Images/" + croppedFileName;

                //Show Reset button
                btnReset.Visible = true;
            }
            catch (Exception ex)
            {
                lblMsg.Text = "Oops!! error occured : " + 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;
    }


Asp.Net VB code  to validate,upload,crop and store image to folder

In code file (default.aspx.vb) write the code as:

First add following namespaces:

Imports System.IO
Imports System.Drawing

Then write the code as:

Protected Sub btnUpload_Click(sender As Object, e As System.EventArgs) Handles btnUpload.Click
        Dim fileName As String = String.Empty
        Dim filePath As String = String.Empty
        Dim extension As String = String.Empty
        Try
            'Check if Fileupload control has file in it
            If FileUpload1.HasFile Then
                ' Get selected image extension
                extension = Path.GetExtension(FileUpload1.FileName).ToLower()
                'Check image is of valid type or not
                If extension = ".jpg" OrElse extension = ".jpeg" OrElse extension = ".png" OrElse extension = ".gif" OrElse extension = ".bmp" Then
                    'Create unique name for the file
                    fileName = Guid.NewGuid().ToString() & extension
                    'Create path for the image to store
                    filePath = Path.Combine(Server.MapPath("~/Images"), fileName)
                    'Save image in folder
                    FileUpload1.SaveAs(filePath)
                    'Show the panel and load the uploaded image in image control.
                    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 occured : " & 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.EventArgs) Handles btnCrop.Click
        Dim croppedFileName As String = String.Empty
        Dim croppedFilePath As String = String.Empty
        'get uploaded image name
        Dim fileName As String = Path.GetFileName(imgToCrop.ImageUrl)
        'get uploaded image path
        Dim filePath As String = Path.Combine(Server.MapPath("~/Images"), fileName)

        'Check if file exists on the path i.e. in the UploadedImages folder.
        If File.Exists(filePath) Then
            'Get the image from UploadedImages folder.
            Dim orgImg As System.Drawing.Image = System.Drawing.Image.FromFile(filePath)
            'Get user selected cropped area
            'Convert.ToInt32(String.Format("{0:0.##}", YCoordinate.Value)),

            Dim areaToCrop As New Rectangle(Convert.ToInt32(XCoordinate.Value), Convert.ToInt32(YCoordinate.Value), Convert.ToInt32(Width.Value), Convert.ToInt32(Height.Value))
            Try

                Dim bitMap As New Bitmap(areaToCrop.Width, areaToCrop.Height)
                'Create graphics object for alteration
                Using g As Graphics = Graphics.FromImage(bitMap)
                    'Draw image to screen
                    g.DrawImage(orgImg, New Rectangle(0, 0, bitMap.Width, bitMap.Height), areaToCrop, GraphicsUnit.Pixel)
                End Using

                'name the cropped image
                croppedFileName = "crop_" & fileName
                'Create path to store the cropped image
                croppedFilePath = Path.Combine(Server.MapPath("~/Images"), croppedFileName)
                'save cropped image in folder
                bitMap.Save(croppedFilePath)
                orgImg.Dispose()
                bitMap = Nothing
                'Now you can delete the original uploaded image from folder               
                File.Delete(filePath)
                'Hide the panel
                pnlCrop.Visible = False
                'Show success message in label
                lblMsg.ForeColor = Color.Green
                lblMsg.Text = "Image cropped and saved successfully"

                'Show cropped image
                imgCropped.ImageUrl = "~/Images/" & croppedFileName

                'Show Reset button
                btnReset.Visible = True
            Catch ex As Exception
                lblMsg.Text = "Oops!! 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.EventArgs) Handles btnReset.Click
        imgCropped.ImageUrl = ""
        lblMsg.Text = String.Empty
        btnReset.Visible = False
    End Sub

                              Download the complete example 

Now over to you:
" I hope you have learned how to validate,upload,crop and store image to folder in asp.net using jQuery with this example and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon