Simple answer is no if this needs to be done on client side. The canvas element is the only way to convert an image to bitmap data or data-uris (and even then security restriction may apply preventing this).
You can maybe get around this using Flash but of course that would require the client to have Flash installed.
Or setting up an external web service where you can upload the image and have it return the data you need.
For IE8 and lower there are no options out of the box (exCanvas gives you canvas drawing capabilities but can't provide bitmap data which is needed here). Basically, for IE8 you will need a server.
Answer from user1693593 on Stack OverflowSimple answer is no if this needs to be done on client side. The canvas element is the only way to convert an image to bitmap data or data-uris (and even then security restriction may apply preventing this).
You can maybe get around this using Flash but of course that would require the client to have Flash installed.
Or setting up an external web service where you can upload the image and have it return the data you need.
For IE8 and lower there are no options out of the box (exCanvas gives you canvas drawing capabilities but can't provide bitmap data which is needed here). Basically, for IE8 you will need a server.
There are some answers given here
How can you encode a string to Base64 in JavaScript?
have you tried any of them?
javascript - Convert an image to base64 without using HTML5 Canvas - Stack Overflow
javascript - Convert image from url to Base64 - Stack Overflow
How to get base64 image data without call canvas toDataURL? - Stack Overflow
javascript - Convert image to base64 without server - Stack Overflow
A canvas doesn't hold (for example) a jpg. A jpg is lossy. When you load it into canvas, it gets 'unpacked'. When you use a built-in canvas method to output a dataURL, it will first re-compress the raw canvas-data (32 bit per pixel inc alpha) to the (lossy-level depending on internal paramaters) format you have chosen as output, then convert that data to base64.
What I'm trying to say here is, that canvas would not produce a true base64 encoding of the original file; instead it would produce a base64 encoding of the canvas-content (one of canvas' supported output formats). In yet other words: you are not base64-encoding the original binary.
That being said and explained.. there is more.. you might stumble on cross-site security problems inside the browser (assuming you want to be able to feed any URL).
Thus the solution, solving both problems above (also employed by the website you referenced), is to pass the URL (or the bare text entered or file uploaded) to the server where the server gets the image (data) and base64 encodes it (the actual original binary) and passes it back to the client(browser) (for example via AJAX/JSON/etc.).
However, you also say that you are "working solely in javascript without an HTML page". That's kind of vague. In my answer above I assumed a browser (as host) anyway (otherwise you would have mentioned node.js (or something like that) and you'd have gotten error messages about document). If however you do use node, then there is probably something available to download the binary contents from an URL (which you then pass through your javascript implementation of base64 (which again is probably already available in node.js)).
The site at most likely use serverside technology (ASP, PHP, etc) to download the image and get it's base64 encoding. You cannot reverse engineer something that is executed on the serverside.
If you use clientside technology (like JavaScript) you may run into "Cross-Origin Resource Sharing"-problems.
The code you have supplied works as it should and you can see this by executing the following 2 calls. Please note that Wikipedia allows resource sharing while jshell.net (JSFiddle) does not - so check you console log for the "Cross-Origin Resource Sharing"-error message.
// Works fine:
convertImgToBase64("http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png", function(data){alert(data)});
// Does not work due to "Cross-Origin Resource Sharing"
convertImgToBase64("http://jsfiddle.net/img/logo.png", function(data){alert(data)});
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to @Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
- The MDN reference of
HTMLCanvasElement.toDataURL(). - And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by @HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
A way to avoid the main HTML to be affected is to create an off-screen canvas that is kept out of the DOM-tree.
This will provide a bitmap buffer and native compiled code to encode the image data. It is straight forward to do:
function imageToDataUri(img, width, height) {
// create an off-screen canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// set its dimension to target size
canvas.width = width;
canvas.height = height;
// draw source image into the off-screen canvas:
ctx.drawImage(img, 0, 0, width, height);
// encode image to data-uri with base64 version of compressed image
return canvas.toDataURL();
}
If you want to produce a different format than PNG (default) just specify the type like this:
return canvas.toDataURL('image/jpeg', quality); // quality = [0.0, 1.0]
Worth to note that CORS restrictions applies to toDataURL().
If your app is giving only base64 encoded images (I assume they are data-uri's with base64 data?) then you need to "load" the image first:
var img = new Image;
img.onload = resizeImage;
img.src = originalDataUriHere;
function resizeImage() {
var newDataUri = imageToDataUri(this, targetWidth, targetHeight);
// continue from here...
}
If the source is pure base-64 string simply add a header to it to make it a data-uri:
function base64ToDataUri(base64) {
return 'data:image/png;base64,' + base64;
}
Just replace the image/png part with the type the base64 string represents (ie. make it an optional argument).
Ken's answer is the right answer, but his code doesn't work. I made some adjustments on it and it now works perfectly. To resize a Data URI :
// Takes a data URI and returns the Data URI corresponding to the resized image at the wanted size.
function resizedataURL(datas, wantedWidth, wantedHeight)
{
// We create an image to receive the Data URI
var img = document.createElement('img');
// When the event "onload" is triggered we can resize the image.
img.onload = function()
{
// We create a canvas and get its context.
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// We set the dimensions at the wanted size.
canvas.width = wantedWidth;
canvas.height = wantedHeight;
// We resize the image with the canvas method drawImage();
ctx.drawImage(this, 0, 0, wantedWidth, wantedHeight);
var dataURI = canvas.toDataURL();
/////////////////////////////////////////
// Use and treat your Data URI here !! //
/////////////////////////////////////////
};
// We put the Data URI in the image's src attribute
img.src = datas;
}
// Use it like that : resizedataURL('yourDataURIHere', 50, 50);