html2canvas output selected div PHP - php

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']?

Related

Issue converting obj (3d) to png [duplicate]

How would I convert a render to a .png image?
I've been looking around for awhile but nothing has worked.
Here is a function I use and a fiddle that shows it working.
function takeScreenshot() {
// For screenshots to work with WebGL renderer, preserveDrawingBuffer should be set to true.
// open in new window like this
var w = window.open('', '');
w.document.title = "Screenshot";
//w.document.body.style.backgroundColor = "red";
var img = new Image();
img.src = renderer.domElement.toDataURL();
w.document.body.appendChild(img);
// download file like this.
//var a = document.createElement('a');
//a.href = renderer.domElement.toDataURL().replace("image/png", "image/octet-stream");
//a.download = 'canvas.png'
//a.click();
}

html2canvas save image doesn't work

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!

Pull img src from this html grabbed with javascript

I am extracting an image from a part of the document using:
var theImg = document.getElementById('imageDiv').innerHTML;
This returns something like
theImg = <img src="http://website.com/image.jpg?&image-presets&" alt="foo" style="z-index: 1" />
How could I grab just the src of the image, without the parameter. So that
theImg = http://website.com/image.jpg
I am open to using a regular expression, php, or vanilla javascript.
Untested, but I believe this should do the job. It first retrieves the image src and then strips off everything starting with the ?.
var imgDiv = document.getElementById('imageDiv');
var imgs = imgDiv.getElementsByTagName("img");
for (var i = 0; i<imgs.length; i++) {
var theImg = imgs[i].getAttribute('src').substr(0, theImg.indexOf('?'));
console.log(theImg);
// Do whatever you need to with theImg. Add to an array or whatever...
}
Since there appear to be no correct and complete answers so far with a working demonstration, I'll attempt one:
var imgs = document.getElementById('imageDiv').getElementsByTagName('img');
var theImgSrc = imgs[0].src;
var loc = theImgSrc.indexOf("?");
if (loc != -1) {
theImgSrc = theImgSrc.substr(0, loc);
}
You can see it in action here: http://jsfiddle.net/jfriend00/NSczd/
Just call .getAttribute('src') on the image element itself, and assign that string to theImg.
More fully, the following:
var theImg = document.getElementById('your_image').getAttribute('src');
Handles both parts of the question:
var imgDiv = document.getElementById('imageDiv');
var imgs = imgDiv.getElementsByTagName("img");
var url = "";
if (imgs.length > 0) {
var img = imgs[0];
var questionIndex = img.src.indexOf("?");
if (questionIndex > -1) {
url = img.src.substring(0, questionIndex);
} else {
url = img.src;
}
}
alert(url);
http://jsfiddle.net/cvhwZ/2/
Sorry, yeah, this is better.
var theImgSRC = document.getElementById('imageDiv').querySelector('img').getAttribute('src');
document.getElementById('imageDiv').querySelector("img").getAttribute('src').theImg.substr(0, theImg.indexOf('?'));

Image from Flash BitmapData to PHP to webpage

