When i try to upload a file via jQuery File Upload i am taking below response.
Is it posible to add image dimensions to this result like width: 300px and height: 400px? I try to edit UploadHandler.php for that need but i can't success. There is a function called set_additional_file_properties in UploadHandler.php. I tried to add a custom variable to the function but it fails because i think this function called before the file upload process. It even could not find the file to get dimensions. I don't know why probably i am looking to wrong side of the document.
protected function set_additional_file_properties($file) {
$file->dimensions = file_exists($file->url);
$file->deleteUrl = $this->options['script_url']
.$this->get_query_separator($this->options['script_url'])
.$this->get_singular_param_name()
.'='.rawurlencode($file->name);
$file->deleteType = $this->options['delete_type'];
if ($file->deleteType !== 'DELETE') {
$file->deleteUrl .= '&_method=DELETE';
}
if ($this->options['access_control_allow_credentials']) {
$file->deleteWithCredentials = true;
}
}
Solution
protected function set_additional_file_properties($file) {
$a = getimagesize(realpath(dirname($file->url))."/".$file->name);
$width = $a[0];
$height = $a[1];
if ($a) {
$file->width = $width;
$file->height = $height;
}
...
}
If I get your problem (you want to add width and height information to the image on the server side) then this should help:
http://php.net/manual/function.getimagesize.php
Returns an array with up to 7 elements. Not all image types will include the channels and bits elements.
Index 0 and 1 contains respectively the width and the height of the image.
=> getimagesize($file)
Only need to change UploadHandler.php file in set_additional_file_properties($file) function for the following:
protected function set_additional_file_properties($file) {
$filesize = getimagesize("files/".$file->name); //'files' folder is default folder to upload
$width = $filesize[0];
$height = $filesize[1];
if ($filesize) {
$file->width = $width;
$file->height = $height;
}
$file->deleteUrl = $this->options['script_url']
.$this->get_query_separator($this->options['script_url'])
.$this->get_singular_param_name()
.'='.rawurlencode($file->name);
$file->deleteType = $this->options['delete_type'];
if ($file->deleteType !== 'DELETE') {
$file->deleteUrl .= '&_method=DELETE';
}
if ($this->options['access_control_allow_credentials']) {
$file->deleteWithCredentials = true;
}
}
just added these lines:
$filesize = getimagesize("files/".$file->name); //'files' folder is default folder to upload
$width = $filesize[0];
$height = $filesize[1];
if ($filesize) {
$file->width = $width;
$file->height = $height;
}
Related
I've created a functionality on my website where user's can change the background image via upload. The procedure is following:
User goes to settings page and selects an image file to be uploaded. After selecting image, the browser will output it so that user can preview
it before actually saving it's file to in to the folder and filepath in to the database. After that, if user is happy with the result, he can save it to the
folder by pressing "Upload Background Image" button.
All of the above is handled with AJAX.
I am having trouble to just output the image to the browser without actually saving it twice, first into tests folder and after that into backgrounds folder.
I'm using CodeIgniter as my backend framework and jQuery for my AJAX requests.
Here are my methods for outputting (testing) and saving the image:
public function test_image()
{
if($this->input->is_ajax_request())
{
// This part of code needs to be replaced to only just output the image (return it as a JSON), not actually saving it to another a folder
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
$new_img_name = random_string('unique'). "." . $ext;
$config['upload_path'] = './public/images/uploads/tests';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '2000';
$config['max_height'] = '1600';
$config['file_name'] = $new_img_name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('image_errors' => $this->upload->display_errors('<p class="text-center">','</p>'))));
return false;
} else {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('userfile' => $new_img_name)));
}
} else {
echo "Not an ajax request";
}
}
// This method works properly
public function upload_background_image()
{
if (isset($_POST))
{
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
$new_img_name = random_string('unique'). "." . $ext;
$config['upload_path'] = './public/images/uploads/backgrounds';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '2000';
$config['max_height'] = '1600';
$config['file_name'] = $new_img_name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('image_errors' => $this->upload->display_errors('<p class="text-center">','</p>'))));
return false;
} else {
$this->load->model('user_model');
$user_id = $this->session->userdata('user_id');
$upload_photo = $this->user_model->updateUserInfo($user_id, ['body_background_url' => $new_img_name]);
if ($upload_photo === true) {
$this->session->set_userdata(['body_background_url' => $new_img_name]);
redirect(base_url());
}
}
}
}
And here's my AJAX:
$("#bg-cover-file").change(function(e) {
e.preventDefault();
var form = $(this).closest('form');
form.ajaxSubmit({
dataType: 'json',
beforeSubmit: function() {
},
success: function(response) {
if(response.userfile) {
// Output the image
$('.test-image').attr('src', response.userfile);
$('span.file-input').hide();
// Change the form action attribute
var new_path = 'uploads/upload_background_image';
form.attr('action', new_path);
} else {
$('#error-modal').modal('show');
$("#error-body").html(response.image_errors);
return false;
}
}
});
return false;
});
--Working Demo--
I have put comments in this demo to explain what the steps are so please read them.
If you don't understand anything in this answer please leave a comment below and i will update the answer until you understand line for line. You don't learn from copy/paste so please be sure to understand the answer.
function MyFunction() {
var img=document.getElementById('BackgroundImage');
var Status=document.getElementById('Status');
var savebtn=document.getElementById('savebtn');
/* SetBG will target the body tag of the web page.
You can change this to any element -
var SetBG=document.getElementById('YourID').style;
*/
var SetBG=document.body.style;
//Split the image name
var fileExt=img.value.split('.');
//Use the last array from the split and put to lowercase
var fileformat=fileExt[fileExt.length -1].toLowerCase();
// Check the file extension (Image formats only!)
if((fileformat==='jpg')||(fileformat==='gif')||(fileformat==='png')||(fileformat==='jpeg')) {
if (img.files && img.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//----Image is ready for preview.
SetBG.background='url('+e.target.result+') no-repeat center center fixed';
/*---- Optional, Set background as cover ---*/
SetBG.backgroundSize="cover";
SetBG.OBackgroundSize="cover";
SetBG.webkitBackgroundSize="cover";
//--Hide Loading Message
Status.style.display="none";
//----- Display (Save/Upload button?)
savebtn.style.display="block";
}
/*-------Reading File....
Display a message or loading gif for large images to be processed?
*/
Status.innerHTML="Loading...";
Status.style.display="block";
savebtn.style.display="none";
reader.readAsDataURL(img.files[0]);
}
}else{
/*----User file input not accepted (File isn't jpg/gif/png/jpeg)
Empty the input element and set the background to default.
*/
Status.innerHTML="Format not accepted";
Status.style.display="block";
savebtn.style.display="none";
SetBG.background='white';
document.getElementById('BackgroundImage').value='';
}
}
#Status{display:none;background:white;color:black;font-size:16pt;}
#savebtn{display:none;}
<div id="Status"></div>
<input type="file" id="BackgroundImage" onchange="MyFunction()"/>
<button id="savebtn" onclick="alert('Now upload the image');">Upload and save</button>
I hope this helps. Happy coding!
This may help you
let assume your browse button's id is bg-cover-file and the id of the image tag where you want to display the image preview_image
$(document).on("change", "#bg-cover-file", function(event)
{
if (this.files && this.files[0])
{
var reader = new FileReader();
reader.onload = function (e)
{
$('#preview_image').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
function MyFunction() {
var img=document.getElementById('BackgroundImage');
var Status=document.getElementById('Status');
var savebtn=document.getElementById('savebtn');
/* SetBG will target the body tag of the web page.
You can change this to any element -
var SetBG=document.getElementById('YourID').style;
*/
var SetBG=document.body.style;
//Split the image name
var fileExt=img.value.split('.');
//Use the last array from the split and put to lowercase
var fileformat=fileExt[fileExt.length -1].toLowerCase();
// Check the file extension (Image formats only!)
if((fileformat==='jpg')||(fileformat==='gif')||(fileformat==='png')||(fileformat==='jpeg')) {
if (img.files && img.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//----Image is ready for preview.
SetBG.background='url('+e.target.result+') no-repeat center center fixed';
/*---- Optional, Set background as cover ---*/
SetBG.backgroundSize="cover";
SetBG.OBackgroundSize="cover";
SetBG.webkitBackgroundSize="cover";
//--Hide Loading Message
Status.style.display="none";
//----- Display (Save/Upload button?)
savebtn.style.display="block";
}
/*-------Reading File....
Display a message or loading gif for large images to be processed?
*/
Status.innerHTML="Loading...";
Status.style.display="block";
savebtn.style.display="none";
reader.readAsDataURL(img.files[0]);
}
}else{
/*----User file input not accepted (File isn't jpg/gif/png/jpeg)
Empty the input element and set the background to default.
*/
Status.innerHTML="Format not accepted";
Status.style.display="block";
savebtn.style.display="none";
SetBG.background='white';
document.getElementById('BackgroundImage').value='';
}
}
#Status{display:none;background:white;color:black;font-size:16pt;}
#savebtn{display:none;}
<div id="Status"></div>
<input type="file" id="BackgroundImage" onchange="MyFunction()"/>
<button id="savebtn" onclick="alert('Now upload the image');">Upload and save</button>
i'm trying to use PHP to move some files, as it does that I have a script which will compare the source location with the destination location and work out the difference.
It all starts with a button like so:
<input type="button" class="upload_button" onClick="upload_images('drive_<?=$x["letter"]?>');start_upload_progress()" value="<?=$x["name"]?>"/>
This then starts these two scripts:
function upload_images(x) {
var url = "http://localhost:1234/ppa/php/process_upload.php?x="+x
doc("upload_iframe").src = url;
}
First of all it will change a hidden iframe url to the PHP script and send over the drive letter.
function start_upload_progress() {
upload_progress("http://localhost:1234/ppa/php/upload_progress.php",function() {
doc("upload_bar").innerHTML = this;
if(this != 100) {
//doc("upload_bar").innerHTML = x;
setTimeout(start_upload_progress(),1000);
}
});
}
Next the above script will start, the console.log is simply for me to see if it's working, although I do not see "start" in my console. This function uses a callback, the below code simply loads a PHP script and returns the result. If the result is less than 100 then the call is made again every couple of seconds.
function upload_progress(url, callback) {
var http = getHTTPObject();
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
if (http.responseText == "true") {
//window.location.replace("http://localhost:1234/ppa/rotate.php");
}
callback.call(http.responseText);
}
};
http.open("GET", url, true);
http.send();
}
Below is the PHP script, this was working when I set the $_SESSION['tmp'] variable manually.
<?php
session_start();
//If session has been created then ready to start progress bar
if (isset($_SESSION['tmp'])) {
if ($_SESSION['tmp'] != "true") {
$session_date = str_replace("/","",$_SESSION['session_date']);
$tmp = explode("_", $_SESSION['tmp']);
$upload_number = $tmp[1];
$drive = $tmp[0];
//get paths
$destination = $_SESSION['ROOT_PATH']."data/images/".str_replace("/","",$_SESSION['session_date'])."/".$upload_number."/";
$source = $drive.":/DCIM/";
if (is_dir($destination) && is_dir($source)) {
$source_size = foldersize($source);
$destination_size = foldersize($destination);
echo "Percentage: ".floor(($destination_size / $source_size * 100));
}
} else {
echo "done: ".$_SESSION['tmp'];
}
}
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/'). '/';
foreach($files as $t) {
if ($t<>"." && $t<>"..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
}
else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
?>
The $_SESSION['tmp'] variable is created just before the files begin to move, it seems like I can't access this session variable until the code has finish executing...
It is created here, at the top of the file moving script:
if (isset($drive)) {
$x = explode("_", $drive);
$x = $x[1];
//Check if connected file exists
if(file_exists($x.":/connected.txt")) {
$file = file_get_contents($x.":/connected.txt");
if ($file != false) {
$file_code = split(":", $file);
//Check if the file has the correct pass code
if($file_code[0] == $code) {
$_SESSION['tmp'] = $x."_".$drive;
When the files have finished moving the variable is set to "true", which seems to be the only value I can get...
Any ideas why my "start_upload_progress" function is not working? The console.log isn't running and I don't think the $_SESSION['tmp'] variable is setting until the file moving script has finished.
Edit 2:
I have got the script running, it compares the source and the destination and updated the innerHTML of the div with the difference. Only issue is that it only seems to work when I move the files from one place to the other manually.
The upload_progress script seems to freeze whilst the files are being moved, it should run at the same time to check the progress.
I have watched the files disappear from the source folder as well but all at the same time, shouldn't they move one by one as the scripting is only moving them one by one...
I want to upload a video file using PHP and show the progress of the upload via an Progress Bar. But this is more difficult like i thought and i tried to put the pieces ive found together but unfortunately i didnt found a working piece of code that has the needed php, ajax and html code all together, so ive tried to put different pieces together.
My Code functions nearly completely. The only thing is, that the current process of the file upload, which i've got in percent, is loaded by my javascript only AFTER the process has ended, and not from the beginning.
Here is my PHP Code:
function file_get_size($file) {
//open file
$fh = fopen($file, "r");
//declare some variables
$size = "0";
$char = "";
//set file pointer to 0; I'm a little bit paranoid, you can remove this
fseek($fh, 0, SEEK_SET);
//set multiplicator to zero
$count = 0;
while (true) {
//jump 1 MB forward in file
fseek($fh, 1048576, SEEK_CUR);
//check if we actually left the file
if (($char = fgetc($fh)) !== false) {
//if not, go on
$count ++;
} else {
//else jump back where we were before leaving and exit loop
fseek($fh, -1048576, SEEK_CUR);
break;
}
}
//we could make $count jumps, so the file is at least $count * 1.000001 MB large
//1048577 because we jump 1 MB and fgetc goes 1 B forward too
$size = bcmul("1048577", $count);
//now count the last few bytes; they're always less than 1048576 so it's quite fast
$fine = 0;
while(false !== ($char = fgetc($fh))) {
$fine ++;
}
//and add them
$size = bcadd($size, $fine);
fclose($fh);
return $size;
}
$filesize = file_get_size('remote-file');
$remote = fopen('remote-file', 'r');
$local = fopen('local-file', 'w');
$read_bytes = 0;
while(!feof($remote)) {
$buffer = fread($remote, 2048);
fwrite($local, $buffer);
$read_bytes += 2048;
//Use $filesize as calculated earlier to get the progress percentage
$progress = min(100, 100 * $read_bytes / $filesize);
fwrite(fopen('files/upload/progress.txt', 'w'), $progress);
//you'll need some way to send $progress to the browser.
//maybe save it to a file and then let an Ajax call check it?
}
fclose($remote);
fclose($local);
This is my Javascript Code:
function main()
{
var pathOfFileToRead = "files/upload/progress.txt";
var contentsOfFileAsString = FileHelper.readStringFromFileAtPath
(
pathOfFileToRead
);
document.body.innerHTML = contentsOfFileAsString;
}
function FileHelper()
{}
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
main();
function progressBarSim(al) {
var bar = document.getElementById('bar-fill');
var status = document.getElementById('status');
status.innerHTML = al+"%";
bar.value = al;
al++;
var sim = setTimeout("progressBarSim("+al+")",1000);
if(al == 100){
status.innerHTML = "100%";
bar.value = 100;
clearTimeout(sim);
var finalMessage = document.getElementById('finalMessage');
finalMessage.innerHTML = "Process is complete";
}
}
var amountLoaded = 0;
progressBarSim(amountLoaded);
The Progressbar does currently work over an Timer, because the main() function doesnt read the content of the "progress.txt" from the beginning but only at the end. so i would like to have some help to combine progressBarSim with main().
*Edit: * I have found a working piece of code: http://www.it-gecko.de/html5-file-upload-fortschrittanzeige-progressbar.html and am using that now.
Here is a ajax function for modern browsers:
//url,callback,type,FormData,uploadFunc,downloadFunc
function ajax(a,b,e,d,f,g,c){
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
more about this function https://stackoverflow.com/a/18309057/2450730
here is the html
<form><input type="file" name="file"><input type="submit" value="GO"></form>
<canvas width="64" height="64"></canvas>
<canvas width="64" height="64"></canvas>
<pre></pre>
you can add more fields inside the form and you don't need to change anything in the javascript functions. it always sends the whole form.
this is the code to make this ajax function work
var canvas,pre;
window.onload=function(){
canvas=document.getElementsByTagName('canvas');
pre=document.getElementsByTagName('pre')[0];
document.forms[0].onsubmit=function(e){
e.preventDefault();
ajax('upload.php',rdy,'post',new FormData(this),progressup,progressdown)
}
}
function progressup(e){
animate(e.loaded/e.total,canvas[0],'rgba(127,227,127,0.3)')
}
function progressdown(e){
animate(e.loaded/e.total,canvas[1],'rgba(227,127,127,0.3)')
}
function rdy(e){
pre.textContent=this.response;
}
this is the animation that moves the circular canvas progress bar
function animate(p,C,K){
var c=C.getContext("2d"),
x=C.width/2,
r=x-(x/4),
s=(-90/180)*Math.PI,
p=p||0,
e=(((p*360|0)-90)/180)*Math.PI;
c.clearRect(0,0,C.width,C.height);
c.fillStyle=K;
c.textAlign='center';
c.font='bold '+(x/2)+'px Arial';
c.fillText(p*100|0,x,x+(x/5));
c.beginPath();
c.arc(x,x,r,s,e);
c.lineWidth=x/2;
c.strokeStyle=K;
c.stroke();
}
you can extend this function with some nice bounce effect on initializzation or on progresschange.
http://jsfiddle.net/vL7Mp/2/
to test i would just simply use a upload.php file like that
<?php
print_r(array('file'=>$_FILE,'post'=>$_POST));
?>
test it with chrome first... then apply the necessary changes to use it with older browsers... anyway this code should work with all the newest browsers now.
i understand that this functions are not simple to understand so ...
if you have any questions just ask.
maybe there are some syntax error or something is missing... because i just copied the whole functions and applied some changes on the fly.
some other useful functions:
display a readable filesize:
https://stackoverflow.com/a/20463021/2450730
convert MS to time string or a time string to MS
function ms2TimeString(a){
var ms=a%1e3>>0,s=a/1e3%60>>0,m=a/6e4%60>>0,h=a/36e5%24>>0;
return (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s)+'.'+(ms<100?(ms<10?'00'+ms:'0'+ms):ms);
}
function timeString2ms(a){
var ms=0,b;
a=a.split('.');
!a[1]||(ms+=a[1]*1);
a=a[0].split(':'),b=a.length;
ms+=(b==3?a[0]*3600+a[1]*60+a[2]*1:b==2?a[0]*60+a[1]*1:s=a[0]*1)*1e3;
return ms
}
A simple PAD LEFT function
function padL(a,b,c){//string,length=2,char=0
return (new Array(b||2).join(c||0)+a).slice(-b);
}
ps.i'm also working on a conversion progress bar. if you are intrested i can show you my progress.
I would like to ask for any suggestion on how to implement PDF download with private document in Scribd.
Code to upload the document with Scribd using PHP.
function allowPdf($doc_ids) {
$method = "docs.changeSettings";
$params['doc_ids'] = $doc_ids;
$params['access'] = 'private';
$params['download_formats'] = 'pdf';
$params['disable_select_text'] = 1;
// Method from Scribd Developer
// http://www.scribd.com/clients/scribd_php_client.zip
$result = $this->postRequest($method, $params);
return $result;
}
In the Front End code to render out the Scribd JS.
function renderScribdDoc(doc_id, access_key, id) {
id = id || 'embedded_doc';
var scribd_doc = scribd.Document.getDoc(doc_id, access_key),
onDocReady = function(e) {};
scribd_doc.addParam('jsapi_version', 2);
scribd_doc.addParam('hide_disabled_buttons', false);
scribd_doc.addParam('public', true);
scribd_doc.addParam('width', 520);
scribd_doc.addParam('height', 390);
scribd_doc.addEventListener('docReady', onDocReady);
scribd_doc.write(id);
}
I don't know what is the correct way to pass the parameter in Scribd to allow user to download private document as PDF.
Thank you very much.
I need to upload the canvas image data to the server (database) on the fly, i.e., I need to create a form and with an input=file, and post the image data without any user interaction.
FWIW, this is how I got it working.
My server is in google app engine. I send canvas.toDataURL()'s output as part of post request using jQuery.post. The data URL is base64 encoded image data. So on server I decode it and convert it to image
import re
import base64
class TnUploadHandler(webapp.RequestHandler):
dataUrlPattern = re.compile('data:image/(png|jpeg);base64,(.*)$')
def post(self):
uid = self.request.get('uid')
img = self.request.get('img')
imgb64 = self.dataUrlPattern.match(img).group(2)
if imgb64 is not None and len(imgb64) > 0:
thumbnail = Thumbnail(
uid = uid, img = db.Blob(base64.b64decode(imgb64)))
thumbnail.put()
From client I send the data like this:
$.post('/upload',
{
uid : uid,
img : canvas.toDataURL('image/jpeg')
},
function(data) {});
This may not be the best way to do it, but it works.
You don't need a file input, just get the data with ctx.getImageData() and post it to the server with Ajax.
See the MDN Documentation for CanvasRenderingContext2D.getImageData().
But you won't be able to get the image data in IE, even with ExCanvas.
Here is how I solved this. Posting the image as base64 array using JavaScript and then decoding and saving it as a image using PHP.
Client side (JavaScript):
$.post('/ajax/uploadthumbnail',
{
id : id,
img : canvas.toDataURL("image/png")
}, function(data) {
console.log(data);
});
Server side (PHP):
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $_SERVER['DOCUMENT_ROOT'] . '/images/some_name.png';
file_put_contents($file, $data);
Here is a demo of an online signature app that I wrote last year Canvas Signature Demo. This has the advantage of posting only the vector data to the server. With all of the path info, you could also apply smoothing algorithms or scale it as needed before persisting.
<canvas id="signature" width="300" height="100"></canvas>
<form method="post" id="signature_form" action="signing.aspx">
<input type="hidden" name="paths" id="paths"/>
<p><label>Cover #</label> <input type="text" id="covernumber" name="covernumber"/>
<input type="submit" id="save" value="Save"/>
</form>
I store the path data into a hidden field and post that to the server.
signature.js Core logic below:
mouseDown: function(event) {
var point = this.getRelativePoint(event);
this.paths.push( [ point ] );
this.ctx.fillRect(point.x,point.y,1,1);
this.penDown = true;
this.updateField();
},
mouseUp: function(event) {
this.penDown = false;
this.ctx.closePath();
if ( Prototype.Browser.IE && event.srcElement.tagName != "INPUT" ) {
var ver = getInternetExplorerVersion();
if ( ver >= 8 && ver < 9 && document.selection ) {
document.selection.empty();
}
}
},
mouseMove: function(event) {
if ( this.penDown ) {
var lastPath = this.paths[ this.paths.length - 1 ];
var lastPoint = lastPath[ lastPath.length - 1 ];
var point = this.getRelativePoint(event);
lastPath.push( point );
this.ctx.strokeStyle = "#000000";
this.ctx.beginPath();
this.ctx.moveTo(lastPoint.x,lastPoint.y);
this.ctx.lineTo(point.x, point.y);
this.ctx.stroke();
this.ctx.closePath();
this.updateField();
}
},
updateField: function() {
if ( this.field ) {
this.field.value = this.paths.toJSON();
}
}
Here is my relevant server side .Net code (C#).
if ( Request("paths") ) {
var objBitmap : Bitmap = new Bitmap(300, 100);
var objGraphics : Graphics = Graphics.FromImage(objBitmap);
objGraphics.Clear(Color.Transparent);
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
var paths:Array = eval(Request("paths")) || [];
var p : int;
var q : int;
var path : Array;
for ( p = 0; p< paths.length; p++ ) {
var path = paths[p];
if ( path.length == 1 ) {
objGraphics.DrawRectangle(new Pen(Color.Black), path[0].x, path[0].y, 1, 1);
} else {
for ( q = 1; q<path.length; q++ ) {
var prev = path[q-1];
var curr = path[q];
objGraphics.DrawLine(new Pen(Color.Black), parseInt(prev.x),parseInt(prev.y),parseInt(curr.x),parseInt(curr.y));
}
}
}
objBitmap.Save("C:\\temp\\" + Request("covernumber") + ".png", ImageFormat.Png);
objBitmap.Dispose();
objGraphics.Dispose();
}
You can get the image data in the form of a data: url, this only works in Firefox and Opera so far though.
http://cow.neondragon.net/index.php/681-Canvas-Todataurl