fengyuanchen / cropper

⚠️ [Deprecated] No longer maintained, please use https://github.com/fengyuanchen/jquery-cropper
MIT License
7.75k stars 1.74k forks source link

How To Upload Cropped Image To Server ? #489

Closed e-vural closed 9 years ago

e-vural commented 9 years ago

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

fengyuanchen commented 9 years ago

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
// ...
e-vural commented 9 years ago

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?

e-vural commented 9 years ago

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

sonic0002 commented 9 years ago

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.

e-vural commented 9 years ago

I think, should be a upload button in Demo App

fengyuanchen commented 9 years ago

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

You should handle them yourself.

mayurmehta commented 8 years ago

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

fengyuanchen commented 8 years ago

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

vivek28111992 commented 8 years ago

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?

kpomservices commented 8 years ago

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);

wagon11 commented 7 years ago

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..

dcaliri commented 6 years ago

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.


  var $image = $('#image');

  $image.cropper({
    aspectRatio: 1,
    zoomable: false,
    cropBoxResizable: false,
    ready: function () {
      $image.cropper('setCropBoxData', {
        height: 160, width: 160
      });
    }
  });

  $(document).ready(function(){
    $('#guardar_crop').click(function() {
      $image.cropper('getCroppedCanvas').toBlob(function (blob) {
        var formData = new FormData();

        formData.append('file', blob, '<%= @image.id %>_cut.png');
        formData.append('image_id', '<%= @image.id %>');

        console.log($image.cropper('getCropBoxData'));
        $.ajax('/admin/attachments/upload', {
          method: "POST",
          data: formData,
          processData: false,
          contentType: false,
          success: function () {
            alert('Corte guardado exitosamente');
            location.reload();
          },
          error: function () {
            alert('Error');
          }
        });
      });
    });
  });
</script>```

Any clue of what am I doing wrong?

Thanks,

Diego
fengyuanchen commented 6 years ago

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

$image.cropper('getCroppedCanvas', { 
  width: 160, 
  height: 160 
})
KnarikYeritsyan commented 6 years ago

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);
MrCherevko commented 6 years ago

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

fengyuanchen commented 6 years ago

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

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

streljk93 commented 6 years ago

$().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"

imedev2 commented 6 years ago

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!!!!

Verythai commented 6 years ago

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)>

` C:\tmp\tested.png: written on server site. image types can be supported such as png, jpg, gif whatever you prefer. Hope this helps. ### Sample Screenshots ![googledev](https://user-images.githubusercontent.com/8064428/44634626-6fda5b00-a9c6-11e8-8b56-a750d9d75fed.png) ![base](https://user-images.githubusercontent.com/8064428/44634444-7667d300-a9c4-11e8-8f50-23bb818cd179.JPG) ![results](https://user-images.githubusercontent.com/8064428/44634461-99928280-a9c4-11e8-9526-1d50be8e6ce4.JPG) ![tested](https://user-images.githubusercontent.com/8064428/44634467-a1eabd80-a9c4-11e8-95e8-00d0439e23cb.jpg)
koharabdul commented 5 years ago

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');
                }
            });
        });
    });
MrCherevko commented 5 years ago

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');
                }
            });
        });
    });
koharabdul commented 5 years ago

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?

fengyuanchen commented 5 years ago

@koharabdul

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

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

pushkidman commented 5 years ago

@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?

fengyuanchen commented 5 years ago

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

pushkidman commented 5 years ago

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

ersingenc commented 4 years ago

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

sinaiflow commented 4 years ago

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

darkleizar commented 4 years ago

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();
}