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?
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;
?>
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
Related
After struggling with this issue for 2 days, reading a lot of material online, here I am begging for your help.
I'm trying to resize some images uploaded via FileReader, resize with canvas and send to my server with php.
Everything works as expected, except when I try to upload multiple files.
The script loads only the last image, despite showing base64 data for all images with a console.log ();
I'm missing something that I don't know what it is.
Here is the code:
<input type="file" id="input" onchange="process()" multiple/>
function process(){
const file = document.querySelector("input").files;
var abc = [];
for(i = 0; i<file.length; i++){
if(!file[i]) return;
const reader = new FileReader();
reader.readAsDataURL(file[i]);
reader.onload = function(event){
const imgElement = document.createElement("img");
imgElement.src = event.target.result;
imgElement.onload = function(e){
const canvas = document.createElement("canvas");
const MAX_WIDTH = 800;
const scaleSize = MAX_WIDTH / e.target.width;
canvas.width = MAX_WIDTH;
canvas.height = e.target.height * scaleSize
const ctx = canvas.getContext("2d");
ctx.drawImage(e.target, 0,0, canvas.width, canvas.height)
var srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
sendToServer(srcEncoded);
}
};
}
}
function sendToServer(data){
let formData = new FormData();
formData.append("foto", data);
fetch('teste.php', {method: "POST", body: formData});
}
As gugateider said, the javascript part its ok.
I think the problem its on the server side.
It only saves the last image no mather how much I selecte in the input.
Unfortunately I only have a PHP server, which is enough, but it limits the possibilities of solutions for this technology.
Here is the php code.
$data = $_POST['foto'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents(round(microtime(true)).'_image.png', $data);
Problem Solved!
I think the round(microtime(true)) wasn't enough to generate unique names.
I changed it to uniqid() and worked.
So the PHP code becomes:
$data = $_POST['foto'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents(uniqid().'_image.png', $data);
I have an image loaded to the browser in a HTML canvas wrapper.
<canvas id="image1" class="" width="213" height="213" style="width: 213px; height: 213px;"></canvas>
When I try to save this to the server via AJAX, it works fine but when the file is a JPEG, it doesn't redirect from the AJAX.
Here's my ajax
var imageName = $('#image_name').val();
var canvas = document.getElementById('image1');
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(data) {
alert(data);
window.location.replace("http://****.co.uk/dither/step3.php?id="+data)
});
Here's my php
<?php
define('UPLOAD_DIR', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
echo $file;
?>
If the image is a png file, then the redirect works, but if it's a JPEG it just returns back to the same page.
If I alert the 'dataURL' before the ajax call it returns a array with the first part as 'data:image/png;base64' no matter what type of file extension.
I don't know enough about the base64 stuff to figure this out.
as javascript is asynchronous the ajax was firing before the file upload had completed an thats why it was failing.
Use this sample of code to create create image from string, this will fix the issue
imagecreatefromstring($n) then imagejpeg($r,$y) or imagepng($r,$y);
and
imagedestroy($r);
I was introduced to Cropit recently and find it really easy to use but I am stuck at one area. I am trying to use Cropit and form submit. I am following the demo provided by Cropit.
Javascript:
$('form').submit(function() {
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return false;
});
PHP:
$encoded = $base64_string;
$decoded = urldecode($encoded);
$image_name = explode(';', $decoded);
$image_name = explode(':', $image_name[0]);
$image = array_pop($image_name);
$ext = explode('/', $image);
//decode the url, because we want to use decoded characters to use explode
$decoded = urldecode($encoded);
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $decoded);
//we just get the last element with array_pop
$base64 = array_pop($exp);
//decode the image and finally save it
$data = base64_decode($base64);
$str = random_string('alnum', 8);
$file = $str.'.'.$ext[1];
$data = $upload;
file_put_contents('assets/image_test/cropped/'.$file, $data);
It is able to output the file into my folder but the picture is just a blank screen with the dimension I set.
I have try to search the web but I couldn't find any solution to my problem.
Hope to get help from anyone who have encounter or know a solution.
javascript function to call the html2 canvas element to scrrenshot the the target div
<script type="text/javascript">
function capture() {
$('#target').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
$('#img_val').val(canvas.toDataURL("image/png"));
//Submit the form manually
document.getElementById("myForm").submit();
}
});
}
</script>
php code
<?php
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//echo $unencodedData;
//Save the image
$date = date_create();
$timestamp= date_timestamp_get($date);
echo $timestamp;
$rand = mt_rand(100000,999999);
echo $rand;
$string = "cp-string";
echo $string;
$name = "$string.$timestamp.$rand.png";
//$name = "$string/$timestamp/$rand.png";
//$unencodedData = "$string/$timestamp/$rand";
file_put_contents($name , $unencodedData);
?>
Dont know how to give different folders path for saving the image
Normally use copy function for upload file into a folder.
according to your code you can do something like
$dir_to_save = "foldername"
if (!is_dir($dir_to_save)) {
mkdir($dir_to_save);
}
$path = $dir_to_save."/".$name;
file_put_contents($path, $unencodedData);
NOTE: use ABSOLUTE_PATH not relative paths
For more information
So I currently found this photo cropping plugin called cropit . Demos are here . So what I want to do is grab the cropped photo and upload the name of the photo to the mysql database and save it to a directory using php.
So far I have this :
HTML :
<form method="POST">
<div class="image-editor">
<div class="cropit-image-preview-container">
<div class="cropit-image-preview"></div>
</div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<input type="hidden" name="image-data" class="hidden-image-data" />
<button type="submit">Submit</button>
</div>
</form>
jQUERY :
$('form').submit(function() {
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return false;
});
All I need help is with the php set up code because when I crop the photo and select submit, jquery returns the serialize code, and all this code that I'm usually not familiar with appears. Here is a few characters of the serialized code jquery returns:
image-data=data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE...
1. Saving the base64 encoded image
<?php
//save your data into a variable - last part is the base64 encoded image
$encoded = "data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE";
//decode the url, because we want to use decoded characters to use explode
$decoded = urldecode($encoded);
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $decoded);
//we just get the last element with array_pop
$base64 = array_pop($exp);
//decode the image and finally save it
$data = base64_decode($base64);
$file = 'data.png';
//make sure you are the owner and have the rights to write content
file_put_contents($file, $data);
2. Getting the filename of base64 encoded image
$encoded = "data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE";
$decoded = urldecode($encoded);
$exp = explode(';', $decoded);
$exp = explode(':', $exp[0]);
$image = array_pop($exp);
echo ($image);
I got Hosch Nok's answer to work by not decoding the encoded data.
Not calling:
$decoded = urldecode($encoded);
But working directly with the $encoded variable.