I'm trying to display an image exported from a flash BitmapData in a basic webpage.
The export from flash works perfectly :
import flash.display.BitmapData;
var vBitmap = new BitmapData(300, 400, true, 0x000000);
vBitmap.draw(themovieclip_mc);
btn1.onRelease = function() {
var vLV = new LoadVars();
vLV.tableData = new Array();
for (i=0; i<300; i++) {
for (j=0; j<400; j++) {
vLV.tableData.push(vBitmap.getPixel(j, i));
}
}
vLV.send("webpage.php", "_self", "POST");
};
Then I get the image in the webpage.php file
<?php
$lv = $_POST['tableData'];
$temp = explode(",",$lv);
settype($temp[1],'integer');
$img = imagecreatetruecolor(300,400);
$k = 0;
for($i=0; $i<300; $i++){
for($j=0; $j<400; $j++){
imagesetpixel($img,$j,$i,$temp[$k]);
$k++;
}
}
$temporary_file_name = tempnam("/tmp");
imagejpeg($img,"$temporary_file_name",100);
?>
<html>
<img src="/tmp/<?php echo $temporary_file_name; ?>" />
<h1>Lorem ipsum</h1>
<p>lorem ipsum dolor sit amet</p>
</html>
the above code does NOT work, I can't find a way to display the image embedded in the webpage. Any help woud be really appreciated.
I am assuming that the insertion of the image data into the web page is your only problem. (without data, it's impossible to tell how well the image generation process itself works.)
I can't find a way to display the image embedded in the webpage
There isn't any good way to do this. You need to get the image from a separate image resource, there's no way around it (except data: URIs but those are broken).
You could write the avatar file into a temporary file:
$temporary_file_name = tempnam("/path/to/somedir");
imagejpeg($img,"$temporary_file_name",100);
then in the HTML, output:
<img src='/somedir/<?php echo $temporary_file_name; ?>' />
you would have to add some mechanism to remove the temporary file later.
So, I finally found my way through this.
That might not be the best way to do it, but at least it works.
//AS3
import com.adobe.images.JPGEncoder;
function createJpg(aMovieClip, aQuality){
var vSource = new BitmapData(200, 304, true, 0 );
vSource.draw(aMovieClip, new Matrix(1,0,0,1,100,152)); // decale de width/2 et height/2
var vEncoder = new JPGEncoder(aQuality);
var vByteArray = vEncoder.encode(vSource);
return vByteArray;
};
// export image to server
function exportJpg(aMovieClip){
var vByteArray = createJpg(aMovieClip, 80);
var vRequest:URLRequest = new URLRequest('URL_TO_THE_PHP_FILE');
var vLoader: URLLoader = new URLLoader();
vRequest.contentType = 'application/octet-stream';
vRequest.method = URLRequestMethod.POST;
vRequest.data = vByteArray;
navigateToURL(vRequest, "_self");
};
// save image on users computer
function saveJpg(aMovieClip, aString){
var vByteArray = createJpg(aMovieClip, 80);
var vFR = new FileReference();
vFR.save(vByteArray, aString);
};
Then the PHP/HTML file
<?php
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$img = $GLOBALS["HTTP_RAW_POST_DATA"];
$prefix = "foo";
$path = "/full/server/path/to/directory/with/777/permissions";
// give a unique name to the file
$name = $prefix.md5(time().rand());
$temporary_file_name = $path.'/'.$name.'.jpg';
$fp = fopen($temporary_file_name, 'wb');
fwrite($fp, $img);
fclose($fp);
// find the name of the image without the full server path
$array = explode("/", $temporary_file_name);
$length = count($array);
$filename = $array[$length - 1];
//give a path to the image file
$imagepath = "http://www.domain.com/directory/".$filename;
}else{
// error : the POST data was not found
}
?>
<html>
<head>
</head>
<body>
<h1>Lorem ipsum</h1>
<p><img src="<?php echo $imagepath; ?>"</p>
</body>
</html>

Script to draw image

I am looking for a PHP script that will allow me to draw an image with my mouse and save it as an image. If you know of any please help.
In case you do feel like reinventing a few wheels :-)
Make a Javascript snippet that lets you draw. This can of course be as advanced or simple as you wish, for example:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
pos = false;
ctx.strokeStyle = "red";
$(canvas).bind("mousedown", function(evt) {
pos = {x: evt.layerX, y: evt.layerY};
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
});
$(canvas).bind("mousemove", function(evt) {
if(!pos) return; // You may not want to do this on every mousemove.
pos = {x: evt.layerX, y: evt.layerY};
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
});
$(canvas).bind("mouseup", function(evt) {
if(!pos) return;
ctx.closePath();
pos = false;
});
Also add a button that sends the image data to your PHP script:
$('#btn').bind("click", function(evt) {
$.post('saveImage.php', {image : canvas.toDataURL('image/jpeg')});
});
In your saveImage.php script on the server, decode the data and write it to a file.
$imgData = $_POST["image"]; // Probably a good idea to sanitize the input!
$imgData = str_replace(" ", "+", $imgData);
$imgData = substr($imgData, strpos($imgData, ","));
$file = fopen('myImage.jpg', 'wb');
fwrite($file, base64_decode($imgData));
fclose($file);
Should do the trick :-) I'm using jQuery for the JS bits here, that's of course not necessary.
PHP is executed server-side, whereas interaction with the mouse is carried out client-side. You would need to use an in-browser technology like JavaScript or Flash to capture the mouse movements and generate bitmap data first.

Categories