Cropper: How To Upload Cropped Image To Server ?

Created on 24 Oct 2015  路  29Comments  路  Source: fengyuanchen/cropper

I did not success upload cropped image to server. I didnt use php.

Most helpful comment

I solved saving the cropped image by
// client side
var cropcanvas = $('#imagetocrop').cropper('getCroppedCanvas');
var croppng = cropcanvas.toDataURL("image/png");

$.ajax({
type: 'POST',
url: 'savecropimage.php',
data: {
pngimageData: croppng,
filename: 'test.png'
},
success: function(output) {
}
})
//server side php
$filename = $_POST['filename'];
$img = $_POST['pngimageData'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents($filename, $data);

All 29 comments

JavaScript:

$().cropper('getCroppedCanvas').toBlob(function (blob) {
  var formData = new FormData();

  formData.append('croppedImage', blob);

  $.ajax('upload.php', {
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function () {
      console.log('Upload success');
    },
    error: function () {
      console.log('Upload error');
    }
  });
}/* , 'image/jpeg' */);

PHP:

// upload.php
var $file = $_FILES['croppedImage'];

// Handle the file
// ...

I saw that codes in your page. But i cannot take image data.Ajax never work. I wanna press a button and send cropped image file ($_FILES['croppedImage']) to a php page. What is wrong? Html or javascript?

please show me a way. I only want send to server cropped image.

I believe what Cropper does is it will send the original image to the server along with some meta data like where to start crop and how much to crop.

With that you can handle the cropping on the server side yourself. This is what I have seen so far. And I have tested it on my own project(though I am using PHP).

Not sure whether it will send the cropped image to the server at the moment. Maybe the author can answer it.

I think, should be a upload button in Demo App

@emrevural20
I had pointed out how to upload the cropped image to server side, the other things:

  • How to read an image from file input when user choose it
  • How to create an image and start the cropper on it
  • How to trigger to call the getCroppedCanvas method

You should handle them yourself.

But problem is the "toBlob" function called in this. It is undefined.

The toBlob API is not implemented in most browsers, but there is a polyfill:
https://github.com/eligrey/canvas-toBlob.js

Can somebody post working code, I just want to upload image to server.I am getting FormData as empty object.
Please post detail code if anybody has solved this?

I solved saving the cropped image by
// client side
var cropcanvas = $('#imagetocrop').cropper('getCroppedCanvas');
var croppng = cropcanvas.toDataURL("image/png");

$.ajax({
type: 'POST',
url: 'savecropimage.php',
data: {
pngimageData: croppng,
filename: 'test.png'
},
success: function(output) {
}
})
//server side php
$filename = $_POST['filename'];
$img = $_POST['pngimageData'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents($filename, $data);

In savecropimage.php

$filename = $_POST['filename'];
$img = $_POST['pngimageData'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);

file_put_contents($filename, $data);

Warning: file_put_contents(): Filename cannot be empty in .........
PLEASE HELP..

hey @fengyuanchen . First of all, thanks for this library, it's awesome.

I'm writting here now because I have a very weird problem and I can't find issues where other people might be experiencing the same.

The problem is the following:

_When I trigger the event to upload the cropped selection on a new image, sometimes it uploads me an image of 160x160 (as desired) and sometimes it uploads me a smaller square image. This is a problem because I need to display that cropped version elsewhere in 160x160 and if it was saved in let's say 80x80, when I try to display it, it's blured/pixeled because of a quality issue._

I have a fixed crop box with aspect ratio 1 and 160 x 160 pixels. I desire all my images that are the result of cropping part of a bigger image to have that size. Here's the code I'm using.

Check that I also do a console.log just to see that right before making the ajax call, the size of the CropBox is the desired one (and what I get logged as a result is fine, but it's still not the size of the saved image afterwards).

The reason why I'm using ready and not built as suggested many times is because it just doesn't work for me with built at all.

``````

Any clue of what am I doing wrong?

Thanks,

Diego

@dcaliri Don't care about the crop box size, just resize the cropped image in getCroppedCanvas method:

$image.cropper('getCroppedCanvas', { 
  width: 160, 
  height: 160 
})

html

<img id="imagecrop" src="image.jpg" />
<button  type="submit" name="save" value="crop" id="crop">Save</button>

js code

var cropper;
var image = $('#imagecrop');
cropper = new Cropper(image, {
                        aspectRatio: 1 ,
                        zoomOnWheel: false,
                        viewMode: 1,
                        built: function () {
                            image.cropper('setCropBoxData', cropBoxData);
                            image.cropper('setCanvasData', canvasData);
                        },
                        ready: function () {
                            var containerData = cropper.getContainerData();
                            var cropBoxData = cropper.getCropBoxData();
                        }
                    });

$('button#crop').on('click', function (event) {
cropper.getCroppedCanvas().toBlob(function (blob) {
                    var formData = new FormData();
                    formData.append('croppedImage', blob);

                    $.ajax("action.php", {
                        method: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function () {
                            alert('Upload success');
                            location.reload();
                        },
                        error: function () {
                            alert('Upload error');
                        }
                    });
                });
});

action.php

        $file_to_upload = $_FILES['croppedImage']['tmp_name'];
        $file_name = 'cropped.jpg';
        move_uploaded_file($file_to_upload, $file_name);

I get another issue, when I'm sending cropped image with blob its can't send it as a gif file....

@MrCherevko After cropped, only the first frame of a GIF is left.

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage

$().cropper('getCroppedCanvas').toBlob(function (blob) {

$.ajax('upload.php', {
  method: "PUT",
  data: blob,
  processData: false,
  contentType: false,
  success: function () {
    console.log('Upload success');
  },
  error: function () {
    console.log('Upload error');
  }
});

});

We insert blob into ajax data. Without "new FormData"

im trying to send the cropped image to database for several hours but I couldn't find the solution,

any one give me a hint please!!!!

Spent considerable time to pass the learning curve and integrating this wonderful plugin into ColdFusion app (read previously a posting of PHP example), I think that it may be useful to share this work-able example with some CF users to save people's time:

script almost completely copied and pasted from the owner fengyuanchen:

`

`

CF Template

<cfif IsDefined("form.cropperImage")> <cfif IsImageFile(cropperImage)> <cfset myImage = ImageRead(cropperImage)> <cfset ImageWrite(myImage,"c:\tmp\tested.jpg")> <cffile action="write" addNewLine = "yes" output="#now()#: IsImageFile: #IsImageFile(cropperImage)#" file="c:\tmp\imagetested.txt"> </cfif> </cfif>

C:tmptested.png: written on server site. image types can be supported such as png, jpg, gif whatever you prefer.

Hope this helps.

Sample Screenshots

googledev

base

results

tested

may I ask to you? how to add "input_text()" in the group form for add image name???
$("#image").cropper();
$('#btnUpload').click(function(){
$("#image").cropper('getCroppedCanvas').toBlob(function (blob){
var formData = new FormData();

            formData.append('croppedImage', blob);

            $.ajax({
                method: "POST",
                data: formData,
                processData: false,
                contentType: false,
                url: '<?php echo base_url() ?>uploadimages/upload',
                success: function (){
                    alert('Upload success');
                    window.location.href="<?php echo base_url() ?>uploadimages";
                },
                error: function (){
                    alert('Error data');
                }
            });
        });
    });

if i understand correctly you can formData.append('image_name',input_text()) before sending it to backend.

may I ask to you? how to add "input_text()" in the group form for add image name???
$("#image").cropper();
$('#btnUpload').click(function(){
$("#image").cropper('getCroppedCanvas').toBlob(function (blob){
var formData = new FormData();

            formData.append('croppedImage', blob);

            $.ajax({
                method: "POST",
                data: formData,
                processData: false,
                contentType: false,
                url: '<?php echo base_url() ?>uploadimages/upload',
                success: function (){
                    alert('Upload success');
                    window.location.href="<?php echo base_url() ?>uploadimages";
                },
                error: function (){
                    alert('Error data');
                }
            });
        });
    });

html

<img id="imagecrop" src="image.jpg" />
<button  type="submit" name="save" value="crop" id="crop">Save</button>

js code

var cropper;
var image = $('#imagecrop');
cropper = new Cropper(image, {
                        aspectRatio: 1 ,
                        zoomOnWheel: false,
                        viewMode: 1,
                        built: function () {
                            image.cropper('setCropBoxData', cropBoxData);
                            image.cropper('setCanvasData', canvasData);
                        },
                        ready: function () {
                            var containerData = cropper.getContainerData();
                            var cropBoxData = cropper.getCropBoxData();
                        }
                    });

$('button#crop').on('click', function (event) {
cropper.getCroppedCanvas().toBlob(function (blob) {
                    var formData = new FormData();
                    formData.append('croppedImage', blob);

                    $.ajax("action.php", {
                        method: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function () {
                            alert('Upload success');
                            location.reload();
                        },
                        error: function () {
                            alert('Upload error');
                        }
                    });
                });
});

action.php

        $file_to_upload = $_FILES['croppedImage']['tmp_name'];
        $file_name = 'cropped.jpg';
        move_uploaded_file($file_to_upload, $file_name);

how do we add file types in the codding above?

@koharabdul

formData.append(name, value, filename); // define file extension in the filename

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

@fengyuanchen
I have a question regarding the upload, something that I noticed just recently when I started refactoring the image uploader.
The original input file is 'image/jpeg', however, after I edit it with the plugin and upload it to server (the way you describe at the top of the thread) it transforms into 'image/png'. Is this the expected behaviour?

Want to restore the mime type of the output image?

var mimeType = getMimeTypeFromTheOriginalImage(image);

cropper.getCroppedCanvas().toBlob((blob) => {
  // ...
}, mimeType);

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

Want to restore the mime type of the output image?

var mimeType = getMimeTypeFromTheOriginalImage(image);

cropper.getCroppedCanvas().toBlob((blob) => {
  // ...
}, mimeType);

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

cheers! already solved it, forgot to mention

Hi,
Can someone send working sample of saving cropping file ?
I am newbie and need it.
Thank you for your helps

Hi,
Can someone send working sample of saving cropping file ?
I am newbie and need it.
Thank you for your helps

Hello, you find working sample? i need too

Hi,
Can someone send working sample of saving cropping file ?
I am newbie and need it.
Thank you for your helps

have you take a look to https://github.com/pavelakafoks/cropper/tree/master/examples/crop-avatar?

Also, if you can use base64 encoding, sending data to your server become very simple.
Starting from the blob, your can use this in your javascript

var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
    var base64data = reader.result;
   // POST base64data with ajax
}

and a simple endpoint that accepts a string as body parameter
in c# a snippet can be

var uploadFile = Path.Combine(uploadTempFolder, Guid.NewGuid().ToString());
// input.CroppedBase64 = the base64 string created above
if (input.CroppedBase64.StartsWith("data:image/png;base64,"))
    input.CroppedBase64 = input.CoppedBase64.Substring("data:image/png;base64,".Length);
byte[] imgBytes = Convert.FromBase64String(input.CroppedBase64);

using (var imageFile = new FileStream(uploadFile, FileMode.Create))
{
    imageFile.Write(imgBytes, 0, imgBytes.Length);
    imageFile.Flush();
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

steefaan picture steefaan  路  6Comments

richdenis86 picture richdenis86  路  8Comments

WillJW picture WillJW  路  3Comments

sohaibameen picture sohaibameen  路  4Comments

zilions picture zilions  路  3Comments