HTML5 save canvas to file on server - javascript

i need to create a component using html5 canvas that given an image the user can paint on it and directly (via a kind of save button) upload it's customized version on the server.
Can i use html canvas for it ?
Any suggestion ?
thx in advance

You can get the image as data-url like this:
var dataUrl = document.getElementById('your-canvas').toDataURL();
You could then send this (very long string) to the server and save it to a file after decoding it (it is encoded in base64).
EDIT: Remember to submit this via POST, as suggested in the comments. GET has some length-limits in various browsers, so its likely to exceed those limits with such a huge amout of data.

Note that this is currently dead-on-arrival for Android (up to and including 2.3). Please star this issue - http://code.google.com/p/android/issues/detail?id=7901

Related

Convert string to image and send it to WhatsApp

I'm developing a phonegap app and I need it to be able to convert a string that will be in a localStorage variable into a PNG image and share it on WhatsApp Messenger. I've never done somethin' like that before. The idea of using canvas to generate the Image came to mind but I have no idea how to work it out from there and sent the data I've got from the dataToUrl function to WhatsApp. If someone can give me an idea on how to do it or an alternative way to do it I'd really appreciate. The string will be something like shown below:
"##########################Central Jogos##########################Apostador: testValor Apostado: R$5Valor Retorno: R$6.15Data Aposta: 19/02/2017 15:07Qtd. Jogos: 1-----------------------------------------Vasco X FlamengoEmpate: 1.2310/03/2017 15:30=======================Cambista: Cambista TesteTelefone: (82) 9977-8877"
I just found this cordova plugin that allows you to share images, links, base64 and other things not just on WhatsApp Messenger but also on Facebook, Twitter and a bunch of other apps. I think it might be extremely helpfull. Thank you guys that answered me.
SocialShare GitHub Repo
You can generate a base64 string from a <canvas>.
You need to use the <canvas> element where your image is going to be stored, basically you need to load your image into the canvas.
Then you can use the toDataURL to get the string on base64 format.
Convert your image to Base64 String like these image uri to Base64
Draw an image canvas using this Base64 string Base64 png data to html5 canvas
Reconvert Base64 string to Image using HTML5 Canvas to PNG File
you can also save the canvas image file by using reimg library
just save and share the saved image by step 4 on button click

how to secure img src path when user clicks on view source using javascript?

How to secure the src path of the image when clicks on inspect element so that user should not get to know about the actual src path..please help me with the solution and it should be done with javascript only no other tags should be used.
You can convert image into base 64 data URIs for embedding images.
Use: http://websemantics.co.uk/online_tools/image_to_data_uri_convertor/
Code sample:
.sprite {
background-image:url(data:image/png;base64,iVBORw0KGgoAAAA... etc );
}
This is commonly done server-side, where you have an endpoint that serves the image file to you as bytes...
You can store the images in a private location on the server where IIS/<your favourite web server> doesn't have direct access to it, but only a web app, running on it, with the required privilege is authorized to do so.
Alternatively people also "store" the images in the database itself and load it directly from there.
In either case, the response which has to be sent back has to be a stream of bytes with the correct mime type.
Edit:
Here are a couple of links to get you started if you are into ASP.NET:
http://www.codeproject.com/Articles/34084/Generic-Image-Handler-Using-IHttpHandler
http://aspalliance.com/1322_Displaying_Images_in_ASPNET_Using_HttpHandlers.5 <- this sample actually does it from a database.
Don't let the choice of front-end framework (asp.net, php, django, etc) hinder you. Search for similar techniques in your framework of choice.
Edit:
Another way if you think html5 canvas is shown here: http://www.html5canvastutorials.com/tutorials/html5-canvas-images/
However you run into the same problem. Someone can view the image url if they can see the page source. You'll have to revert to the above approach eventually.

Force image caching with javascript

