Generate image data from HTML Canvas element - javascript

What is the best way to generate image data from the contents of an HTML canvas element?
I'd like to create the image data such that it can be transmitted to a server (it's not necessary for the user to be able to directly save to a file). The image data should be in a common format such as PNG or JPEG.
Solutions that work correctly in multiple browsers are preferred, but if every solution depends on the browser, recent versions of Firefox should be targeted.

Firefox and Opera have a toDataURL() method that returns a data-URL formatted PNG. You can assign the result to a form field to submit it to the server.
The data URL is base-64 encoded, so you will have to decode it on the server side. You would also need to strip off the "data:image/png;" part of course.

I think a lib you can use is Canvas2Image, it uses native features from Canvas, but it won't work on any browser. I have an optimized version of this lib, if you want to, I'll share it with you.
Then you could get the generated Data URI and send it using Ajax to the server.

Related

Convert already loaded image to base64

I have a use case to convert images to base64 using the url. But the website loads the image only once. I cannot convert to canvas since it requires a network call and is forbidden for second time.
But I am able to achieve the conversion using the sources panel in chrome which has an option to convert already loaded images to data URI. Ex: https://developers.google.com/web/updates/2015/05/copy-image-as-data-uri
I would like to do this programatically using javascript.
Either I inject a module while the image loads to convert to base64 and store it or access the sources panel in chrome to convert to data URI as it does.
I would like to know if there are any extensions to achieve this.
Thank you

Get binary image data from input type "file" using JavaScript/jQuery for use with picture preview with AJAX in WebMatrix [duplicate]

This question already has answers here:
Closed 10 years ago.
I have had trouble when researching or otherwise trying to figure out how (if it's even possible) to get binary image data using JavaScript/jQuery from an html input element of type file.
I'm using WebMatrix (C#), but it may not be necessary to know that, if the purposes of this question can be answered using JavaScript/jQuery alone.
I can take the image, save it in the database (as binary data), then later show the pic on the page, from the binary data, after posting. This does, however, leave me without a pic preview, before uploading, for which I am almost certain I must use AJAX.
Again, this may not even be possible, but as long as I can get the binary image data, I believe I can push it to the server with AJAX and process the image the same way I would if I were taking it from a database (note that I don't save the image files themselves using GUID and all that,I just save the binary data).
If there is an easier way to show a pic preview using the input element, that would work fine, too, of course, as the whole idea behind me trying to do this is to show a pic preview before they hit the submit form button (or at least create that illusion).
**********UPDATE***********
I do not consider this a duplicate of another question because, my real question is:
How can I get image data from an input type "file", with JavaScript/jQuery?
If I can just get the data (in the right format) back to the server, I should be able to work with it there, and then return it with AJAX (although, I am absolutely no AJAX expert).
There is, according to the research that I have done, NO WAY to get picture previews in all IE versions using only javascript (this is because getting the full file path is seen, by them, as a potential security risk). I could ask my users to add the site to the trusted sites, but you don't usually ask users to tamper with those kinds of settings (not to mention the quickest way to make your site seem suspicious to users is to ask them to directly add your site to the trusted sites list. That's like sending an email and asking for a password. "Just trust me! I'm soooo safe!" :)
Short answer: Use the jQuery form plugin, it suports AJAX-like form submits even for file uploads.
tl;dr
Thumbnail preview is popular websites is usually done by a number of steps, basically the website do these steps:
upload the RAW image
Resize and optimise the image for data storage
Generate a temporary link to that file (usually stored in a server maintained HTTP session)
Send it back to the user, to enable a 'preview'
Actually store the image after user confirms the image
A few bad solutions are:
Most of the modern browsers has options to enable script access to local files, but usually you don't ask your users to tinker with those low level settings.
Earlier Internet Explorer (ah... yes it's a shame) and ancient versions of modern browsers will expose the full file path by reading the 'value' of file input box, which you can directly generates an tag and use that value. (Now it is replaced by some c:/fakepath/... thing.)
Use Adobe Flash to mimic the file selection panel, it can properly read local files. But passing it into JavaScript is another topic...
Hope these helps. ;)
UPDATE
I actually came across a situation that requires a preview before uploading, I'd like to also put it here. As I could recall, there were no transitional versions in modern browsers that do not implement FileReader before masking the real file path, but feel free to correct me if so. This solution should caters most of the browsers, as long as they are supported by jQuery.
// 1. Listen to change event
$(':file').change(function() {
// 2. Check if it has the FileReader class
if (!this.files) {
// 2.1. Old enough to assume a real path
setPreview(this.value);
}
else {
// 2.2. Read the file content.
var reader = new FileReader();
reader.onload = function() {
setPreview(reader.result);
};
reader.readAsDataURL();
}
});
function setPreview(url) {
// Do preview things.
$('.preview').attr('src', url);
}

Generate an <IMG> tag in JavaScript with an array of bytes?

I have an SQL Server table that contains two columns - an integer ID and a varbinary(max) ImageData, which is a JPEG image. In Javascript, I have an Ajax call to get the ImageData for a particular ID and return it as a byte array. How do I generate an XHTML IMG tag that will display the image?
My thought was to use createObjectURL on the returned array, but (a) this needs to be able to run on IE 8, which doesn't seem to support the method, and (b) Firefox appears to be expecting an actual Blob type rather than an array of bytes (and the Blob() constructor doesn't appear to exist).
I do have an alternative - return the data as a Base64 string, then use the tag, but that does not work in IE8, and there may be a size limitation on other browsers (some of the images are 600K, which means that the tag could have over 1 million characters).
You are over-engineering a problem where a simpler solution already exists.
Insert the following HTML using AJAX and let the browser fetch the image itself via HTTP. Sending out image data via AJAX would require a pointless base64 encode/decode and ends up taking up more bandwith and defeats the browser cache.
<img src="imageServer.php?imageID=3224" />
Then imageServer.php (you build this or grab it somewhere) will grab the appropriate image record, spit out an image MIME type, then stream the binary data.

