Search code examples
javascriptcrossrider

JavaScript serialize image (icon)


I am building an extension in CrossRider. I need to save images/icons, which I have their url, in a database. They are tiny images and won't be a problem in the database. I might have something like that accessible to background.js:

<img src="http://something.com/icon.ico" alt="icon">

And I want to be able to serialize that image to the database (it's a key/value database) and deserialize that later and display it. Something like HTML5's FileReader.readAsDataUrl() will be good, but I can't use that method because it seems too tied to forms.

Thanks ([-|).


Solution

  • Base64 conversion to display the image doesn't seem to be necessary:

    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://g.etfv.co/http://www.google.com', true);
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
        var icon_blob = xhr.response; //That can be saved to db
        var fr = new FileReader();
        fr.onload = function(e) {
            document.getElementById('myicon').src = fr.result; //Display saved icon
        };
        fr.readAsDataURL(icon_blob);
    };
    xhr.send(null);
    

    Here's it on JSFiddle.