Crop Image and upload with php

Otávio Barreto picture Otávio Barreto · Mar 14, 2017 · Viewed 15.8k times · Source

I have a crop image script. How can the script upload the cropped image when the user clicks the save button? How can I make the PHP the cropped image and upload to server?

The documentation is here on github - cropperjs.

Answer

Sᴀᴍ Onᴇᴌᴀ picture Sᴀᴍ Onᴇᴌᴀ · Mar 15, 2017

how to crop and upload when click save button? , How to make the php get the cropped image and upload to server?

In the readme, the description of method getCroppedCanvas() mentions uploading a cropped image:

After then, you can display the canvas as an image directly, or use HTMLCanvasElement.toDataURL to get a Data URL, or use HTMLCanvasElement.toBlob to get a blob and upload it to server with FormData if the browser supports these APIs.1

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

  formData.append('croppedImage', blob);

  // Use `jQuery.ajax` method
  $.ajax('/path/to/upload', {
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function () {
      console.log('Upload success');
    },
    error: function () {
      console.log('Upload error');
    }
  });
});

So for your example, the button labeled save references cropper but that is only defined inside the callback of the DOM-loaded callback (i.e. window.addEventListener('DOMContentLoaded', function () {). I would recommend using an event delegate (see example plunker mentioned below) but if you wanted to reference cropper it would need to be declared outside the DOM-loaded callback.

var cropper;
window.addEventListener('DOMContentLoaded', function () {
    //assign cropper:
    cropper = new Cropper(image, { ...

You can see it in action in this plunker. It utilizes a PHP code that merely takes the uploaded cropped image and returns the base64 encoded version (using base64_encode()).

The PHP code used in the plunker example is listed below:

<?php
$output = array();

if(isset($_FILES) && is_array($_FILES) && count($_FILES)) {
     $output['FILES'] = $_FILES;

     //this is where the cropped image could be saved on the server
     $output['uploaded'] = base64_encode(file_get_contents($_FILES['croppedImage']['tmp_name']));
}
header('Content-Type: application/json');
echo json_encode($output);

Instead of just echoing the base64-encoded version of the file, move_uploaded_file() could be used to upload the file and then return information about the uploaded file (e.g. file ID, path, etc).

move_uploaded_file($_FILES['croppedImage']['tmp_name'], '/path/to/save/cropped/image');

1(https://github.com/fengyuanchen/cropperjs#user-content-getcroppedcanvasoptions)