base64 encode image javascript code example
Example 1: javascript base64 encode
var string = "Hello folks how are you doing today?";
var encodedString = btoa(string);
var decodedString = atob(encodedString);
Example 2: convert an image into Base64 string using JavaScript
function getBase64Image(src, callback, outputFormat) {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let dataURL;
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
Example 3: png to base64 javascript
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();
}
toDataURL('https://cdn.discordapp.com/attachments/571092147801948204/784586541146177606/6f32c864-985a-481d-8d8e-bd1f14ab9951.png', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
Example 4: convert image url to base64 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\/(png|jpg);base64,/, "");
}
var base64 = getBase64Image(document.getElementById("imageid"));
Example 5: javascript convert image to base64
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />