I am using html2canvas.js to create a screenshot of a webpage. The only thing is that I don't know how to transfer this data to an image file format so that I can save it and link it in the database.
This is my current code:
<script language="Javascript">
setInterval(function() {
html2canvas(document.body, {
onrendered: function(canvas2) {
context.drawImage(video, 0, 0, 240, 180);
$.post(
"' . self::get_link('save_screenshots') . '",
"user_id=' . module_security::get_loggedin_id() .
'&screenshot=" + encodeURI(canvas2.toDataURL())
);
document.body.appendChild(canvas2)
}
})
}, 1*60*1000);
</script>
This may help you:
<?php
// requires php5
define('UPLOAD_DIR', 'your/images/directory/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$img_file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($img_file, $data);
if($img_file){
// store the link to database
} else{
//return error msg
}
?>
You should let jQuery handle the request encoding for you:
$.post(url, {
user_id: 123,
screenshot: canvas2.toDataURL()
}, function() {
// success
document.body.appendChild(canvas2);
});
Then, you decode it like so on the server side:
$data = base64_decode(substr(
$_POST['screenshot'],
strpos($_POST['screenshot'], ',') + 1
));
Related
I'm struggling with saving my canvas image to server using JavaScript and PHP. I've tried multiple examples for both JS and PHP and it always fails. There's conflicting advice on how to send image data to PHP script (base64, blob, FormData) and I'm not sure how best to communicate back to JS. Currently, zero bytes PNG files are being saved to server and I'm not sure why. I'd like to save generated canvas as a PNG on server and execute a command in JS on success. How best to approach it?
JS:
var off_canvas = document.createElement('canvas');
off_canvas.width = 1080;
off_canvas.height= 1080;
var ctx = off_canvas.getContext("2d");
var brick = new Image();
brick.src = '../img/brick-white.jpg';
brick.onload = function(){
var pattern = ctx.createPattern(this, "repeat");
ctx.fillStyle = pattern;
ctx.fill();
};
var base64img = off_canvas.toDataURL("image/jpeg");
fetch("../php/save_image.php", {
method: "POST",
image: base64img
}) .then(response => response.text())
.then(success => console.log(success)) //execute command
.catch(error => console.log(error));
PHP:
<?php
$img = $_POST['image'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . "/img")) {
mkdir($_SERVER['DOCUMENT_ROOT'] . "/img", 0777, true);
}
$file = $_SERVER['DOCUMENT_ROOT'] . "/img/".time().'.png';
$success = file_put_contents($file, $data);
print $success ? $file.' saved.' : 'Unable to save the file.';
?>
After some fiddling with multiple options on both JS and PHP, this is what finally worked:
JS
var off_canvas = document.createElement('canvas');
off_canvas.width = 1080;
off_canvas.height = 1080;
var off_ctx = off_canvas.getContext("2d");
off_ctx.beginPath();
off_ctx.rect(20, 20, 150, 800);
off_ctx.fillStyle = "red";
off_ctx.fill();
var brick = new Image();
brick.src = "img/brick-white.jpg";
brick.onload = function(){
var pattern = off_ctx.createPattern(brick, "repeat");
off_ctx.fillStyle = pattern;
off_ctx.fillRect(500, 0, 1000, 1000);
// needs delay to fully render to canvas
var timer = window.setTimeout(save_canvas(off_canvas), 500);
};
function save_canvas(c) {
var b64Image = c.toDataURL("image/png");
fetch("../php/save_image_b64.php", {
method: "POST",
mode: "no-cors",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
body: b64Image
}) .then(response => response.text())
.then(success => console.log(success))
.catch(error => console.log(error));
}
PHP
<?php
$img = file_get_contents("php://input"); // $_POST didn't work
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . "/img")) {
mkdir($_SERVER['DOCUMENT_ROOT'] . "/img", 0777, true);
}
$file = $_SERVER['DOCUMENT_ROOT'] . "/img/".time().'.png';
$success = file_put_contents($file, $data);
print $success ? $file.' saved.' : 'Unable to save the file.';
?>
in your js page add console.log(base64img);
in your browser console, copy object. i use firefox, if you use something else, then from there copy console message.
the message will be data:image/jpeg;base64,/9j/4AAQSk......
in your php page;
$img = "data:image/jpeg;base64,/9j/4AAQSk.....";
echo "<img src='$data' />"; exit;
now you will know the image is coming or not.
if image is not showing you are not implementing the fetch method correctly
if image is showing, see if you are able to create dir/file. that is, apache has permission to create dir/file. if you are able
I'm converting svg using html2canvas to save on server side as png product preview before checkout with base64. The svg works fine. It's for a customized item checkout. The problem is after customization and checkout is clicked, the svg image does not save to preview on checkout page before checking out. Reason is i don't what to write to for the php to save it. I need help in writing the php code for "savetoserver.php" to save to server
function imagetopng(){
function showCheckout() {
$("#checkoutcontainer").show();
$(".productoverview").show();
$("#popup").show();
}
setTimeout(showCheckout, 500);
html2canvas($(".stole"), {
allowTaint: true,
letterRendering: true,
onrendered: function(canvas) {
$('.stole-png').prepend(canvas);
var dataURL = canvas.toDataURL('image/png', 1.0);
$.ajax({
type: "POST",
url: "savetoserver.php",
data: {
imgBase64: dataURL
}
})
.done(function(o) {
var fileurl = o;
var websiteurl = "http://woven.indexsta.com/";
var formatted = websiteurl + fileurl;
//var formatted = "stole-designs/" + fileurl
$('#stole-url').attr('value', formatted);
$('#stolepreview').attr('src', fileurl);
// If you want the file to be visible in the browser
// - please modify the callback in javascript. All you
// need is to return the url to the file, you just saved
// and than put the image in your browser.
});
}
});
$('.stole-png').empty();
};
$('#closecheckout').on('click touch',function(){
$("#checkoutcontainer").css('display','none');
$("#popup").css('display','none');
});
I figured it out. Incase anyone faces same challenge, here's the script i wrote to solve it.
<?php
// requires php5+
// create directory
if (!file_exists('images/')) {
mkdir('images/', 0777, true);
}
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);
print $success ? $file : 'Unable to save the file.';
?>
I have this ajax code, pretty simple :
$.ajax({
type: "POST",
url: "save.php",
data: {
imgBase64: dataURL,
counter : time
}
});
And in the other side, I have my php file :
<?php
define('UPLOAD_DIR', 'upload/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$counter = $_POST['counter'];
$formatedcounter = sprintf('%03d', $counter);
$data = base64_decode($img);
$filename = UPLOAD_DIR . 'GWD' . $formatedcounter . '.png';
$success = file_put_contents($filename, $data);
print $success ? $file : 'Unable to save the file.';
?>
I would like to combine both. Is it possible to write the php code instead of "save.php" for data in ajax? I've already tried but I get errors in phpstorm.
Thanks a lot!
Regards.
Thanks a lot guys.
So it can only point to a file. It's not (for example) possible to write the php code after and to point to it.
I am using the Gmail API function in javascript:
var request = gapi.client.gmail.users.messages.attachments.get({
'userId': 'me',
'messageId': 'MyMessageId',
'id': 'MyAttachmentId'
});
request.execute(function(resp) {
var dd = new FormData();
//here resp.result.data is the base64 data of the attachment file
dd.append( "img_data", JSON.stringify( resp.result.data ) );
fetch("http://my-url",{
method: 'post',
body: dd
});
}
I am sending this data to a url, where the server code is done using php.
I am using the following code to decode the base64 data and to save the file(Just for png image files):
define('UPLOAD_DIR', './');
$img = json_decode($_POST['img_data']);
$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);
print $success ? $file : 'Unable to save the file.';
Everything works fine, but the saved image file is corrupted and shows the error: Fatal error reading PNG image file: Decompression error in IDAT
Finally got the solution. Added the following php code:
$img = str_replace(' ', '+', $img);
$img = str_replace('_', '/', $img);
$img = str_replace('-', '+', $img);
The new code to decode and to save the file:
define('UPLOAD_DIR', './');
$img = json_decode($_POST['img_data']);
$img = str_replace(' ', '+', $img);
$img = str_replace('_', '/', $img);
$img = str_replace('-', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Am working on converting canvas to image and upload it to server when the user submit the form.
The image posted correctly but it appears empty in the server.
Here is my code, (Am using phonegap)
.drawImage ()is in the main.js .. but canvas..toDataURLis in a script in the html
<script>
function insert()
{
var img = document.getElementById("myCanvas")[0].toDataURL("image/jpeg");
$.ajax({
type: "POST",
url: "http://*******************/create.php?title="+ ($("#myTitle").val())+"&description="
+$("#myDesc").val()+"&price="+$("#myPrice").val(),
data: {img: img},
success: function(data)
{
alert("inserted");
}});
</script>
php
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Any idea ?
EDIT !!!
Finally it is UPLOADING!!!
Thanks to Jack Franzen for his suggestion.
I've changed the php code to
$img = $_POST['img'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.jpg';
$success = file_put_contents($file, $data);
and it is working as charm! :)
I Know your problem! Your PHP code is looking for a "PNG", but your javascript is generating a "JPG"
Just switch toDataURL("image/jpeg") To toDataURL()