Tuesday, 15 March 2016

Upload, crop Images and convert to Base64string in MVC

Upload, crop Images  and convert to Base64string in MVC


Step1: UserImageCrop.cshtml  --- view Page

@model Laysous.Cinetot.WebAPP.Models.UserImageCrop
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_UserPostLayout.cshtml";
}









<script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>

    <link href="~/JsLibraries/Jcrop-v0.9.12/css/jquery.Jcrop.min.css" rel="stylesheet" />
    <script src="~/JsLibraries/Jcrop-v0.9.12/js/jquery.Jcrop.min.js"></script>

    <script src="~/JsLibraries/file-upload/jquery.fileupload.js"></script>
    <script src="~/JsLibraries/file-upload/jquery.fileupload-ui.js"></script>
    <script src="~/JsLibraries/file-upload/jquery.iframe-transport.js"></script>




<div class="register_banner">
    <div class="container">
        <div class="row">
            <center>
                @using (Html.BeginForm("imgcrop", "UserImageCrop"))
                {
                    <h2 class="fs-title">Woow..!!! Upload your profile pic to connect with your bestie...</h2>
                    <h3 class="fs-subtitle"></h3>
                    <div class="col-md-6 col-md-offset-3">
                        <center><div id="dvPreview" name="dvPreview" class="prw"><img id="imgPreview" name="imgPreview" src="~/images/Browse.png" style="padding: 10px;border-radius: 100%;margin-bottom: 20px;" /></div></center>                       
                        <br><br>
                        @Html.Hidden("UploadedImagePath", string.Empty, new { id = "hf-uploaded-image-path" })
                        @Html.HiddenFor(m => m.CroppedImagePath, new { id = "hf-cropped-image-path" })

                        <p>@Html.TextBoxFor(m => m.MyFile, new { id = "fu-my-simple-upload", type = "file" })</p>
                        <br />
                        <div class="redbg1"><center><h3><a id="hl-start-upload" href="#">Start Upload</a></h3></center></div>                      
                        <div id="crop-image-area" style="display:none;">
                            <p><a href="#" id="hl-crop-image">Crop Image</a></p>
                            <p><img id="uploaded-image" src="~/images/advertise_banner.jpg" /></p>
                            <p><img id="my-cropped-image" src="#" style="display:none;" /></p>
                            <p><input type="submit" value="Submit" id="btn-my-submit" style="display: none;" /></p>
                        </div>                       
                        <br><br>
                        <font color="red">(or)</font>
                        <br><br>
                        <h4><a href="../UserRegistration/UserRegisterStep2">SKIP</a></h4>
                        <div class="errmsg">@TempData["Msg"]</div>
                    </div>
                }
            </center>
        </div>
    </div>
    </div>


    <script type="text/javascript">

        //************************************** JavaScript for ajax file upload **************************************
        var jqXHRData;

        $(document).ready(function () {

            'use strict';

            $('#fu-my-simple-upload').fileupload({
                url: '/File/UploadFile',
                dataType: 'json',
                add: function (e, data) {
                    jqXHRData = data;
                },
                done: function (event, data) {
                    if (data.result.isUploaded) {

                        $("#hf-uploaded-image-path").val(data.result.filePath);

                        destroyCrop();

                        $("#uploaded-image").attr("src", data.result.filePath + "?t=" + new Date().getTime());

                        initCrop();

                        $("#crop-image-area").fadeIn("slow");
                    } else {

                    }
                },
                fail: function (event, data) {
                    if (data.files[0].error) {
                        alert(data.files[0].error);
                    }
                }
            });
        });

        $("#hl-start-upload").on('click', function () {
            if (jqXHRData) {
                jqXHRData.submit();
            }
            return false;
        });
        //************************************** JavaScript for ajax file upload END **************************************




        //************************************** JavaScript for cropping of image *****************************************
        var imageCropWidth = 512;
        var imageCropHeight = 512;
        var cropPointX = 0;
        var cropPointY = 0;

        $("#hl-crop-image").on("click", function (e) {
            e.preventDefault();
            cropImage();
        });

        function initCrop() {
            $('#uploaded-image').Jcrop({
                onChange: setCoordsAndImgSize,
                aspectRatio: 1,
                minSize: [250, 250],
                maxSize: [512, 512],
                setSelect: [140, 180, 160, 180]
              
            });
        }

        function destroyCrop() {
            var jcropApi = $('#uploaded-image').data('Jcrop');

            if (jcropApi !== undefined) {
                jcropApi.destroy();
                $('#uploaded-image').attr('style', "").attr("src", "");
            }
        }

        function setCoordsAndImgSize(e) {

            imageCropWidth = 100+ e.w;
            imageCropHeight = 100 +e.h;

            cropPointX =  e.x;
            cropPointY =  e.y;
          
        }

        function cropImage() {

            if (imageCropWidth == 0 && imageCropHeight == 0) {
                alert("Please select crop area.");
                return;
            }

            $.ajax({
                url: '/Image/CropImage',
                type: 'POST',
                data: {
                    imagePath: $("#hf-uploaded-image-path").val(),
                    cropPointX: cropPointX,
                    cropPointY: cropPointY,
                    imageCropWidth: imageCropWidth,
                    imageCropHeight: imageCropHeight
                },
                success: function (data) {

                    $("#hf-cropped-image-path").val(data.photoPath);                 
                    $("#my-cropped-image")
                        .attr("src", data.photoPath + "?t=" + new Date().getTime())
                        .show();

                    $("#btn-my-submit").fadeIn("slow");
                },
                error: function (data) { }
            });
        }

        //************************************** JavaScript for cropping of image END **************************************

    </script>


