Image cropping using Jcrop in ASP.NET MVC Application

What is Image cropping?

  • Image cropping refer to removal of some part of image
  • Uses to improve framing and size
  • Applied in photograph to resize image

Application overview
In this project, I will show image cropping of an employee phot when employee information saved and modified. Full crud operation applied in the application with image cropping.
Let’s have a look on the implementation of the project.

Tools and Technology used

I used following tools and technology to develop the project –

  1. Visual Studio 2015
  2. Visual C#
  3. ASP.NET MVC
  4. Entity Framework 5
  5. Razor view engine
  6. JCrop

Step 1: Create a ASP.net MVC Project
File -> New project and select the project template Visual C# -> ASP.NET Web Application (.NET Framework) -> Console application (.NET Core).

0108_01

Select MVC as a Template as ASP.NET Template and click OK

0108_02

Step 2: Change or Add Connection String
Change or Add connection string in Web.config as follows

  
    
  
  

Step 3: Install JCrop Nuget Package
Go to Tools -> NuGet Package Manager -> Manages NuGet Package Manager for the solution -> Search Jcrop and install jquery.jcrop.js

0108_02_B

Step 4: Create model class

Create model class “Employee” as follows.

Employee Class

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace JCropMVC.Models
{
    public class Employee
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Display(Name = "Full Name")]
        [Required(ErrorMessage = "Name cannot be empty")]
        public string Name { get; set; }

        [Display(Name = "Father Name")]
        public string FatherName { get; set; }

        [Display(Name = "Designation")]
        public string Designation { get; set; }

        [Display(Name = "Mobile No")]
        public string Mobile { get; set; }

        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Display(Name = "Image URL")]
        public string PhotoURL { get; set; }
    }
}

Step 5: Modify Context class
Modify ApplicationDbContext in IdentityModel Class

    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public DbSet Employees { get; set; }
    }

Step 6: Create Controller and Views
Create Employees Controller and Views
Click Right button on Controller Folder->Add Controller. Now choose scaffolding template as MVC Controllers with views using Entity Framework and then Click Add.

0108_03

Now select Model class as Employee and Data Context Class as ApplicationDbContext as follows. Then click OK.

0108_04

Step 7: Modify the controller
Modify EmployeesController as follows. Here method ProcessImage(string croppedImage) is used to process and save image. An extra parameter added for Create and Edit action.

using System;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using JCropMVC.Models;
using System.IO;

namespace JCropMVC.Controllers
{
    public class EmployeesController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Employees
        public ActionResult Index()
        {
            return View(db.Employees.ToList());
        }

        // GET: Employees/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // GET: Employees/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Employees/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,FatherName,Designation,Mobile,Email,PhotoURL")] Employee employee, string avatarCropped)
        {
            string filePath = ProcessImage(avatarCropped);
            employee.PhotoURL = filePath;

            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        /// 
        /// Process image and save in predefined path
        /// 
        /// 
        /// 
        private string ProcessImage(string croppedImage)
        {
            string filePath = String.Empty;
            try
            {
                string base64 = croppedImage;
                byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
                filePath = "/Images/Photo/Emp-" + Guid.NewGuid() + ".png";
                using (FileStream stream = new FileStream(Server.MapPath(filePath), FileMode.Create))
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Flush();
                }
            }
            catch (Exception ex)
            {
                string st = ex.Message;
            }

            return filePath;
        }

        // GET: Employees/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Employees/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,FatherName,Designation,Mobile,Email,PhotoURL")] Employee employee, string avatarCropped)
        {
            string filePath = ProcessImage(avatarCropped);
            employee.PhotoURL = filePath;

            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        //[Authorize(Users ="sumon")]
        // GET: Employees/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Employees/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Step 8: Modify the views for Employee

Create.cshtml

@model JCropMVC.Models.Employee

@{
    ViewBag.Title = "Create";
}



@using (Html.BeginForm("Create", "Employees", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    
@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Name, new { @class = "" }) @Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder = "Enter employee full name...", type = "text" }) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.FatherName, new { @class = "" }) @Html.TextBoxFor(model => model.FatherName, new { @class = "form-control", placeholder = "Enter father name...", type = "text" }) @Html.ValidationMessageFor(model => model.FatherName)
@Html.LabelFor(model => model.Designation, new { @class = "" }) @Html.TextBoxFor(model => model.Designation, new { @class = "form-control", placeholder = "Enter designation name...", type = "text" }) @Html.ValidationMessageFor(model => model.Designation)
@Html.LabelFor(model => model.Mobile, new { @class = "" }) @Html.TextBoxFor(model => model.Mobile, new { @class = "form-control", placeholder = "Enter mobile number...", type = "text" }) @Html.ValidationMessageFor(model => model.Mobile)
@Html.LabelFor(model => model.Email, new { @class = "" }) @Html.TextBoxFor(model => model.Email, new { @class = "form-control", placeholder = "Enter email address...", type = "text" }) @Html.ValidationMessageFor(model => model.Email)
@Html.LabelFor(model => model.PhotoURL, new { @class = "" })
Width:   Height: Crop Image
Employee Image

}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Edit.cshtml

@model JCropMVC.Models.Employee

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm()) { @Html.AntiForgeryToken() @*
*@

Employee


@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.Id)
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.FatherName, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.FatherName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FatherName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
@*
@Html.LabelFor(model => model.PhotoURL, htmlAttributes: new { @class = "" })
@Html.EditorFor(model => model.PhotoURL, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PhotoURL, "", new { @class = "text-danger" })
*@
@Html.LabelFor(model => model.PhotoURL, new { @class = "" })
Width:   Height: Crop Image
Employee Image

@*
*@ }
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Index.cshtml

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.FatherName) @Html.DisplayNameFor(model => model.Designation) @Html.DisplayNameFor(model => model.Mobile) @Html.DisplayNameFor(model => model.Email) @Html.DisplayNameFor(model => model.PhotoURL)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.FatherName) @Html.DisplayFor(modelItem => item.Designation) @Html.DisplayFor(modelItem => item.Mobile) @Html.DisplayFor(modelItem => item.Email) @**@ @*@Html.DisplayFor(modelItem => item.PhotoURL)*@ @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id })

Delete.cshtml

@model JCropMVC.Models.Employee

@{
    ViewBag.Title = "Delete";
}

Delete

Are you sure you want to delete this?

Employee


@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.DisplayNameFor(model => model.FatherName)
@Html.DisplayFor(model => model.FatherName)
@Html.DisplayNameFor(model => model.Designation)
@Html.DisplayFor(model => model.Designation)
@Html.DisplayNameFor(model => model.Mobile)
@Html.DisplayFor(model => model.Mobile)
@Html.DisplayNameFor(model => model.Email)
@Html.DisplayFor(model => model.Email)
@Html.DisplayNameFor(model => model.PhotoURL)
@Html.DisplayFor(model => model.PhotoURL)
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
| @Html.ActionLink("Back to List", "Index")
}

Step 9: Add image folders
Add Image folders and sub folders (Deafult and Photo) as follows. Add blank photo in the Default folder to show blank photo for the employee.

0108_05

Step 10: Add Employee link
Add Employee link in the nav bar of _Layout page as follows.

                

Step 11: Run the application
Now run the application. Click Employee link in the nav bar. You can View, add, modify and delete employee information. If you go to the create or edit page, you have an option to upload photo and have option to crop the image and then save the image with employee information. Yes! You are done. Let’s cheers!

0108_06