0

I trying to take image as a file input from the user and the display it as a base64 encoded string. Here's my code

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript – Convert Image to Base64 String</title>
</head>
<body>

    <input type="file" name="upload" id="file" accept="image/*">
    <br>
    <br>    
    <button type="button" onclick="showResult()">Show Source</button>
    <div id="image-source">Image Source :</div>
    <br>
    <div>Data URL:</div>
    <div id="result"></div>
    <script type="text/javascript">
        function toDataURL(src, callback) {
            var xhttp = new XMLHttpRequest();

            xhttp.onload = function() {
                var fileReader = new FileReader();
                fileReader.onloadend = function() {
                    callback(fileReader.result);
                }
                fileReader.readAsDataURL(xhttp.response);
            };

            xhttp.responseType = 'blob';
            xhttp.open('GET', src, true);
            xhttp.send();
        }



        showResult(){
            var x = document.getElementById("file").value;
            document.getElementById("image-source").innerHTML = x;
            toDataURL(x, function(dataURL) {
            // do something with dataURL
            document.getElementById('result').innerHTML = dataURL;
        });
        }


    </script>

</body>
</html>

Do I need to store the source of the image seperately to encode it ? Is there a simpler way to encode a user uploaded image ??

Kriti Singh
  • 35
  • 1
  • 7
  • Why do you want to mess with base64!? A waste of CPU, 33% extra storage, and headaches for usually no benefit. – Brad Feb 27 '20 at 06:00
  • Hi @Brad actually I am trying to send the image to vision api, the api accepts either base-encoded files or gcloud bucket file links or image url (public), I want the results dynamically so I thought base encoding would be best. If know any better method I'd be more than glad to use it . – Kriti Singh Feb 27 '20 at 06:04
  • Wow, what sort of API won't accept binary image data? That'd be far better. – Brad Feb 27 '20 at 06:04
  • According to the documentation https://cloud.google.com/vision/docs/request#providing_the_image , these are only listed ways. I am new to programming, any guidance would be helpful. – Kriti Singh Feb 27 '20 at 06:11
  • Do you want to convert an image a user has selected (using the file input element) to a base64 dataURL on the client side? I'm not understanding why the code is using XMLHttpRequest and what its purpose is. – traktor Feb 27 '20 at 06:35
  • @traktor53 I went through this article https://bytenota.com/javascript-convert-image-to-base64-string/ and it used FileReaderApproach ( i was just trying ways to encode the image ) . And yes I want to convert an image a user has selected (using the file input element) to a base64 dataURL on the client side – Kriti Singh Feb 27 '20 at 07:01

1 Answers1

4

Here's a simple example converting the first image selected using the file browse button. File reading occurs on the client side after an image has been selected. File reading is asynchronous so I've promisified the file reading function:

"use strict";

const fileDataURL = file => new Promise((resolve,reject) => {
    let fr = new FileReader();
    fr.onload = () => resolve( fr.result);
    fr.onerror = reject;
    fr.readAsDataURL( file)
});

function showResult(file) {
    fileDataURL( file)
    .then( data => (document.getElementById("result").textContent = data))
    .catch(err => console.log(err));
}
#result {
   width: 80%;
   font-family: monospace;
   overflow-wrap: break-word;
}
<p>
<input type="file" onchange="showResult( this.files[0]);" accept="image/*">
<div>Data URL:</div>
<div id="result"></div>
traktor
  • 17,588
  • 4
  • 32
  • 53