Haneef Puttur

Integrate Croppic to ASP.NET MVC C# – For Cropping Passport Size Picture 3.5cm X 4.5 Cm

Solution :

Integrate Croppic to ASP.NET MVC C# , so that user can upload an image and crop, zoom , rotate the image and save to the assigned folder.

Step 1:

Create one empty Project ASP.NET Web Application in Visual Studio 2013

Step 2 :

Download croppic (Image cropping jquery plugin from croppic.net == > Link  http://croppic.net/croppic.zip

Please note that I have edited the css files to match the folder structure. Please download the entire solution from github and follow it.

Step 3 :

Extract The croppic Folder inside the scripts folder and make sure the folder structure as shown

Step 4:

Create a controller called Croppic and paste following content.

using Newtonsoft.Json;
 using System;
 using System.Drawing;
 using System.Drawing.Drawing2D;
 using System.IO;
 using System.Web;
 using System.Web.Mvc;

//Coding by Haneef puttur

namespace Croppic.Controllers
 {
 public class CroppicController : Controller
 {

public ActionResult Index()
 {
 return View();
 }

[HttpPost]
 public string UploadOriginalImage(HttpPostedFileBase img)
 {
 string folder = Server.MapPath("~/Temp");
 string extension = Path.GetExtension(img.FileName);
 string pic = System.IO.Path.GetFileName(Guid.NewGuid().ToString());
 var tempPath = Path.ChangeExtension(pic, extension);
 string tempFilePath = System.IO.Path.Combine(folder, tempPath);
 img.SaveAs(tempFilePath);
 var image = System.Drawing.Image.FromFile(tempFilePath);
 var result = new
 {
 status = "success",
 width = image.Width,
 height = image.Height,
 url = "../Temp/" + tempPath
 };
 return JsonConvert.SerializeObject(result);
 }

[HttpPost]
 public string CroppedImage(string imgUrl, int imgInitW, int imgInitH, double imgW, double imgH, int imgY1, int imgX1, int cropH, int cropW, int rotation)
 {
 var originalFilePath = Server.MapPath(imgUrl);
 var fileName = CropImage(originalFilePath, imgInitW, imgInitH, (int)imgW, (int)imgH, imgY1, imgX1, cropH, cropW, rotation);

//unlock any pending procss , close any open files and delete temp file
 System.GC.Collect();
 System.GC.WaitForPendingFinalizers();

if (System.IO.File.Exists(originalFilePath))
 {
 System.IO.File.Delete(originalFilePath);

}

var result = new
 {
 status = "success",
 url = "../Cropped/" + fileName
 };

return JsonConvert.SerializeObject(result);
 }

private string CropImage(string originalFilePath, int origW, int origH, int targetW, int targetH, int cropStartY, int cropStartX, int cropH, int cropW, int rotation)
 {
 var originalImage = Image.FromFile(originalFilePath);

//if rotation is required call rotation function
 if (rotation != 0)
 {
 originalImage = RotateImage(originalImage, rotation);
 }

var resizedOriginalImage = new Bitmap(originalImage, targetW, targetH);
 var targetImage = new Bitmap(cropW, cropH);

//create brush to fill image background with white color
 SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 255));

using (Graphics g = Graphics.FromImage(targetImage))
 {
 //fill bg with white color
 g.FillRectangle(brush, 0, 0, cropW, cropH);

g.DrawImage(resizedOriginalImage, new Rectangle(0, 0, cropW, cropH), new Rectangle(cropStartX, cropStartY, cropW, cropH), GraphicsUnit.Pixel);
 g.Dispose();
 }

// put new name for the file
 string newname = System.IO.Path.GetFileName(Guid.NewGuid().ToString());
 // change the extesion of file to jpg
 string ext = ".jpg";
 //build the file name
 string fileName = Path.ChangeExtension(newname, ext);
 //move the file to cropped folder
 var folder = Server.MapPath("~/Cropped");
 string croppedPath = Path.Combine(folder, fileName);
 //save image and force to format conversion to jpg
 targetImage.Save(croppedPath, System.Drawing.Imaging.ImageFormat.Jpeg);
 targetImage.Dispose();
 originalImage.Dispose();
 return fileName;
 }

public static Bitmap RotateImage(Image img, float rotationAngle)
 {
 Bitmap bmp = new Bitmap(img.Width, img.Height);
 Graphics gfx = Graphics.FromImage(bmp);
 gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);
 gfx.RotateTransform(rotationAngle);
 gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);
 gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
 gfx.DrawImage(img, new Point(0, 0));
 gfx.Dispose();
 return bmp;
 }
 }
 }

Step 5

Now Create a Index View under Croppic Folder and paste following content

 @{
 ViewBag.Title = "Index";
 }
 <link href="~/Scripts/Croppic/croppic.css" rel="stylesheet" />
 <script src="~/Scripts/Croppic/croppic.js"></script>
 <div class="container">

<div class="row">
 <div class="col-lg-6">
 <div id="croppic" style="width: 400px; height: 513px; overflow: hidden"></div>
 @*<div id="croppic"></div>*@
 <span class="btn" id="cropContainerHeaderButton">Click to Upload Your Picture</span>
 </div>
 </div>

</div>

<script type="text/javascript">

var croppicContaineroutputMinimal = {
 uploadUrl: '/Croppic/UploadOriginalImage',
 cropUrl: '/Croppic/CroppedImage',
 customUploadButtonId: 'cropContainerHeaderButton',
 modal: true,
 doubleZoomControls: false,
 rotateControls: true,
 loaderHtml: '<div class="loader bubblingG"><span id="bubblingG_1"></span><span id="bubblingG_2"></span><span id="bubblingG_3"></span></div> '
 }
 var cropContaineroutput = new Croppic('croppic', croppicContaineroutputMinimal);

</script>




Step 6

Now in Shared View Folder , Edit the bundle lines of -Layout.cshtml so that jquery is initiated at the beginning of the page as below

 

 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>@ViewBag.Title - My ASP.NET Application</title>
 @Styles.Render("~/Content/css")
 @Scripts.Render("~/bundles/modernizr")

@Scripts.Render("~/bundles/jquery")
 @Scripts.Render("~/bundles/bootstrap")

</head>
 <body>
 <div class="navbar navbar-inverse navbar-fixed-top">
 <div class="container">
 <div class="navbar-header">
 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 </button>
 @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
 </div>
 <div class="navbar-collapse collapse">
 <ul class="nav navbar-nav">
 <li>@Html.ActionLink("Home", "Index", "Home")</li>
 <li>@Html.ActionLink("About", "About", "Home")</li>
 <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
 </ul>
 @Html.Partial("_LoginPartial")
 </div>
 </div>
 </div>
 <div class="container body-content">
 @RenderBody()
 <hr />
 <footer>
 <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
 </footer>
 </div>

@RenderSection("scripts", required: false)
 </body>
 </html>


Create Two Folders in the root

1 : Cropped  (to Store cropped images)

2: Temp (To store temp images)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Now Run the application and browse to Croppic Controller


 

If you wish to change the crop size please hcnage in 2 places:

  1. Croppic / Index.cshtml as below

Also change the dimension in Scripts => Croppic => Croppic.css

 

For complete source code of the project please refer : https://github.com/haneefputtur/ASP_NET_CROPPIC

You can also download the complete solution at : https://github.com/haneefputtur/ASP_NET_CROPPIC/archive/master.zip

 

Exit mobile version