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.
Related
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();
}
First of all, sorry for my bad English, I'm Italian. I'm a bit new to programming, but for my office I need to create script that's a bit complex (at least for me). Before explaining the problem i'll explain what i'm doing.
I scripted a canvas that creates an image from data input, then i send the image data to php for the saving process. The problem is that i need to send also an value of 1 of the js vars (in the example value1). I can't figure out how to pass this information together with the raw image data.
The js code for the img drawing and saving. i need to pass the value1 to the save.php
button.addEventListener("click",function(){
//saving the values of the form
var value1 = document.getElementById("value1").value;
//text on the canvas
var value1X = (maxWidth-ctx.measureText(value1).width)/2+500;
//drawing the inputed text on the canvas
ctx.drawImage(img,0,0);
ctx.fillText(value1,value1X,maxHeight);
//getting the image url and sending it to save.php for the saving process
var imageURL = c.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
}, false);
Here is the PHP file:
<?php
if (isset($GLOBALS[HTTP_RAW_POST_DATA])) {
$imageData = $GLOBALS[HTTP_RAW_POST_DATA];
$imageData = str_replace('data:image/png;base64,', '', $imageData);
$imageData = str_replace(' ', '+', $imageData);
$data = base64_decode($imageData);
//here i need the value1 value from the javascript
$dirname = "value1";
$filename = "header_top.png";
$newdir = mkdir($dirname);
$path = ("the/path/to".$dirname."/");
$fp = fopen($path.$filename, 'wb');
fwrite($fp, $data);
fclose($fp);
}
I hope I was able to explain myself so you can help me.
Thank you very much.
EDIT:
I think i get it, i mean for the moment it works but i don't know if it the right way doing it.
The fact is that i'm calling a php file so i simple added at the end of the url "?dir="+value1 and it works.
ajax.open("POST", 'saving.php?dir='+value1, false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
and in the php file i simply call $_GET['dir'] to get the value.
#hendrik thank you very much for your answer, unfortunaly i can't get it work with json, maybe becouse i didn't know it.
Anyway if someone knows a better way would be nice.
I think using JSON would be a good way to send the data to your PHP file. That way you can store multiple variables in an Object or Array.
// Store your data in an Object
var imageData = {
url: 'http://adsadsf.com',
name: 'foobar.gif',
width: 500,
height: 400,
directory: 'img/'
}
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
// Send the imageData object as JSON
ajax.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
ajax.send(JSON.stringify(imageData));
Unfortunately I don't know enough about PHP to explain exactly how to handle the received JSON data, but I guess you can use the json_decode method for that.
More about JSON: http://www.json.org/js.html
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 an canvas on my site where the user can draw and can also add an image. By clicking a Save button I want the canvas to be saved as a PNG image.
Everything works fine in Firefox, but in Chrome for example when I add an image in the canvas and then try to save it, the image on the canvas has not been saved.
My code in javascript for adding an image is:
var imageObj = new Image();
imageObj.onload = function(){
x.drawImage(this, destX, destY, destWidth, destHeight);
};
imageObj.src = 'myImage.png';
Then for saving the canvas:
var drawingString = myDrawing.toDataURL("image/png");
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST",'save_image.php',true);
<!-- set the mime type so the image goes through as base64 -->
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function() {
<!-- once the image data has been sent -->
if (ajax.readyState == 4){
alert("Saved");
}
}
ajax.send(postData);
and in PHP:
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data like you would with traditional post
$rawImage=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers
$removeHeaders=substr($rawImage, strpos($rawImage, ",")+1);
// decode it from base 64 and into image data only
$decode=base64_decode($removeHeaders);
// save to your server
$imageFile = 'myImage.png';
$fopen = fopen($imageFile, 'w' );
fwrite( $fopen, $decode);
fclose( $fopen );
}
The problem is that the background canvas it is saved in both cases. Only the image on top of the background is note saved in Chrome, Safari or IE. Does anyone know why this code is behaved differently in Firefox and in other browsers?
I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.