How to Convert an Image into Base64 String Using JavaScript

How can I convert an image into Base64 string using JavaScript?

You can use the HTML5 <canvas> for it:

Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).

Convert image from url to Base64

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\/(png|jpg);base64,/, "");
}

var base64 = getBase64Image(document.getElementById("imageid"));

This method requires the canvas element, which is perfectly supported.

  • The MDN reference of HTMLCanvasElement.toDataURL().
  • And the official W3C documentation.

converting image to base64 - image becomes invisible

I am assuming u need the key baseImageCorrect and encoding key at the same level.

Use this instead:

const EncodedImage = JSON.stringify({
fileBase64: {baseImageCorrect, encoding: 'base64' },
});

Trying to convert image to Base64 string in javascript and trying to convert to byte array in c#, gives Invalid character in base64 string error

When using the readAsDataURL method, the result contains a Data URL which is prefixed with the data: schema.

From MDN web docs:

Note: The file's result results in a string that cannot be directly decoded as Base64. To retrieve only the Base64 encoded string, you must remove data:*/*;base64, from the string.

So just like Jonathon Chase commented, you would have to remove the schema's prefix either in your Javascript code, before sending it down to your C# web service or in your web service.

How can I convert an image into Base64 string from an image source?

I think you want to do this https://jsfiddle.net/samet19/yv9a4op8/

function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("output").src = newImage.src;
}
fileReader.readAsDataURL(fileToLoad);
}
}

Difficulty converting image to Base64

I found a solution. Hopefully someone will use this in future.

So, the request-promise library had some default encoding. To remove it, I added 'encoding' property to options object and set it to null. As in below

    const options = {
method: 'GET',
url: `${url('sites')}/${siteId}/views/${viewId}/image`,
headers: {
'X-Tableau-Auth': token
},
encoding: null
};

How to convert file to base64 in JavaScript?

Modern ES6 way (async/await)

const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});

async function Main() {
const file = document.querySelector('#myfile').files[0];
console.log(await toBase64(file));
}

Main();

UPD:

If you want to catch errors

async function Main() {
const file = document.querySelector('#myfile').files[0];
try {
const result = await toBase64(file);
return result
} catch(error) {
console.error(error);
return;
}
//...
}

Image convert to Base64

function readFile() {

if (!this.files || !this.files[0]) return;

const FR = new FileReader();

FR.addEventListener("load", function(evt) {
document.querySelector("#img").src = evt.target.result;
document.querySelector("#b64").textContent = evt.target.result;
});

FR.readAsDataURL(this.files[0]);

}

document.querySelector("#inp").addEventListener("change", readFile);
<input id="inp" type="file">
<p id="b64"></p>
<img id="img" height="150">


Related Topics



Leave a reply



Submit