1

我正在 CrossRider 中构建一个扩展。我需要将图像/图标(我有它们的 url)保存在数据库中。它们是微小的图像,不会成为数据库中的问题。我可能有类似的东西可以访问background.js

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

而且我希望能够将该图像序列化到数据库(它是一个键/值数据库)并稍后反序列化并显示它。像 HTML5 这样的东西FileReader.readAsDataUrl()会很好,但我不能使用那种方法,因为它似乎太依赖于表单。

谢谢([-|)。

4

2 回答 2

2

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.

于 2013-12-21T22:02:40.907 回答
1

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/

于 2013-12-19T23:34:35.737 回答