Here is the example that shows converting an image file to base 64 string code. It can be done by the canvas method.
HTML5 provides the canvas tag that is used to draw a canvas.
For converting an image file to base 64 string you need to create a canvas and load your image into that. After this, you can use the toDataURL() method to get the string in base64 format.
Code:
function encodeImage(src, callback) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
callback(canvas.toDataURL());
}
img.src = src;
}
You have to call the above function from your code after uploading the image file. Canvas can be used in almost all the browsers.
0 Comment(s)