I'm rendering a screenshot with html2canvas 0.4.0 and want to save it as image on my webserver.
To do so, I've written the following function:
JavaScript
function screenShot(id) {
html2canvas(id, {
proxy: "https://html2canvas.appspot.com/query",
onrendered: function(canvas) {
$('body').append(canvas); // This works perfect...
var img = canvas.toDataURL("image/png");
var output = img.replace(/^data:image\/(png|jpg);base64,/, "");
var Parameters = "image=" + output + "&filedir=" + cur_path;
$.ajax({
type: "POST",
url: "inc/saveJPG.php",
data: Parameters,
success : function(data)
{
console.log(data);
}
}).done(function() {
});
}
});
}
saveJPG.php
<?php
$image = $_POST['image'];
$filedir = $_POST['filedir'];
$name = time();
$decoded = base64_decode($image);
file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX);
echo $name;
?>
After the canvas is rendered I can perfectly append it to the HTML body, but saving it on my server result in a corrupted (?) file.
I can read the dimensions in IrvanView, but the image is transparent / empty?
The file is about 2.076 KB large. So it's not really empty.
I tried this with JPEG as well and it results in a corrupted file and IrfanView says something like "bogus marker length".
The screenshot has the dimensions of 650x9633. Is it to much data for a POST-Method?
In case someone stumbles over the same problem, here is how I solved it:
The problem depended on the fact, that + in URLs is interpreted as an encoded space (like %20) by most servers. So I needed to encode the data first and then send it via POST to my designated PHP function.
Here is my code:
JavaScript
function screenShot(id) {
html2canvas(id, {
proxy: "https://html2canvas.appspot.com/query",
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png");
var output = encodeURIComponent(img);
var Parameters = "image=" + output + "&filedir=" + cur_path;
$.ajax({
type: "POST",
url: "inc/savePNG.php",
data: Parameters,
success : function(data)
{
console.log("screenshot done");
}
}).done(function() {
//$('body').html(data);
});
}
});
}
savePNG.php
<?php
$image = $_POST['image'];
$filedir = $_POST['filedir'];
$name = time();
$image = str_replace('data:image/png;base64,', '', $image);
$decoded = base64_decode($image);
file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX);
echo $image;
?>
Cheers!
Related
I'm going off of Dropzone.js resources provided by: http://www.dropzonejs.com/
What I'm trying to do - After uploading the image(s) and filling out all inputs, to get the link for each image that was uploaded in this session, to be passed into an AJAX request URL as a POST type.
My HTML:
<div id="myForm">
<input type="text" id="form-name" placeholder="Name">
<input type="text" id="form-email" placeholder="Email">
<form action="/upload-target" class="dropzone" id="myDropZone"></form>
<button id="submit-info">submit</button>
</div>
My JS:
<script>
$("div#myDropzone").dropzone({ url: "/upload.php" },
function() {
console.log("Hello");
});
</script>
The images are uploaded to a directory mentioned in the PHP code below, but I have a problem with the above script, where the output in the console doesn't even print. Hello doesn't show in the console when anything is uploaded.
My upload.php:
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'img/uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
?>
Just to explain the above code, once an image(s) is
selected/drag-and-dorpped, upload.php uploads the images to
http://example.com/img/uploads/ folder.
Here's where I need help:
I am trying for when clicking the button with id submit-info, passing each image I've just uploaded as a string to the AJAX request:
<script>
$('#submit-info').click(function() {
var str = "name=" + $('#form-name').val()
+ "&email=" + $('#form-email').val()
+ "&images=" + /* what to put here */;
console.log(str);
$.ajax({
type: "post",
url: "sendEmail.php",
data: str,
dataType: "json",
success: function (confirmation) {
// some code here dealing with after the email is sent like hiding the form
}
});
});
</script>
Here's one way to do it:
var files = '';
if (Dropzone.forElement("#my-dropzone").files.length > 0) {
for (var i = 0; i<Dropzone.forElement("#my-dropzone").files.length; i++) {
if (i === (Dropzone.forElement("#my-dropzone").files.length - 1) ) {
files += Dropzone.forElement("#my-dropzone").files[i].name;
}
else {
files += Dropzone.forElement("#my-dropzone").files[i].name + '~';
}
}
}
The above code should be placed inside of the $('#submit-info').click(function() { ... so that once the submit button is clicked, we set an empty string, check if there are any files that were uploaded, and concatenate them if they exist.
For this example, the files are being separated by ~ characters. So once the string is passed through, you can declare your str variable like so:
$('#submit-info').click(function() {
var str = "name=" + $('#form-name').val()
+ "&email=" + $('#form-email').val()
+ "&images=" + files;
I'm trying and failing to send the viewport width and heigth to a PHP file!
I know this or rather many similar questions about passing to PHP have already been asked and I've been going through these as well. However, I haven't figured out why it doesn't work for me...
I get the following output, where the second line would match the first, if the data had been passed:
Your viewport width is 1519x766
Width is: 880 and Height is 495
I just can't get the information passed to the PHP part - tried it like this in one file and also in two files, where I then call the php file using:
<?php include 'panzoom.php';?>
I use this code in the head:
<script>
var viewportwidth;
var viewportheight;
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
$(document).ready(function() {
$.ajax({
url: 'http://localhost/index.php',
type: 'POST',
dataType: 'json',
data: {
width : viewportwidth,
height : viewportheight
}
});
});
</script>
<?php
$GLOBALS['directory'] = "photos/frontpage/";
if(isset($_POST['width']) && isset($_POST['height'])) {
$GLOBALS['width'] = $_POST['width'];
$GLOBALS['height'] = $_POST['height'];
}else{
$GLOBALS['width'] = 880;
$GLOBALS['height'] = 495;
}
$width = $GLOBALS['width'];
$height = $GLOBALS['height'];
echo '<p>Width is: ' . $width . ' and Height is ' . $height . '</p>';
?>
You have posted a JSON string to the PHP script and it is called data so you should be looking for $_POST['data']
Also as it is posted as a json string, in order to make sense of it in PHP you normally decode it to either an array or a string using json_decode()
You also dont need to create all the variables in javascript to clutter up the global namespace.
So try this
<script type="text/javascript">
document.write('<p>Your viewport width is '+
window.innerWidth+'x'+window.innerHeight+'</p>');
$(document).ready(function() {
$.ajax({
url: 'index.php',
type: 'POST',
dataType: 'json',
data: {
width : window.innerWidth,
height : window.innerHeight
}
});
});
</script>
<?php
$GLOBALS['directory'] = "photos/frontpage/";
if( isset($_POST['data']) ) {
$obj = json_decode($_POST['data']);
$GLOBALS['width'] = $obj->width;
$GLOBALS['height'] = $obj->height;
}else{
$GLOBALS['width'] = 880;
$GLOBALS['height'] = 495;
}
$width = $GLOBALS['width'];
$height = $GLOBALS['height'];
echo '<p>Width is: ' . $width . ' and Height is ' . $height . '</p>';
?>
My jQuery Ajax code is:
<div class="page_rank">
<form name="searchForm" id="searchForm" method="post">
<span class="my_up_text">ENTER THE WEBSITE TO CHECK GOOGLE PAGE RANK:</span>
<br /><br />
<input type="text" name="my_site"/></div><div class="p_ity"><input type="submit" class="btn" value="PAGE RANK" /> </form></div><div id="my_pass"></div>
<script>
function sub_form()
{
document.forms["searchForm"].submit();
}
$(function () {
$('form#searchForm').on('submit', function(e) {
$( ".p_ity" ).hide();
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html(data);
}
});
e.preventDefault();
});
});
</script>
My php code is:
<?php
header('Content-type: image/jpeg');
require('./get_page_rank.php');
$url=$_POST['my_site'];
//echo $url;
$pr = new PR();
//$rank= $pr->get_google_pagerank($url);
$rank=$pr->get_google_pagerank($url);
// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('./images/page-rank/G.jpg');
if($jpg_image)
{
// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 0, 0, 0);
// Set Path to Font File
$font_path = './images/page-rank/Helvetica.TTF';
// Set Text to Be Printed On Image
$text = $rank;
// Print Text On Image
imagettftext($jpg_image, 85, 0, 305, 100, $white, $font_path, $text);
// Send Image to Browser
imagejpeg($jpg_image,NULL,100);
// Clear Memory
imagedestroy($jpg_image);
}
?>
It works perfectly if I execute the PHP separately with manual input so I think the problem is with jQuery html() function. I am sure the image is not corrupted and I am using utf-8 encoding and I also tried base64_encode(imagejpeg()) but got the same output.
OUTPUT:
��*����D\�#��梸�����[[h� ��0 s��('�y\�ӎ+��_�P 7��){�i�i��ĽOH�
_��:�� VV���y�x���o~�Eh��R��U�1�C����|�~,�ѿ
��7c��|S�����W�:�g��� ����K�z��A��D .͓�<�n��F� d�Qƹ̸{%�*֣�2�q7c�9UJ�0s��w�ߞ>ҥX��UaQG��w�bq8��
imagejpeg() outputs the image to browser directly, so the response is not the html content you could use with .html(), you don't have to use ajax in this case, the url should be used as the src of an image tag.
You could do like below:
$(function () {
$('form#searchForm').on('submit', function(e) {
$( ".p_ity" ).hide();
$('<img />').attr('src', 'check-google-page-rank.php?my_site='+ encodeURIComponent($('[name= "my_site"]').val())).load(function() {
$(this).appendTo('#my_pass');
});
e.preventDefault();
});
});
And change $url=$_POST['my_site']; to $url=$_GET['my_site'];.
In your php handler, write your image in a file;
$imgFolderPAth = "/path/to/img/";
imagejpeg($jpg_image,$imgFolderPAth . "image.jpg",100);
echo $imgFolderPAth . "image.jpg";
and in your js;
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html('<img src="' + data + '"/>');
}
});
Or alternatively you can use;
imagejpeg($jpg_image,NULL,100);
$rawImageBytes = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $rawImageBytes ) . "' />";
and in your js, you can use as it is
I'm building an audio player that makes 3 different API calls, and I need them all to be in JSONP format, so I made a PHP proxy file that determines the output of the JSON data like so:
$datatype = $_GET["type"];
$artist = urlencode($_GET["artist"]);
$album = urlencode($_GET["album"]);
$content = "";
if($datatype == 'albumart'){
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=' . $artist . '&album=' . $album . '&format=json');
} elseif($datatype == 'artistart'){
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=' . $artist . '&autocorrect=1&format=json');
} else {
$content = file_get_contents('http://cjzn.streamon.fm/metadata/recentevents/CJZN-48k.json');
}
header('Content-type: application/json; charset=utf-8');
echo $_GET['callback'] . '(' . json_encode($content) . ')';
Upon testing the output it seems to work fine, it gets the respective API data, wraps it in the JSONP () and accepts a JSONP callback.
Bur when I try and use it in my Javascript file it doesn't seem to work, but I can't figure out why! Here's an example of one of the functions being used to call the JSON data:
function getAlbumArt(artist,album){
var dataArtist = artist,
dataAlbum = album,
albumArtURL;
$.ajax({
url: 'jsonproxy.php',
dataType: 'jsonp',
data: {
type: 'albumart',
artist: dataArtist,
album: dataAlbum
},
success: function(data) {
if(data.album.image[4]["#text"]){
var albumArtURL = data.album.image[4]["#text"];
$('section.player div.album-artwork').css({'background-image':'url("' + albumArtURL + '")'});
} else {
getArtistArt(dataArtist);
}
},
error: function() {
getArtistArt(dataArtist);
alert('Sorry, unable to retrieve album artwork!');
}
});
}
Can anyone help with why this doesn't work for me?
Edit
I did alert(data); on success, and that returned all of the data from the feed, after that if I did something more specific like alert(data.album.image[4]["#text"]); it returned undefined. Very confused here. Anyone have any thoughts?
this code almost works
this will output the entire page into a jpg
question: how can i grab only the content inside '#myDiv' and output that as a jpg file?
JS:
$('.myButton').click(function(){
$('#myDiv').html2canvas();//<< has no effect
var queue = html2canvas.Parse();
var canvas = html2canvas.Renderer(queue,{elements:{length:0}});
var img = canvas.toDataURL();
img.replace(/^data:image\/(png|jpg);base64,/, "");
$.post( "postIO.php", {img:img}, function(data) {
//$('#recieve').append(data);
});
return false;
});
postIO.php:
$canvasImg = $_POST['img'];
//$canvasImg = str_replace('data:image/png;base64,', '', $canvasImg);
$data = base64_decode($canvasImg);
$File = "z.jpg";
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
fclose($Handle);
reference from here
I have download and try html2canvas, then I find out the jquery plugin does not complete (it's does nothing than capture the image and create canvas, no use) so I write capture code myself.
var el = $('div').get(0);
function saveData(dturl){
//Upload here
console.debug(dturl);
}
html2canvas.Preload(el, {
complete: function(image){
var queue = html2canvas.Parse(el, image, {elements: el}),
$canvas = $(html2canvas.Renderer(queue, {elements: el}));
saveData($canvas[0].toDataURL());
}
});
Hope it help you
so to use with your program you have to write
function saveData(dturl){
dturl.replace(/^data:image\/(png|jpg);base64,/, "");
$.post( "postIO.php", {img:dturl}, function(data) {
//$('#recieve').append(data);
});
}
$('.myButton').click(function(){
var el = $('#myDiv').get(0);
html2canvas.Preload(el, {
complete: function(image){
var queue = html2canvas.Parse(el, image, {elements: el}),
$canvas = $(html2canvas.Renderer(queue, {elements: el}));
saveData($canvas[0].toDataURL());
}
});
});
after var canvasImg = canvasRecord.toDataURL("image/jpg");, you may need to replace it using var data = canvasImg.replace(/^data:image\/(png|jpg);base64,/, "");
and is that $canvasImg = $_POST['canvasImg']; instead of $_POST['img']?