3

How to get crop the image using my own button?

I tried to execute this

var canvas = $selector.cropper('getCroppedCanvas')

but it's returning null value.

Is there a way to get the cropped canvas? And how can I put the cropped canvas data into <input type="file"> value and send it to PHP?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Hitori
  • 569
  • 1
  • 5
  • 21

2 Answers2

6

Your selector should be the HTML container which contains the image: The Javascript and HTML should be like as mentioned below:

$img = $('#uploader-preview');

$img.cropper('getCroppedCanvas');
var canvaURL = canvas.toDataURL('image/jpeg'); // it returns the cropped image / canvas
<img src="" id="uploader-preview">

Send Canvas Image to PHP:

var photo = canvas.toDataURL('image/jpeg');                
$.ajax({
  method: 'POST',
  url: 'photo_upload.php',
  data: {
    photo: photo
  }
});

Here's PHP Script
photo_upload.php

<?php
 
 $data = $_POST['photo'];
 list($type, $data) = explode(';', $data);
 list(, $data)      = explode(',', $data);
 $data = base64_decode($data);

 mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");

 file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
 die;
?>
vikram jeet singh
  • 3,416
  • 2
  • 21
  • 22
  • I guess second line of first snippet should be: var canvas = $img.cropper('getCroppedCanvas'); Or where canvas came from? – morgar Nov 25 '18 at 00:54
1

What is $selector? If it something like this:

var $selector = $(".selector");

Then you need call getCroppedCanvas() function to jQuery wrapper. Because if you write:

var canvas = $selector.cropper('getCroppedCanvas');

It calls cropper getCroppedCanvas function to DOM element, not to jQuery element.

Write something like this:

var $selector = $(".selector"); 
var canvas = $($selector).cropper('getCroppedCanvas');

And it will be work fine. If you want save canvas data as image on server, you can read this answer

Community
  • 1
  • 1
  • Your concept of jquery objects seems a bit confused. $('body').get(0) == $($('body')).get(0); – stt Sep 05 '15 at 12:22