How to save a photo using jQuery? - javascript

I am developing a software using html, javascript and php. It is supposed to save pictures using a webcam and then saving them into a database.
The thing is, it takes the pictures with no problem, but I actually can't figure out how to save the pictures to a file, and which format would be more efficient to save it into the MySql DB.
Here's how I am taking the pictures:
jQuery(document).ready(function(){
//Este objeto guardará algunos datos sobre la cámara
window.datosVideo = {
'StreamVideo': null,
'url' : null
};
jQuery('#botonFoto').on('click', function(e){
var oCamara,
oFoto,
oContexto,
w, h;
oCamara = jQuery('#videoElement');
oFoto = jQuery('#foto');
w = oCamara.width();
h = oCamara.height();
oFoto.attr({'width': w, 'height': h});
oContexto = oFoto[0].getContext('2d');
oContexto.drawImage(oCamara[0], 0, 0, w, h);
});
} );
The code takes the picture and draws it in the variable, which is a canvas

It can be done by the following procedure:
HTML:
<canvas id="foto"></canvas>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="img" id="img_val">
<input type="submit" name="submit" value="submit" />
</form>
JS:
<script type="text/javascript">
var c = document.getElementById("foto");
document.getElementById("img_val").value = c.toDataURL();
</script>
PHP:
<?php
if(isset($_POST['submit'])) :
$data = $_POST['img'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('uploads/image.png', $data);
endif;
?>
What's going here?
Firstly I added a form below the canvas to store image in base64 encoded format in a hidden input field.
Secondly JS script get content from canvas and stores it in base64 encoded format into the hidden input field.
Now when the user submits the form to upload image the data will be send to the server containing image in encoded format.
Thirdly PHP code remove the data:image/png;base64, and decode back the recieved data to store image with proper content into the server.
It may be helpful to you to understand how to send an image to the server.

Related

Dropzone always return 'empty($_FILES)' as true

I need to add drag and drop to my web page. I'm trying to get dropped image and upload them to my database.
HTML
<form action="parser.php" id="file-up" class="dropzone">
<input type="submit" value="Upload" id="file-up_btn"/>
</form>
JS
Dropzone.autoDiscover = false;
$('#file-up_btn').click(function(e){
var myDropzone = new Dropzone("#myId", {
autoQueue: false,
url: "/parser.php",
});
console.log("Uploading");
});
Dropzone shows that the uploading finished successfully. But it does not show any files in the php file.
<?php
if(!empty($_FILES)){
echo 'Inside';
$temp = $_FILES['file']['tmp_name'];
$dir_seperator = DIRECTORY_SEPARATOR;
$folder = "uploads";
//$destination_path = dirname(__FILE_).$dir_seperator.$folder.$dir_seperator;
$destination_path = tempnam(sys_get_temp_dir(), 'Tux');
echo '<h1>Uploading section $destination_path</h1>';
$target_path = $destination_path.$_FILES['file']['name'];
move_uploaded_file($temp,$target_path);
echo 'Updated';
}else{
echo '<h1>No files</h1>';
}
?>
it always returns No files. I am new to DropZone. Please help me on this. Thanks in advance. :)
Two thinks to check:
id isn't the same.
in js: "#myId"
in html: #file-up or #file-up_btn
There no myid in html to refer so img isn't added to form.
from logical behaviour:
empty($_FILES) is true when no files are transmited
!empty($_FILES) is false because of !. So no file is attach.
Check Developer Tools->Network and check Preserve log. Check what header is sent with what data (maybe nothing is sent etc, it is half success when you can inform if file is added to form data).
Screenshoot to show what we all need to help: developer tools

Image corrupted when using Cropit and form submit

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.

fengyuanchen jQuery cropper plugin - how to get cropped canvas

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

How to crop and upload photo using cropit jquery plugin with php

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.

html2canvas capturing div image

im working on my wordpress site in which i want a div to be converted to image.. im using html2canvas javascript and it works perfect. when i capture a post it saves it to the server has "Captured.jpg". all good till here.. but when i click capture again on a different post it replaces the previous image "captured.jpg". i want all the images of the posts that i capture to be saved on server with post names may be? is it possible?
Header
<script type="text/javascript">
function capture() {
$("#quotesingle").html2canvas({
canvas: hidden_screenshot,
onrendered: function() {
var img = $("#hidden_screenshot")[0].toDataURL();
img= img.replace('data:image/png;base64','');
$form = '<form name="frmact" action="result.php" method="post" ><input type="hidden" name="img" value="' + img + '" /></form>';
$('body').append($form);
frmact.submit();
$('body').remove($form);
}
});
}
</script>
Results.php
<?php
$canvasImg = $_POST['img'];
$data = base64_decode($canvasImg);
$File = "captured.jpg";
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
fclose($Handle);
?>
captured.jpg is saved.
single.php
//POSTLOOP
<input type=button value="Screenshot" onclick="javascript:capture();" /><br /><br /></div>
<canvas id="hidden_screenshot" style="display:none;" >
is there any way if i trigger the capture for a post to save in a different name or post name or post id.. so it saves it to the server without replacing the old?
thanks
Result.php
Simple change the file name as below:
$File = "screens/" . time() . ".jpg";

Categories

Resources