Step2: UserImageCrop.cs ------------- Model Page


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Laysous.Cinetot.WebAPP.Models
{
    public class UserImageCrop
    {
        public HttpPostedFileBase MyFile { get; set; }

        public string CroppedImagePath { get; set; }
    }
}



Step3: UserImageCrop.cs ------------- Controller Page


using Laysous.Cinetot.WebAPP.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Laysous.Cinetot.WebAPP.Controllers
{
    public class UserImageCropController : Controller
    {
        // GET: UserImageCrop
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult imgcrop(UserImageCrop model)
        {
            string imagePath = Server.MapPath("~/" + model.CroppedImagePath);          
            using (Image image = Image.FromFile(imagePath))
            {
                using (MemoryStream m = new MemoryStream())
                {
                    image.Save(m, image.RawFormat);
                    byte[] imageBytes = m.ToArray();
                    string value = Convert.ToBase64String(imageBytes);
                    Session["Image"] = value.ToString();
                    System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Temp"));
                    foreach (FileInfo file in di.GetFiles())
                    {
                        if (file.Name != System.IO.Path.GetFileName(model.CroppedImagePath))
                        {
                            file.Delete();
                        }
                    }
                    return RedirectToAction("UserRegister", "UserRegistration");
                }
            }
        }
        public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();               
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }
    }
}

step 4: FileController.cs

using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace TestImageUploadAndCrop.Controllers
{
    public class FileController : Controller
    {
        #region Actions

        [HttpPost]
        public ActionResult UploadFile()
        {
            HttpPostedFileBase myFile = Request.Files["MyFile"];
            bool isUploaded = false;

            string tempFolderName = ConfigurationManager.AppSettings["Image.TempFolderName"];

            if (myFile != null && myFile.ContentLength != 0)
            {
                string tempFolderPath = Server.MapPath("~/" + tempFolderName);

                if (FileHelper.CreateFolderIfNeeded(tempFolderPath))
                {
                    try
                    {
                        myFile.SaveAs(Path.Combine(tempFolderPath, myFile.FileName));
                        isUploaded = true;
                    }
                    catch (Exception) {  /*TODO: You must process this exception.*/}
                }
            }

            string filePath = string.Concat("/", tempFolderName, "/", myFile.FileName);
            return Json(new { isUploaded, filePath }, "text/html");
        }

        #endregion
    }
}


