8

I'm working on an offline mode for a simple application, and I'm using Indexeddb (PounchDB as a library), I need to convert an Image to Base64 or BLOB to be able to save it.

I have tried this code which works for only one Image (the Image provided) I don't know why it doesn't work for any other image:

function convertImgToBase64URL(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}
convertImgToBase64URL('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png', function(base64Img){
alert('it works');
      $('.output').find('img').attr('src', base64Img);  
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"> <img> </div>

It works fine, but only with one Image, If I try any other Image it doesn't work

4
  • Tried converting html img element to Blob , then to data URI ? Commented Apr 13, 2015 at 14:04
  • I need to convert Image URL to Base64 Commented Apr 13, 2015 at 14:07
  • Yes. See post below ; see also stackoverflow.com/questions/2390232/… Commented Apr 13, 2015 at 14:22
  • @YasserB. Thanks for the sample code, helped me for a project. 👍
    – user1908391
    Commented Oct 4, 2016 at 12:41

3 Answers 3

4

The image you're using has CORS headers

Accept-Ranges : bytes
Access-Control-Allow-Origin : * // this one
Age : 69702
Connection : keep-alive

which is why it can be modified in a canvas like that.
Other images that don't have CORS headers are subject to the same-origin policy, and can't be loaded and modified in a canvas in that way.

2
  • Thank you for your answer, So what's the possible solutions ? Commented Apr 13, 2015 at 13:53
  • You'd have to convert the image on the serverside if it's coming from an online source that doesn't support CORS.
    – adeneo
    Commented Apr 13, 2015 at 15:32
2

I need to convert Image URL to Base64

See

Understanding the HTML5 Canvas image security rules

Browser Canvas CORS Support for Cross Domain Loaded Image Manipulation

Why does canvas.toDataURL() throw a security exception?


One possible workaround would be to utilize FileReader to convert img , or other html element to a data URI of html , instead of only img src; i.e.g., try opening console at jsfiddle http://jsfiddle.net/guest271314/9mg5sf7o/ , "right-click" on data URI at console, select "Open link in new tab"

var elem = $("div")[0].outerHTML;
var blob = new Blob([elem], {
    "type": "text/html"
});
var reader = new FileReader();
reader.onload = function (evt) {
    if (evt.target.readyState === 2) {
        console.log(
                     // full data-uri
                     evt.target.result
                     // base64 portion of data-uri
                   , evt.target.result.slice(22, evt.target.result.length));
        // window.open(evt.target.result)
    };
};
reader.readAsDataURL(blob);

Another possible workaround approach would be to open image in new tab , window ; alternatively an embed , or iframe element ; utilize XMLHttpRequest to return a Blob , convert Blob to data URI

var xhr = new XMLHttpRequest();
// load `document` from `cache`
xhr.open("GET", "", true); 
xhr.responseType = "blob";
xhr.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        var reader = new FileReader();
        reader.onload = function(e) {
            // `data-uri`
            console.log(e.target.result);
        };
        reader.readAsDataURL(this.response);        
    };
};
xhr.send();
0

Do you need something like this?

http://www.w3docs.com/tools/image-base64

4
  • Yeah quite the same but I will need to convert an Image from URL to Base64 Commented Apr 13, 2015 at 14:07
  • do you need tool (with url) or you want to do it yourself(code)? Commented Apr 13, 2015 at 14:09
  • I know solution but with NodeJs.With javascript I think you can't do that Commented Apr 13, 2015 at 14:16
  • I don't care, I can use any library Commented Apr 13, 2015 at 14:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.