实际上,在我的一个项目中,我需要从远程服务器读取图像并将其作为二进制文件存储在本地数据库中,以便稍后在应用程序中使用。那么有什么简单的方法可以做到这一点吗?这是我唯一坚持的事情,完成申请很重要。请帮忙 !!提前致谢。
最佳答案
它在 HTML5/ES5 环境中相当简单(几乎除了 Internet Explorer 9- 之外的所有环境);
首先需要将图片的二进制内容下载到一个arraybuffer中,然后将其转换为base64 datauri,其实就是一个字符串。这可以存储在浏览器的 localStorage、indexedDb 或 webSQL 中,甚至是 cookie(虽然效率不高);稍后您只需将此 datauri 设置为要显示的图像 src。
<script>
function showImage(imgAddress) {
var img = document.createElement("img");
document.body.appendChild(img);
getImageAsBase64(imgAddress, function (base64data) { img.src = base64data; });
};
function getImageAsBase64(imgAddress, onready) {
//get from online or from whatever string store
var req = new XMLHttpRequest();
req.open("GET", imgAddress, true);
req.responseType = 'arraybuffer'; //this won't work with sync requests in FF
req.onload = function () { onready(arrayBufferToDataUri(req.response)); };
req.send(null);
};
function arrayBufferToDataUri(arrayBuffer) {
var base64 = '',
encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
bytes = new Uint8Array(arrayBuffer), byteLength = bytes.byteLength,
byteRemainder = byteLength % 3, mainLength = byteLength - byteRemainder,
a, b, c, d, chunk;
for (var i = 0; i < mainLength; i = i + 3) {
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
a = (chunk & 16515072) >> 18; b = (chunk & 258048) >> 12;
c = (chunk & 4032) >> 6; d = chunk & 63;
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
}
if (byteRemainder == 1) {
chunk = bytes[mainLength];
a = (chunk & 252) >> 2;
b = (chunk & 3) << 4;
base64 += encodings[a] + encodings[b] + '==';
} else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];
a = (chunk & 16128) >> 8;
b = (chunk & 1008) >> 4;
c = (chunk & 15) << 2;
base64 += encodings[a] + encodings[b] + encodings[c] + '=';
}
return "data:image/jpeg;base64," + base64;
}
</script>
我从这个优秀的帖子中借用了base64转换例程:http://jsperf.com/encoding-xhr-image-data/5
关于javascript - 可以使用javascript或phonegap以二进制模式从远程服务器读取图像吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9840957/