Home > DeveloperSection > Forums > How to Crop And save Image Using Jcrop .js in asp.net
Ankit Singh

Total Post:341

Points:2389
Posted on    December-29-2015 9:12 PM

 .NET .NET  JQuery 
Ratings:


 4 Reply(s)
 933  View(s)
Rate this:
I want to use  Crop And save Image Using Jcrop .js in asp.net How to do this please help me.


aditya kumar Patel

Total Post:250

Points:1782
Posted on    December-29-2015 9:27 PM

I am using jcrop for crop image in asp.net . following below code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ImageCrop.aspx.cs" Inherits="Forumasp.CroupImage.ImageCroup" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Crop Image using crop plugin</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="jquery.Jcrop.js" type="text/javascript"></script>
    <link href="jquery.Jcrop.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
        <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];
                    $('#btnCrop').hide();
                    $('.jcrop-holder').css("display", "none");
                    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>
        <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="5" width="5"></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" />
    </form>
</body>
</html>

using System;
using System.Drawing;
using System.IO;
using Image = System.Drawing.Image;
namespace Forumasp.CroupImage
{
    public partial class ImageCroup : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Upload(object sender, EventArgs e)
        {
            try
            {
                string base64 = Request.Form["imgCropped"];
                byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
                using (System.IO.FileStream stream = new System.IO.FileStream(Server.MapPath("~/Images/Cropped.png"), System.IO.FileMode.Create))
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Flush();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}


Modified On Dec-30-2015 01:51:12 PM

Chintoo Semi

Total Post:135

Points:947
Posted on    December-30-2015 6:54 AM

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Jcrop.aspx.cs" Inherits="Forumasp.Jcrop" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">
    <script src="Scripts/jquery-2.1.4.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
    <link href="Content/bootstrap-theme.css" rel="stylesheet" />
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <link href="CroupImage/jquery.Jcrop.css" rel="stylesheet" />
    <script src="CroupImage/jquery.Jcrop.js"></script>
    <script>
        $(function () {
            var jcrop_api;
            var canvas;
            function initCrop(width, height) {            
                $('#imgUser').Jcrop({
                    onChange: updatePreview,
                    onSelect: updatePreview,
                    trueSize: [width, height],
                    aspectRatio: 1,
                    bgColor: '',
                    bgOpacity: .4
                }, function () {
                    jcrop_api = this;
                    jcrop_api.animateTo([100, 100, 400, 400]);
                });

            }
            function updatePreview(c) {
                if (parseInt(c.w) > 0) {
                    var imageObj = $("#imgUser")[0];
                    canvas = $("#preview")[0];
                    var context = canvas.getContext("2d");
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    context.restore();
                    context.drawImage(imageObj, c.x, c.y, c.w, c.h, 0, 0, canvas.width, canvas.height);
                    $('#imgCropped').val(canvas.toDataURL());
                }

            }

            var cropDiag;
            $("input[name='userimage']").change(function (event) {
                //var mb = $('#imagedata').html();
                //$(".modal-body").html(mb);
                //$('#dialog-cropImage').html("");
                $('#userpopup').modal({
                    backdrop: 'static'
                }, 'show');
                $('#imgUser').removeAttr('src', '');
                showImage(this, $('#imgUser'));
            });

            //$('#btnCrop').click(function () {
            //    $('#frmUserDetails').submit();
            //    jcrop_api.destroy();
            //});

            //$('#btncancel, #Close-cropbox').click(function () {
            //    $('input:file').val("");
            //    jcrop_api.destroy();
            //    jcrop_api = null;
            //    $('#dialog-cropImage').modal('hide');
            //});
         
            $('#imgUser').load(function () {
                debugger;              
                var imgwidth = $('#imgUser').width();
                var imgheight = $('#imgUser').height();
                var imgval = imgwidth / imgheight;
                var diagWidth = $("#dialog-cropImage").width();
                if (imgval > 1) {
                    var ratio = diagWidth / imgwidth;
                    $('#imgUser').width(imgwidth * ratio);
                    $('#imgUser').height(imgheight * ratio);
                    $('#dialog-cropImage').height((imgheight * ratio));
                }
                else {
                    var ratio = $("#dialog-cropImage").height() / imgheight;
                    $('#imgUser').width(imgwidth * ratio);
                    $('#imgUser').height(imgheight * ratio);
                    $('#dialog-cropImage').css('max-width', (imgwidth * ratio) + 32);
                }
                initCrop(this.naturalWidth, this.naturalHeight);
            });

            function showImage(input, imageInput, width, height) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $(imageInput)
                            .attr('src', e.target.result)
                            .width(width)
                            .height(height);
                    };
                    reader.readAsDataURL(input.files[0]);
                }
            }
        });
    </script>
