Sha*_*nki 5 javascript html5 cordova
实际上在我的一个项目中,我需要从远程服务器读取图像并将其作为二进制文件存储在本地数据库中以便以后在应用程序中使用 那么有什么简单的方法可以做到这一点吗?这是我唯一坚持的事情,完成申请很重要.请帮忙 !!提前致谢.
Pet*_*tai 12
它在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>
Run Code Online (Sandbox Code Playgroud)
我从这篇文章中借用了base64转换例程:http://jsperf.com/encoding-xhr-image-data/5