Force paste event to encode images in base64

Background:
I'm developing an HTML5 webapp for my company which is basically a Rich Text Editor (similar to Google Docs) that stores information in a database.
We are using CKEditor 3 as richtext editor and Jquery to acomplish this.
We've chosen Google's Chrome as the preferred browser.
Our app is currently in alpha testing period, having a group of 18 tester (which are the same ones that will use the app). These people is heterogeneous, but almost all of them of them have basic computer skills, mostly limited to MS Word and MS Excel.
.
Problem:
Most of our users still use word to elaborate the document, mainly due to its capacity of generating rich flowcharts. When they copy/paste the generated content to Chrome, images are pasted as link to a local file (auto generated by the OS, in a users/*/temp folder). This means the server can't access these files and the resulting documents (generated PDFs) don't contain the images.
.
Question
How can I force pasted images to be encoded in base64, similiar to what happens in Firefox?
.
Notes
If it's possible to "upload" to server an image referenced as src="file://c:\something", that would solve my problem as I can base64 encode that image later.
We can't switch to firefox since it doesn't fully solve our problem (if an image is "pasted" alongside with text, firefox doesn't base64 encode it) and raises other issues such as an horizontal scrollbar appearing when the text is too long to fit in the textarea.
Yes and no I believe.
It is possible to intercept the paste event and fetch the pasted image as a file, then use FileReader to read the file as a Data URI (base 64 encoded PNG).
However, Word seems to send a reference to a local file, which generates a security exception (at least on Chrome) because of a cross-domain request (http://... and file:///...). As far as I'm concerned there is no way to get the actual contents of such local files, and the contents are not sent as clipboard data itself.
If you copy a "pure" image (e.g. out of Paint), you can get the base 64 encoded data as follows: http://jsfiddle.net/pimvdb/zTAuR/. Or append the image as a base 64 encoded PNG in the div: http://jsfiddle.net/pimvdb/zTAuR/2/.
div.onpaste = function(e) {
var data = e.clipboardData.items[0].getAsFile();
var fr = new FileReader;
fr.onloadend = function() {
alert(fr.result.substring(0, 100)); // fr.result is all data
};
fr.readAsDataURL(data);
};

Image response via POST

I am getting an image as response to a post request. How do I show the same on web-browser using JavaScript. Is it possible to handle binary data using JavaScript?
You might be able to create an img-tag with a base64 src:
<img alt="Embedded Image"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
This can probably be done dynamically aswell, using .createElement and setting the src.
but then you need to convert your binary data to base64 using javascript somehow. It would be simpler if you could do that server-side, since handling binary data in javascript might cause you some trouble. That would however give you quite some overhead, but maybe thats not an issue.
Otherwise, see if this helps you:
http://www.webtoolkit.info/javascript-base64.html
Depending on the data format you might be able to use the data URI to load the image. Note to watch out for browser support.
using Gears you could turn the response into a blob and bind to an URL with the local cache server. after that, any reference to that URL will answer locally with the image data.
The most cross-browser way to do this would be to simply fetch the image URL as the response of the POST request, and then make a GET call to the image using img src="..."
No: images are always loaded from an URL

Categories

Resources