Convert local image to base64 string in Javascript

Mathomatic picture Mathomatic · Sep 29, 2015 · Viewed 36k times · Source

I'm trying to convert a local image to Base64 string. I am not using any HTML and simply need javascript which references the image's path within the code.

For instance, converting:

C:\Users\Work\Desktop\TestImage.jpg

into

/9j/4AAQSkZJRgABAQEASABIAAD/4QBKRXhpZgAASUkqAAgAAAADABoBBQABAAAAMgAAABsBBQABAAAAOgAAACgBAwABAAAAAgAAAAAAAAAAVOoqgJaYAABU6iqAlpgA/+IMWElDQ19QUk9GSUxFAAEBAAAMSExpbm8CEAAAbW50clJHQiBYWVogB84AAgAJAAYAMQAAYWNzcE1TRlQAAAAASUVDIH.....etc...

There are many posts like this but they all seem to utilize HTML in some way, in order to identify the file path. I'm hoping I can write a defined filepath within the javascript.

I tried this to no avail:

function convertImgToBase64()
{
    var canvas = document.createElement('CANVAS');
    img = document.createElement('img'),
    img.src = C:\Users\Work\Desktop\TestImage.jpg;
    img.onload = function()
    {
        canvas.height = img.height;
        canvas.width = img.width;
        var dataURL = canvas.toDataURL('image/png');
        alert(dataURL);
        canvas = null; 
    };
}

One example has the following html and javascript, but I'm hoping this can be consolidated together. Thanks for your support

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>


<input type='file' id="asd" />
<br>
<img id="img" src="//placehold.it/1x1/" />
<div id="base"></div>
</body>
</html>

Javascript:

function el(id){return document.getElementById(id);} // Get elem by ID

function readImage() {
    if ( this.files && this.files[0] ) {
        var FR= new FileReader();
        FR.onload = function(e) {
             el("img").src = e.target.result;
             el("base").innerHTML = e.target.result;
        };       
        FR.readAsDataURL( this.files[0] );
    }
}

el("asd").addEventListener("change", readImage, false);\

Its demo found here

Answer

guest271314 picture guest271314 · Sep 29, 2015

Try utilizing XMLHttpRequest() set responseType to Blob , use FileReader() at XMLHttpRequest onload event to read response as data URI

var xhr = new XMLHttpRequest();       
    xhr.open("GET", "/path/to/local/image/file", true); 
    xhr.responseType = "blob";
    xhr.onload = function (e) {
            console.log(this.response);
            var reader = new FileReader();
            reader.onload = function(event) {
               var res = event.target.result;
               console.log(res)
            }
            var file = this.response;
            reader.readAsDataURL(file)
    };
    xhr.send()