How to Crop and Upload image using JQuery

In this blog, I will explain how to crop an image and then upload that image using jQuery. Here you will come to know about preview an image, and then crop that image and finally upload it using jQuery and C# code.  This implementation has been done using jQuery, so no post back only smooth user experience.

Below code will show you how you can crop an image using jQuery and then upload to your desired folder.

HTML and jQuery Code to Crop an Image:

This code snippet contains the jQuery library, jQuery function which will read image and show a preview of the image in a defined container.
<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
    <title></title>
    <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script>
<script type=”text/javascript” src=”http://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]);
            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);
                $(‘#imgCropped’).val(canvas.toDataURL());
                $(‘[id*=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>
</head>
<body>
    <form id=”form1″ runat=”server”>
   <input type=”file” id=”FileUpload1″ accept=”.jpg,.png,.gif” />
<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=”4″ width=”4″></canvas>
        </td>
    </tr>
</table>
<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” />
    </form>
</body>
</html>

C# Code To Upload Cropped Image:

Below code snippet is a server side (C# code) implementation to upload final image to a folder on server.
    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);
            stream.Flush();
        }
    }



Once you will select an image move your cursor over image to crop an image, once area selected click on crop button and then click on upload button to upload the cropped image.
Output Screen:

image cropping in asp.net using jquery
image cropping in asp.net using jquery

 

1 thought on “How to Crop and Upload image using JQuery”

Leave a Comment

RSS
YouTube
YouTube
Instagram