In this article I will explain with an example, how to Crop and Upload Image with Live Thumbnail Preview using jQuery and HTML5 Canvas in ASP.Net MVC Razor.
The image will be cropped using the Jcrop jQuery plugin, and the Live Thumbnail Preview is displayed using HTML5 Canvas and finally the Cropped Image is uploaded and saved in a folder on server using ASP.Net MVC Razor.
 
 
View
The View consists of a FileUpload element, an Image element, a Button, a Submit Button, an HTML5 Canvas elements and some hidden field elements.
Inside the jQuery document ready event handler, a change event handler is assigned to a FileUpload control and a click event handler is assigned to the HTML Button.
When a file is selected in the HTML FileUpload control, it is read using HTML5 FileReader API and then the image is displayed in the Image element and finally the Jcrop jQuery plugin is applied to the Image element.
Note: For more details on Image display using HTML5 File Reader API, please refer my article HTML5 FileReader API Tutorial with example.
 
The Jcrop plugin makes a call to SetCoordinates function on its onChange and onSelect event handlers, which allow us to save the coordinates and dimensions i.e. height and width of the cropped image to the hidden fields.
When the Crop Button is clicked, it first creates an instance of the HTML5 Canvas and then loads the Image into an Image object with an OnLoad event handler.
Inside the OnLoad event handler, the original image is redrawn on the canvas using the saved coordinates and dimensions i.e. height and width of the cropped image.
Finally the base64 string of the cropped image is fetched from the Canvas using the toDataURL method and is saved in the imgCropped hidden field.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Save", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" id="FileUpload1"/>
        <br/>
        <br/>
        <table border="0" cellpadding="0" cellspacing="5">
            <tr>
                <td>
                    <img id="Image1" src="" alt="" style="display: none"/>
                </td>
                <td>
                    <canvas id="canvas" height="5" width="5"></canvas>
                </td>
            </tr>
        </table>
        <br/>
        <input type="button" id="btnCrop" value="Crop" style="display: none"/>
        <input type="submit" id="btnUpload" value="Upload" style="display: none"/>
        <input type="hidden" name="imgX1" id="imgX1"/>
        <input type="hidden" name="imgY1" id="imgY1"/>
        <input type="hidden" name="imgWidth" id="imgWidth"/>
        <input type="hidden" name="imgHeight" id="imgHeight"/>
        <input type="hidden" name="imgCropped" id="imgCropped"/>
    }
 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/tapmodo/Jcrop/master/js/jquery.Jcrop.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#FileUpload1').change(function () {
                $('#Image1').hide();
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#Image1').show();
                    $('#Image1').attr("src", e.target.result);
                    $('#Image1').Jcrop({
                        onChange: SetCoordinates,
                        onSelect: SetCoordinates
                    });
                }
                reader.readAsDataURL($(this)[0].files[0]);
            });
 
            $('#btnCrop').click(function () {
                var x1 = $('#imgX1').val();
                var y1 = $('#imgY1').val();
                var width = $('#imgWidth').val();
                var height = $('#imgHeight').val();
                var canvas = $("#canvas")[0];
                var context = canvas.getContext('2d');
                var img = new Image();
                img.onload = function () {
                    canvas.height = height;
                    canvas.width = width;
                    context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
                    $('#imgCropped').val(canvas.toDataURL());
                    $('#btnUpload').show();
                };
                img.src = $('#Image1').attr("src");
            });
        });
        function SetCoordinates(c) {
            $('#imgX1').val(c.x);
            $('#imgY1').val(c.y);
            $('#imgWidth').val(c.w);
            $('#imgHeight').val(c.h);
            $('#btnCrop').show();
        };
    </script>
</body>
</html>
 
 
Namespaces
You will need to import the following namespace.
using System.IO;
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation for uploading the Cropped Image
This Action method gets called when the Upload Button is clicked. The cropped image is read as BASE64 string from the imgCropped hidden field using its Name from the Request.Form collection and then it is converted to a Byte Array which is ultimately saved in folder using FileStream class.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Save()
    {
        string base64 = Request.Form["imgCropped"];
        byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
        using (FileStream stream = new FileStream(Server.MapPath("~/Images/Cropped.png"), FileMode.Create))
        {
            stream.Write(bytes, 0, bytes.Length);
            stream.Flush();
        }
        return RedirectToAction("Index");
    }
}
 
 
Screenshot
Crop and Upload Image with Thumbnail using jQuery and HTML5 in ASP.Net MVC
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads