title: How to base64 encode an image in javascript
body: <p>I am developing a phonegap application and using the <code>navigator.getPicture</code> method to get the images.</p>
  
  <p>The way I am getting the picture is:</p>
  
  <pre><code>navigator.camera.getPicture(onSuccess, onFail, { quality: 50, 
  destinationType: Camera.DestinationType.FILE_URI });
  
  function onSuccess(imageURI) {
      var image = document.getElementById('myImage');
      image.src = imageURI;
  }
  </code></pre>
  
  <p>Just like the example in phonegap doc's.</p>
  
  <p>I want to be able to use the imageURI and then convert it to image data in order to upload it later. (I don't want to use phonegap's FileTransfer)</p>
  
  <p>So far I have tried both <a href="https://stackoverflow.com/questions/934012/get-image-data-in-javascript">Get image data in JavaScript?</a> and <a href="https://stackoverflow.com/questions/246801/how-can-you-encode-to-base64-using-javascript">How can you encode a string to Base64 in JavaScript?</a> </p>
  
  <p>When I try the following,</p>
  
  <pre><code>function onSuccess(imageURI) {
      getBase64Image(imageURI);
  }
  
  function getBase64Image(img) {
      // Create an empty canvas element
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
  
      // Copy the image contents to the canvas
      var ctx = canvas.getContext("2d");
     ctx.drawImage(img, 0, 0);
  
     // Get the data-URL formatted image
     // Firefox supports PNG and JPEG. You could check img.src to
     // guess the original format, but be aware the using "image/jpg"
     // will re-encode the image.
     var dataURL = canvas.toDataURL("image/png");
  
     console.log(dataURL); //here is where I get 'data:,'       
  
     return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
  }
  </code></pre>
  
  <p>And print <code>dataURL</code> before returning. I just get <code>data:,</code> as the content. </p>
  
  <p>Any ideas on what I'm doing wrong?</p>