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();
}
Related
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']?
I have a mysql database with a table containing PATH's to images.
I want to load al the images to a TileList. Now i have this in PHP:
<?PHP
mysql_connect("localhost", "root", "root");
mysql_select_db("prototipo");
$result = mysql_query("select entretenimiento_id, e_nombre, e_imagen from entretenimiento");
echo "<?xml version=\"1.0\" ?><entretenimiento>";
while($row = mysql_fetch_assoc($result))
{
echo "<e_nombre>" . $row["e_nombre"] . "</e_nombre>";
echo "<e_imagen>" . $row["e_imagen"] . "</e_imagen>";
}
echo "</entretenimiento>";
?>
This is supposed to fetch me the PATH of the image, the name so it goes on the label of the tile that displays the image, and brings me also the id so i can launch another query when that image is clicked on.
All this is set into a dynamically created XML.
Now my question.... How do i load this??? What to do o AS3?? I already have the AS3 for the tilelist, i only need to load this dynamically created XML from PHP to it.
Thanks in advance. And sorry if i messed up on english, its not my main language. Im South American.
I have a partial answer:
var path:String = "http://localhost/entretenimiento.php";
xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
xmlLoader.load(new URLRequest(path));
function onLoadComplete(e:Event):void {
var xmlData:XML = new XML(e.target.data);
//trace(xmlData);
for (var i:int=0; i<xmlData.*.length(); i++)
{
myTileList.addItem({label:xmlData.e_nombre[i], source:xmlData.e_imagen[i]});
//trace(xmlData.e_nombre[i]);
}
}
Althought this shows me the images and the titles on the tiles, i also get two more tiles that are empty, and in the trace they are shown as "undefined". Any thoughts to why is this?
Here is a sample code that should works :
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
// change the path of your php file
xmlLoader.load(new URLRequest("your-file.php"));
function showXML(e:Event):void
{
var entretenimiento:XML = new XML(e.target.data);
// for each row :
for (var x:XML in entretenimiento.loc)
{
// Change the name of your tilelist
myTileList.addItem({label:x.e_nombre, source:x.e_imagen});
}
}
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('?'));
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>
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.