Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop image using croppie js and upload in asp.net mvc

Hi i want to crop the image and upload it on server.

i am using croppie js plugins and use get() method to get points to crop it on server by using WebImage class.

Asp.net MVC code

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ImageCrop(FormCollection fc)
    {
                WebImage data = WebImage.GetImageFromRequest();
                if (data != null)
                {
                    int x1, y1, x2, y2;
                    x1 = int.Parse(fc["x1"].ToString());
                    y1 = int.Parse(fc["y1"].ToString());
                    x2 = int.Parse(fc["x2"].ToString());
                    y2 = int.Parse(fc["y2"].ToString());
                    var fileName = Path.GetFileName(data.FileName);
                    fileName = Lawyer_id2 + ".jpeg";
                    var big = Server.MapPath("~/contents/ProfilePictures/big/" + fileName);
                    data.Crop(y1, x1, x2, y2);
                    data.Save(big);

                }

      }

Js code

$uploadCrop = $('#upload-demo').croppie({
    viewport: {
        width: 200,
        height: 200,
        type: 'square'
    },
    boundary: {
        width: 300,
        height: 300
    },
    showZoomer: false,
    mouseWheelZoom: false
});
readFile(fl);
$(".closeModal").on("click", function () {
    $uploadCrop.croppie('result', {
        type: 'canvas',
        size: 'viewport'
    }).then(function (resp) {
        $('.upload-msg').css('display', '');
        popupResult({
            src: resp
        });

    });
    var arr = $uploadCrop.croppie('get').points;
    $("#x1").val(arr[0]);
    $("#y1").val(arr[1]);
    $("#x2").val(arr[2]);
    $("#y2").val(arr[3]);
});  

I get all points in hidden input fields and then pass this points to webimge objects to crop but problem is that the cropped image not maintain the aspect ratio and cropped wrongly, browser side cropping is perfect but when i pass that points to server side for cropping it not works like browser side and i have no clue to solve this.

like image 262
NorCode Avatar asked Jun 24 '16 11:06

NorCode


1 Answers

Cropping is already happening on the client side, and you should only send the result to the server side. There is no need to send cropping points to the server.

Define the Select and Upload button on html, and a div with id="main-cropper"

        <div>
            <div>
                <div id="main-cropper"></div>
                <a class="button actionSelect">
                    <input type="file" id="select" value="Choose Image" accept="image/*">
                </a>
                <button class="actionUpload">Upload</button>
            </div>
        </div>

on JS code, attach the croppie object to the dive, define the viewpoint a boundary, and finally send the request to the server to store the result as blob. On the server side, lets say there will be a Create controller with GetImage action waiting for the request. testFileName.png is assigned as file name, and you can modify it based on your scenario.

        var basic = $('#main-cropper').croppie({
            viewport: { width: 200, height: 300 },
            boundary: { width: 300, height: 400 },
            showZoomer: false
        });

        function readFile(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $('#main-cropper').croppie('bind', {
                        url: e.target.result
                    });
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        $('.actionSelect input').on('change', function () { readFile(this); });
        $('.actionUpload').on('click', function() {
            basic.croppie('result','blob').then(function(blob) {
                var formData = new FormData();
                formData.append('filename', 'testFileName.png');
                formData.append('blob', blob);
                var MyAppUrlSettings = {
                    MyUsefulUrl: '@Url.Action("GetImage","Create")'
                }

                var request = new XMLHttpRequest();
                request.open('POST', MyAppUrlSettings.MyUsefulUrl);
                request.send(formData);
            });
        });

on server, in Create controller:

    [HttpPost]
    public ActionResult GetImage(string filename, HttpPostedFileBase blob)
    {
        var fullPath = "~/Images/" + filename;
        blob.SaveAs(Server.MapPath(fullPath));
        return Json("ok");
    }

It also makes sense to generate uuid string, and set it as file name and store it in database.

like image 117
Aryan Firouzian Avatar answered Oct 03 '22 10:10

Aryan Firouzian