1function getBase64Image(src, callback, outputFormat) {
2 const img = new Image();
3 img.crossOrigin = 'Anonymous';
4 img.onload = () => {
5 const canvas = document.createElement('canvas');
6 const ctx = canvas.getContext('2d');
7 let dataURL;
8 canvas.height = img.naturalHeight;
9 canvas.width = img.naturalWidth;
10 ctx.drawImage(img, 0, 0);
11 dataURL = canvas.toDataURL(outputFormat);
12 callback(dataURL);
13 };
14
15 img.src = src;
16 if (img.complete || img.complete === undefined) {
17 img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
18 img.src = src;
19 }
20 }
1function encodeImageFileAsURL(element) {
2 var file = element.files[0];
3 var reader = new FileReader();
4 reader.onloadend = function() {
5 console.log('RESULT', reader.result)
6 }
7 reader.readAsDataURL(file);
8}
9<input type="file" onchange="encodeImageFileAsURL(this)" />
1function toDataURL(url, callback) {
2 var xhr = new XMLHttpRequest();
3 xhr.onload = function() {
4 var reader = new FileReader();
5 reader.onloadend = function() {
6 callback(reader.result);
7 }
8 reader.readAsDataURL(xhr.response);
9 };
10 xhr.open('GET', url);
11 xhr.responseType = 'blob';
12 xhr.send();
13}
14
15toDataURL('https://cdn.discordapp.com/attachments/571092147801948204/784586541146177606/6f32c864-985a-481d-8d8e-bd1f14ab9951.png', function(dataUrl) {
16 console.log('RESULT:', dataUrl)
17})
1<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
2<div id="imgTest"></div>
3<script type='text/javascript'>
4 function encodeImageFileAsURL() {
5
6 var filesSelected = document.getElementById("inputFileToLoad").files;
7 if (filesSelected.length > 0) {
8 var fileToLoad = filesSelected[0];
9
10 var fileReader = new FileReader();
11
12 fileReader.onload = function(fileLoadedEvent) {
13 var srcData = fileLoadedEvent.target.result; // <--- data: base64
14
15 var newImage = document.createElement('img');
16 newImage.src = srcData;
17
18 document.getElementById("imgTest").innerHTML = newImage.outerHTML;
19 alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
20 console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
21 }
22 fileReader.readAsDataURL(fileToLoad);
23 }
24 }
25</script>