Crop And Upload image using JQuery and ASP.Net Code

This is a new blog which explains about cropping an image before uploading it to server.

HTML and JQuery Code:

<html xmlns="">
<head runat="server">
    <script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
    $(function () {
        $('#FileUpload1').change(function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                    onChange: SetCoordinates,
                    onSelect: SetCoordinates
            var type = $(this)[0].files['0'].type;
            document.getElementById('hdnFileType').value = type;


        $('#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);
            img.src = $('#Image1').attr("src");
    function SetCoordinates(c) {
    <form id="form1" runat="server">
   <input type="file" id="FileUpload1" accept=".jpg,.png,.gif" />
<br />
<br />
<table border="0" cellpadding="0" cellspacing="5">
            <img id="Image1" src="" alt="" style="display: none" />
            <canvas id="canvas" height="4" width="4"></canvas>
<br />
<input type="button" id="btnCrop" value="Crop" style="display: none" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="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" />
    <asp:HiddenField ID="hdnFileType" runat="server" />

C# Code To Upload Cropped Image:

    protected void Upload(object sender, EventArgs e)
        string base64 = Request.Form["imgCropped"];
        byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
        string fileType = hdnFileType.Value == "image/jpeg" ? ".jpg" : ".png";
        string name = DateTime.Now.ToFileTime().ToString();
        using (FileStream stream = new FileStream(Server.MapPath("~/Images/" + name + fileType), FileMode.Create))
            stream.Write(bytes, 0, bytes.Length);


Output Screen:

image cropping in

Protected by Copyscape


  1. I have similar approach using mvc5


Post a Comment

Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks