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.
Related
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.
How Can I Store a Base 64 Image to my Database and To my Server Folder. the Following Code is Using to Save that Image into My server Folder. but the image can't open.
$data = $src;
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = '../emailtest'.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = '../emailtest'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
My advice:
1. Avoid to save binary to database, save it into file if possible.
2. Prefer to save binary into blob column better than save base64 into text column. Because base64 encode make this more bigger
Here is, i try to
1. download image from url
2. save binary into file
3. save binary to db
4. convert image binary to base64
5. display image base64 using html <*img> tag
try this code
DEMO
<?php
$img_url = 'http://cdn-o7.outfit7.com/wp-content/uploads/2016/01/Icon-r-512-3.png';
$img_binary = file_get_contents($img_url);
$ext = pathinfo($img_url, PATHINFO_EXTENSION);
$img_base64 = "data:image/".$ext.";base64," . base64_encode($img_binary);
//save into file
$name = "emailtest_".rand().$ext;
file_put_contents($name, $img_binary);
echo "<img src=\"$name\" title=\"show from file\"/>";
//store to db
/* create your new table for testing
CREATE TABLE IF NOT EXISTS `table_img` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`img_binary` blob NOT NULL,
`location` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
$insert="INSERT INTO table_img ('img_binary','location') VALUES('$img_binary','$name')"; //==>save to db using this query
$select="SELECT img_binary FROM table_img WHERE id=1"; //call your image binary using this query
// then convert binary into base64 with this : $img_base64= base64_encode(YOUR BINARY DATA FROM DATABASE);
//because i cant do it live in my server, i will shortcut call previous variable $img_base64 from above instead call binary from db and base64 encode
echo "<img src=\"$img_base64\" title=\"show from base64\"/>";
?>
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.
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
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";