title: Convert jpg/png to base64 using javascript and cordova 2.2.0
body: <h2>Application I'm working on</h2>
  
  <p>I'm working on a Cordova 2.2.0 application that's used in a slow-(or none)internet environment.<br>
  It gains data from a CMS system.
  this data (JSON) is stored locally on the mobile device using <a href="http://cordova.apache.org/docs/en/2.2.0/cordova_file_file.md.html#File" rel="nofollow noreferrer">Cordova's filesystem</a>. This provides data for moments this application doesn't have access to the internet.</p>
  
  <h2>Problem</h2>
  
  <p>Data storage and recovery using Cordova's filesystem is working fine. The data stored to the filesystem is in JSON. After parsing this JSON it is converted to HTML. Problem is that this gives me IMG tags with an external source like this:
  </p>
  
  <pre><code>&lt;img src="http://www.SomeUrl.com/Images/SomeImage.jpg" id="someImage" /&gt;
  </code></pre>
  
  <p>I want to load this Image and convert it to base64 using JavaScript. If this is possible, I will be able to write it to the local filesystem for offline use. Something like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>var imageFromURLToBase64(imageURL){ 
      "use strict";
  
      var image = doSomethingWithUrl(imageURL),
          base64 = "";
  
      //CONVERT IMAGE TO BASE64 HERE
      return base64;
  };
  
  var imageUrl = $("#someImage").attr("src"),
      base64 = imageFromURLToBase64(imageUrl);
  //Store base64 image to local filesystem
  </code></pre>
  
  <p>help is highly appreciated!<br>
  <em>P.S. cross origin requests are enabled on this server!</em></p>
  
  <h2>Alternatives</h2>
  
  <p>If there's some better alternative for caching images out there, I'd be happy to hear about it.
  I've read a little bit about HTML cache manifest <a href="https://stackoverflow.com/questions/10924628/cache-external-image-in-a-phonegap-app">here</a>, but I don't know if this suits my problem.</p>
  
  <h3>Duplicate question</h3>
  
  <p>There are more people dealing with this problem, answers to those questions didn't solve my problem. <a href="https://stackoverflow.com/questions/10924628/cache-external-image-in-a-phonegap-app?lq=1">this answer</a> or <a href="https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript">this answer</a> don't tell me what's the best way to cache my images for a phonegap application. I wondered if there where better ways to encode images to base64, but my real question is: "What's the best way to store/cache my images for a phonegap application?"</p>