</head>
<body>
    <input type="file" name="userimage" size="5">
    <%--<div style="padding: 10px; background: #f00;width: 810px;"  id="imagedata">
        <div id="dialog-cropImage" class="container" title="Force LMS&trade;" style="overflow: hidden; height: 600px; width: 790px; background: black;">
            <img id="imgUser" alt="Crop Image" style="border: none;" />
            <canvas id="preview" width="300" height="300" style="overflow: hidden; visibility: hidden;"></canvas>
        </div>
    </div>--%>


    <div class="modal fade" id="userpopup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content" style="overflow: hidden; width: 820px;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" id="Close-cropbox" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">User Profile Image</h4>
                </div>
                <div class="modal-body">
                    <div id="dialog-cropImage" class="container" title="Force LMS&trade;" style="overflow: hidden; height: 600px; width: 790px; background: black;">
                        <img id="imgUser" alt="Crop Image" style="border: none;" />
                        <canvas id="preview" width="300" height="300" style="overflow: hidden; visibility: hidden;"></canvas>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="button" id="btnCrop" value="Ok" />
                    <input type="button" id="btncancel" value="Cancel" />

                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>

    <style>
        img {
            max-width: 100%;
        }
    </style>
</body>
</html>


aditya kumar Patel

Total Post:250

Points:1782
Posted on    December-30-2015 1:51 PM

For Image Resize
 $('#imgUser').load(function () {
            debugger;
            $('#userpopup').fadeIn(500);
            var imgwidth = $('#imgUser').width();
            var imgheight = $('#imgUser').height();
            var imgval = imgwidth / imgheight;
            var diagWidth = $("#dialog-cropImage").width();
            if (imgval > 1) {
                var ratio = diagWidth / imgwidth;
                $('#imgUser').width(imgwidth * ratio);
                $('#imgUser').height(imgheight * ratio);
                $('#dialog-cropImage').height((imgheight * ratio));
            }
            else {
                var ratio = $("#dialog-cropImage").height() / imgheight;
                $('#imgUser').width(imgwidth * ratio);
                $('#imgUser').height(imgheight * ratio);
                $('#dialog-cropImage').css('max-width', (imgwidth * ratio) + 32);
            }
            initCrop(this.naturalWidth, this.naturalHeight);
        });

aditya kumar Patel

Total Post:250

