Andrew Simeou
Andrew Simeou

Reputation: 91

How to fix image size posted to server using Javascript Cropper

I'm using Cropper https://github.com/fengyuanchen/cropper in a content management system but I'm struggling to get it to fix the size of a cropped image.

What I want to do is ensure whatever size of crop box is drawn on the canvas also results in a cropped image size of exactly 560px X 420px being passed through to the webserver.

The iQuery code I have at the moment is:-

$("#accept_crop").click(function() {

        var $image = $("#image");
        var cropper = $image.cropper();
        var baseURL = window.location.protocol+'//'+window.location.host;
        var pho_id = $("input[name=pho_id]").val();
        var mem_id = $("input[name=mem_id]").val();
        var photopath = $("input[name=photopath]").val();
        $image.cropper('getCroppedCanvas').toBlob(function (blob) {
                var formData = new FormData();
                formData.append('croppedImage', blob);
                formData.append('pho_id', pho_id);
                formData.append('mem_id', mem_id);
                formData.append('photopath', photopath);
                $.ajax(baseURL+'/path', {
                    method: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function () {
                      console.log('Upload success');
                    },
                    error: function () {
                      console.log('Upload error');
                    }
                });
        }, 'image/jpeg', 0.8);      

});

The cropped image is passing over fine but always results in a variable size depending on the size of the crop box that's drawn. Is there any way of fixing the size on the client site regardless of the crop box so that the image is scaled up or down, without using PHP to re-scale it?

Upvotes: 0

Views: 3243

Answers (2)

Naresh Thakur
Naresh Thakur

Reputation: 335

It can be done, check its documentation:

https://github.com/fengyuanchen/cropper#getcroppedcanvasoptions

You can set destination width and height of the output canvas.

Other thing is you need to set the proportion ration as per your required width and height. 560/420 is proportional to 4/3. Set aspectRatio: 4/3. Which will resize the image to your desired size without compromising anything.

Upvotes: 1

Andrew Simeou
Andrew Simeou

Reputation: 91

This always seems to happen... As soon as I've posted a question, I usually answer it myself shortly afterwards even though I've already spent ages trying to figure it out.

By adding adding the width and height options, this seems to work:-

$image.cropper('getCroppedCanvas', {'width': 560, 'height': 420}).toBlob(function (blob) {

Upvotes: 3

Related Questions