可以使用javascript或phonegap以二进制模式从远程服务器读取图像

is possible to read image from remote server using in binary mode using javascript or phonegap?

本文关键字:服务器 图像 读取 模式 二进制 javascript phonegap 可以使      更新时间:2023-09-26

实际上,在我的一个项目中,我需要从远程服务器读取图像,并将其作为二进制文件存储在本地数据库中,以便稍后在应用程序中使用。有什么简单的方法可以让我做到这一点吗?这是我唯一坚持的事情,完成应用程序很重要。请帮忙!!提前谢谢。

它在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