Points:1782
Posted on    December-30-2015 2:33 PM

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Share/_Layouthome.cshtml";
}
<link href="/Content/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="/Content/bootstrap-theme.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-2.1.4.js" type="text/javascript"></script>
<script src="/Scripts/bootstrap.js" type="text/javascript"></script>
<script src="/Scripts/jquery.Jcrop.min.js" type="text/javascript"></script>
<link href="/Content/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" />
<script>
    $(function () {
        var jcrop_api;
        var canvas;
        function initCrop(width, height) {
            $('#imgUser').Jcrop({
                onChange: updatePreview,
                onSelect: updatePreview,
                trueSize: [width, height],
                aspectRatio: 1,
                bgColor: '',
                bgOpacity: .4
            }, function () {
                jcrop_api = this;
                jcrop_api.animateTo([100, 100, 400, 400]);
            });

        }
        function updatePreview(c) {
            if (parseInt(c.w) > 0) {
                var imageObj = $("#imgUser")[0];
                canvas = $("#preview")[0];
                var context = canvas.getContext("2d");
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.restore();
                context.drawImage(imageObj, c.x, c.y, c.w, c.h, 0, 0, canvas.width, canvas.height);
                $('#imgCropped').val(canvas.toDataURL());
            }

        }

        var cropDiag;
        $("input[name='userimage']").change(function (event) {
            //var mb = $('#imagedata').html();
            //$(".modal-body").html(mb);
            //$('#dialog-cropImage').html("");
            $('#userpopup').modal({
                backdrop: 'static'
            }, 'show');
            $('#imgUser').removeAttr('src', '');
            showImage(this, $('#imgUser'));
        });



        $('#imgUser').load(function () {
            debugger;
            $('#userpopup').fadeIn(500);

            var imgwidth = $('#imgUser').width();
            var imgheight = $('#imgUser').height();
            var imgval = imgwidth / imgheight;
            var diagWidth = $("#dialog-cropImage").width();
            if (imgval > 1) {
                var ratio = diagWidth / imgwidth;
                $('#imgUser').width(imgwidth * ratio);
                $('#imgUser').height(imgheight * ratio);
                $('#dialog-cropImage').height((imgheight * ratio));
            }
            else {
                var ratio = $("#dialog-cropImage").height() / imgheight;
                $('#imgUser').width(imgwidth * ratio);
                $('#imgUser').height(imgheight * ratio);
                $('#dialog-cropImage').css('max-width', (imgwidth * ratio) + 32);
                $('.modal-content').width((diagWidth + 30));
                $('#dialog-cropImage').height((imgheight * ratio));
            }
            initCrop(this.naturalWidth, this.naturalHeight);
        });

        function showImage(input, imageInput, width, height) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $(imageInput)
                            .attr('src', e.target.result)
                            .width(width)
                            .height(height);
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
    });
</script>
<input type="file" name="userimage" size="5">
@if (!Request.Browser.IsMobileDevice)
{

    <div class="modal fade" id="userpopup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
        aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content" style="overflow: hidden; width: 820px;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" id="Close-cropbox" aria-hidden="true">
                        &times;</button>
                    <h4 class="modal-title">
                        User Profile Image</h4>
                </div>
                <div class="modal-body">
                    <div id="dialog-cropImage" class="container" title="Force LMS&trade;" style="overflow: hidden;
                        height: 600px; width: 790px; background: black;">
                        <img id="imgUser" alt="Crop Image" style="border: none;" />
                        <canvas id="preview" width="300" height="300" style="overflow: hidden; visibility: hidden;"></canvas>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="button" id="btnCrop" value="Ok" />
                    <input type="button" id="btncancel" value="Cancel" />
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>
}
else
{
    <div class="modal fade" id="userpopup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
        aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content" style="overflow: hidden;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" id="Close-cropbox" aria-hidden="true">
                        &times;</button>
                    <h4 class="modal-title">
                        User Profile Image</h4>
                </div>
                <div class="modal-body">
                    <div id="dialog-cropImage" class="container" title="Force LMS&trade;" style="overflow: hidden;
                        background: black;">
                        <img id="imgUser" alt="Crop Image" style="border: none;" />
                        <canvas id="preview" width="300" height="300" style="overflow: hidden; visibility: hidden;"></canvas>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="button" id="btnCrop" value="Ok" />
                    <input type="button" id="btncancel" value="Cancel" />
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>

}
<style>
    img
    {
        max-width: 100%;
    }
</style>


Modified On Dec-30-2015 02:58:10 PM

Don't want to miss updates? Please click the below button!

Follow MindStick