Step 5: ImageController.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace TestImageUploadAndCrop.Controllers
{
    public class ImageController : Controller
    {
        [HttpPost]
        public ActionResult CropImage(
            string imagePath,
            int? cropPointX,
            int? cropPointY,
            int? imageCropWidth,
            int? imageCropHeight)
        {
            if (string.IsNullOrEmpty(imagePath)
                || !cropPointX.HasValue
                || !cropPointY.HasValue
                || !imageCropWidth.HasValue
                || !imageCropHeight.HasValue)
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
            }

            byte[] imageBytes = System.IO.File.ReadAllBytes(Server.MapPath(imagePath));
            byte[] croppedImage = ImageHelper.CropImage(imageBytes, cropPointX.Value, cropPointY.Value, imageCropWidth.Value, imageCropHeight.Value);

            string tempFolderName = Server.MapPath("~/" + ConfigurationManager.AppSettings["Image.TempFolderName"]);

            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(imagePath);
            string fileName = Path.GetFileName(imagePath).Replace(fileNameWithoutExtension, fileNameWithoutExtension + "_cropped");

            try
            {
                FileHelper.SaveFile(croppedImage, Path.Combine(tempFolderName, fileName));
            }
            catch (Exception)
            {
                //Log an error    
                return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
            }

            string photoPath = string.Concat("/", ConfigurationManager.AppSettings["Image.TempFolderName"], "/", fileName);
            return Json(new { photoPath = photoPath }, JsonRequestBehavior.AllowGet);
        }
    }
}

Step6:FileHelper.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;

namespace TestImageUploadAndCrop
{
    public static class FileHelper
    {
        public static void SaveFile(byte[] content, string path)
        {
            string filePath = GetFileFullPath(path);
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }

            //Save file
            using (FileStream str = File.Create(filePath))
            {
                str.Write(content, 0, content.Length);
            }
        }

        public static string GetFileFullPath(string path)
        {
            string relName = path.StartsWith("~") ? path : path.StartsWith("/") ? string.Concat("~", path) : path;

            string filePath = relName.StartsWith("~") ? HostingEnvironment.MapPath(relName) : relName;

            return filePath;
        }

        public static bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    /*TODO: You must process this exception.*/
                    result = false;
                }
            }
            return result;
        }
    }
}


Step 7: ImageHelper.cs

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace TestImageUploadAndCrop
{
    public static class ImageHelper
    {
        public static byte[] CropImage(byte[] content, int x, int y, int width, int height)
        {
            using (MemoryStream stream = new MemoryStream(content))
            {
                return CropImage(stream, x, y, width, height);
            }
        }

        public static byte[] CropImage(Stream content, int x, int y, int width, int height)
        {
            //Parsing stream to bitmap
            using (Bitmap sourceBitmap = new Bitmap(content))
            {
                //Get new dimensions
                double sourceWidth = Convert.ToDouble(sourceBitmap.Size.Width);
                double sourceHeight = Convert.ToDouble(sourceBitmap.Size.Height);
                Rectangle cropRect = new Rectangle(x, y, width, height);

                //Creating new bitmap with valid dimensions
                using (Bitmap newBitMap = new Bitmap(cropRect.Width, cropRect.Height))
                {
                    using (Graphics g = Graphics.FromImage(newBitMap))
                    {
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        g.CompositingQuality = CompositingQuality.HighQuality;

                        g.DrawImage(sourceBitmap, new Rectangle(0, 0, newBitMap.Width, newBitMap.Height), cropRect, GraphicsUnit.Pixel);

                        return GetBitmapBytes(newBitMap);
                    }
                }
            }
        }

        public static byte[] GetBitmapBytes(Bitmap source)
        {
            //Settings to increase quality of the image
            ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[4];
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

            //Temporary stream to save the bitmap
            using (MemoryStream tmpStream = new MemoryStream())
            {
                source.Save(tmpStream, codec, parameters);

                //Get image bytes from temporary stream
                byte[] result = new byte[tmpStream.Length];
                tmpStream.Seek(0, SeekOrigin.Begin);
                tmpStream.Read(result, 0, (int)tmpStream.Length);

                return result;
            }
        }
    }}

Output




 

No comments: