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 postback 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 servcer 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


Protected by Copyscape

Comments

  1. I have similar approach using asp.net mvc5
    http://www.codingsack.com/2015/12/20/run-time-crop-images-with-asp-net-mvc-generic-handler/

    ReplyDelete

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

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers