可以使用javascript或phonegap以二进制模式从远程服务器读取图像
is possible to read image from remote server using in binary mode using javascript or phonegap?
实际上,在我的一个项目中,我需要从远程服务器读取图像,并将其作为二进制文件存储在本地数据库中,以便稍后在应用程序中使用。有什么简单的方法可以让我做到这一点吗?这是我唯一坚持的事情,完成应用程序很重要。请帮忙!!提前谢谢。
它在HTML5/ES5环境中相当简单(实际上除了InternetExplorer9-之外的所有东西);
首先,您需要将图像的二进制内容下载到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
相关文章:
- 使用JSP从服务器检索和显示图像
- 将处理后的图像上传到服务器
- 使用FormData上传AJAX图像;t在服务器端显示图像
- 从安卓设备将图像上传到服务器时,文件扩展名错误
- 将Adobe创意编辑的图像上传到我的服务器,而不是他们的创意云
- 使用服务器上的HTML/js在网页上显示图像
- 将处理后的图像发送到服务器进行保存
- 从Web服务器下载图像按钮单击使用JavaScript
- 从Div创建图像,并使用Javascript和ASP.net将其保存到服务器
- 在服务器上通过jQueryAjax上传加载的图像时出现问题
- 如何通过ajax php将图像上传到服务器本地目录,其中html表单haven't任何传统的提交按钮
- 如何将图像上传到带有 CSS 过滤器的服务器
- 如何使用 HTML 图像请求将数据发送到服务器,或返回数据作为响应
- 铯:使用自己的OpenStreetMap服务器.:“无法获取图像磁贴”错误
- 如何在 HTML 中的按钮单击上更改图像(IMG URL 每次来自服务器)
- 动态图像加载是否会减少服务器过载
- 在将图像保存到服务器之前检查图像大小
- 如何从服务器响应中显示phonegap中的图像
- Node.js服务器:图像上传/损坏问题
- JavaScript使用服务器图像的FileReader