JavaScript serialize image (icon)

◇◆丶佛笑我妖孽 提交于 2020-01-03 02:22:37

问题


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 ([-|).


回答1:


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.




回答2:


One solution might be to draw the image on a canvas and then use .toDataURL(). See How to get image bytes string (base64) in html5, jquery, javascript? for an example.

You can also fetch binary data via AJAX. Newer browsers can use XMLHttpRequest to retrieve an ArrayBuffer (essentially a byte array). See MDN: Sending and Receiving Binary Data for more information on that. As mentioned in that article, binary data can also be received by setting .overrideMimeType('text\/plain; charset=x-user-defined') on the AJAX request. The latter technique works in older browsers and with jQuery's AJAX functions. However, any type of AJAX will require you to get around the same-origin policy (e.g., by creating a backend web service that fetches/proxies the images and adds the HTTP header Access-Control-Allow-Origin: *).

Binary AJAX example: http://jsfiddle.net/te7L4/



来源:https://stackoverflow.com/questions/20693563/javascript-serialize-image-icon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!