title: Convert local image to base64 string in Javascript
body: <p>I'm trying to convert a <strong>local</strong> image to Base64 <strong>string</strong>. I am not using any HTML and simply need javascript which references the image's path within the code.</p>
  
  <p>For instance, converting:     </p>
  
  <pre><code>C:\Users\Work\Desktop\TestImage.jpg
  </code></pre>
  
  <p>into</p>
  
  <pre><code>/9j/4AAQSkZJRgABAQEASABIAAD/4QBKRXhpZgAASUkqAAgAAAADABoBBQABAAAAMgAAABsBBQABAAAAOgAAACgBAwABAAAAAgAAAAAAAAAAVOoqgJaYAABU6iqAlpgA/+IMWElDQ19QUk9GSUxFAAEBAAAMSExpbm8CEAAAbW50clJHQiBYWVogB84AAgAJAAYAMQAAYWNzcE1TRlQAAAAASUVDIH.....etc...
  </code></pre>
  
  <p>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 <strong>within</strong> the javascript.</p>
  
  <p>I tried this to no avail:</p>
  
  <pre><code>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; 
      };
  }
  </code></pre>
  
  <p>One example has the following html and javascript, but I'm hoping this can be consolidated together. Thanks for your support</p>
  
  <p><strong>HTML:</strong></p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;meta charset=utf-8 /&gt;
  &lt;title&gt;JS Bin&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  
  &lt;input type='file' id="asd" /&gt;
  &lt;br&gt;
  &lt;img id="img" src="//placehold.it/1x1/" /&gt;
  &lt;div id="base"&gt;&lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>Javascript:</strong></p>
  
  <pre><code>function el(id){return document.getElementById(id);} // Get elem by ID
  
  function readImage() {
      if ( this.files &amp;&amp; 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);\
  </code></pre>
  
  <p><a href="http://jsbin.com/ayazin/453/edit?html,js,output" rel="noreferrer">Its demo found here</a></p>