I am trying to clone an image which is generated randomly.
Although I am using the exact same url a different image is load. (tested in chrome and firefox)
I can't change the image server so I am looking for a pure javascript/jQuery solution.
How do you force the browser to reuse the first image?
Firefox:
Chrome:
Try it yourself (maybe you have to reload it several times to see it)
Code:
http://jsfiddle.net/TRUbK/
$("<img/>").attr('src', img_src)
$("<div/>").css('background', background)
$("#source").clone()
Demo:
http://jsfiddle.net/TRUbK/embedded/result/
You can't change the image server if it isn't yours, but you can trivially write something on your own server to handle it for you.
First write something in your server-side language of choice (PHP, ASP.NET, whatever) that:
Hits http://a.random-image.net/handler.aspx?username=chaosdragon&randomizername=goat&random=292.3402&fromrandomrandomizer=yes and downloads it. You generate a key in one of two way. Either get a hash of the whole thing (MD5 should be fine, it's not a security-related use so worries that it's too weak these days don't apply). Or get the size of the image - the latter could have a few duplicates, but is faster to produce.
If the image isn't already stored, save it in a location using that key as part of its filename, and the content-type as another part (in case there's a mixture of JPEGs and PNGs)
Respond with an XML or JSON response with the URI for the next stage.
In your client side-code, you hit that URI through XmlHttpRequest to obtain the URI to use with your images. If you want a new random one, hit that first URI again, if you want the same image for two or more places, use the same result.
That URI hits something like http://yourserver/storedRandImage?id=XXX where XXX is the key (hash or size as decided above). The handler for that looks up the stored copies of the images, and sends the file down the response stream, with the correct content-type.
This is all really easy technically, but the possible issue is a legal one, since you're storing copies of the images on another server, you may no longer be within the terms of your agreement with the service sending the random images.
You can try saving the base64 representation of the image.
Load the image in an hidden div/canvas, then convert it in base64. (I'm not sure if a canvas can be hidden, nor if it is possible to convery the img using html4 tag)
Now you can store the "stringified" image in a cookie, and use it unlimited times...
The headers being sent from your random image generator script include a Cache-Control: max-age=0 declaration which is in essence telling the browser not to cache the image.
You need to modify your image generator script/server to send proper caching headers if you want the result to be cached.
You also need to make sure that the URL stays the same (I didn't look at that aspect since there were tons of parameter being passed).
There seems to be two workarounds:
If you go with the Canvas method, see if you can get the image to load onto the Canvas itself so that you can manipulate the image data directly instead of making a 2nd http request for the image. You can feed the image data directly onto a 2nd Canvas.
If you're going to build a proxy, you can have the proxy remove the No-Cache directive so that subsequent requests by your browser use the cache (no guarantees here - depends on browser/user settings).
First off, you can "force" anything on the web. If you need to force things, then web development is the wrong medium for you.
What you could try, is to use a canvas element to copy the image. See https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images for examples.
Tell it to stop getting a random image, seems to work the way you want when I add this third replace call:
// Get the canvas element.
var background = ($("#test").css('background-image')),
img_src = background.replace(/^.+\('?"?/, '').replace(/'?"?\).*$/, '').replace(/&fromrandomrandomizer=yes/,'')
try:
var myImg = new Image();
myImg.src = img_src;
and then append "myImg" to where you want:
$(document).append(myImg);
I did this with your fiddler scripts and got the same image every time
#test {
background:url(http://a.random-image.net.nyud.net/handler.aspx?username=chaosdragon&randomizername=goat&random=292.3402&fromrandomrandomizer=yes);
width: 150px;
height: 150px;
}
note the .nyud.net after the domain name.

How to save an image converted from a canvas, on the computer, in a user-friendly manner?

I'm using Nihilogic's library Canvas2Image to convert canvas drawings to PNG, and to give the users of my application the possibility to download that image.
What I need is to be able to give the downloadable file a name and the png extension (e.g. "goalboard.png") and not have it download just as an octet stream with no recognizable extension and the name "download", because the average Joe won't know what to do with such a file. And I need to do this on the client-side, because sending that byte stream to the server, depending on the quantity of data in it, can take up to 20 seconds (it's a big canvas!). Not to mention retrieving the image afterward...
So, how do I do this?
One of these should solve your problem (with canvas you can extract the image in base64 format):
Using HTML5/Javascript to generate and save a file
Reading a local file, encoding to base64, I would like to give the user an option to save the result to file
I had a big RaphaelJs canvas too and needed to allow the user to run a script that would save lots of canvas as png images.
I tried to transform my raphael into an svn, then my svg to a png and then using wget but that of course didn't work because my canvas where generated by javascript and wget can't deal with that. In the end I realised that I could just have my webapp to build a page with just the svg canvas and use phantomjs ( a headless browser) to save it as a png. It works briliantly.
It is as simple as that.
1. Make your webapp to build a page with just the svg canvas.
2. Create a svgToPgn.js file with the following code :
var page = require('webpage').create();
page.open('URL_TO_YOUR_HTML_PAGE', function() {
page.render('PATH_TO_PNG/example.png');
phantom.exit();
});
3. Download Phantom (http://phantomjs.org), unzip it and in the bin directory you will find the phantomjs executable. Run :
./phantomjs svgToPgn.js
Your png file will be saved in : PATH_TO_PNG/example.png
And I need to do this on the client-side
Well that requirement kind of kills your chances. Sorry.
You can't do what you want to do, the best you've got is displaying the image and telling the user to right-click save-as.

loading an image through javascript

is there a way to load the full binary of an image in javascript?
what i want to do is to allow the user to preview an image before uploading it.
ie the user selects an image on his local drive (C:\image.jpg) , view it, and decides to upload or cancel.
i tried to set the source to the image path, but it didn't work since it is outside the webapplication project folder.
any help?
thx for your posts, but i ended up creating a temp folder on the server that stores the uploaded image using ajax. and when the user saves the data, the image is moved to another location, and the temp folder is deleted.
You can do something like this:
<img id="preview" src="" style="display:none;" />
<form>
....
<input type="file" id="file" />
....
</form>
<script type="text/javascript">
var file = document.getElementById("file");
var img = document.getElementById("preview");
file.onchange = function(){
img.src = file.value;
img.style.display = 'block';
};
</script>
There is no easy way, what You could do:
Preload image with some ajax file uploader to temp area and then let user decide
Use some third party written solution (f.ex. some flash component)
Here there is also similar question:
is it possible to preview local images before uploading them via a form?
You need server cooperation to access the image binary data. You won't be able to use the "Upload Form" to access the file info without uploading it to a server.
You could however do something like tell the user to paste the source binary data of the image in a textarea or something, then you can use JavaScript to load that binary data and display the actual image.
This is available in some browsers via the HTML5 file access API. Here is the Firefox documentation for file access.
As answered several times, you can't do this with plain HTML/JavaScript due to security restrictions. You need to send the image anyway. You can however handle this using a Java Applet since it runs entirely at the client machine and offers more control than HTML/JS. There are several free and ready-to-use ones. JumpLoader looks good and some major sites also uses it. With Flash it should also be possible, but I am not sure which ones offers this functionality. Check/tryout some Flash Multi File Uploaders.

Categories