Can I read an image from a remote server using binary mode using javascript or a phone call?

In fact, in one of my projects I need to read images from a remote server and store them in a local database as binary files for use in the application later. so is there a simple way i can do this? this is the only thing I'm stuck in, and it’s important to fill out an application. please help !! Thanks in advance.

+5
source share
1 answer

It’s pretty simple in HTML5 / ES5 (almost everything except Internet Explorer 9);

First you need to load the binary content of the image into a buffer array, and then convert it to base64 datauri, which is actually a string. This can be saved in browsers localStorage, indexedDb or webSQL or even in a cookie (but not too efficient); Later, you simply set this datauri as the src image to display.

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

I took the base64 conversion routine from this beautiful post: http://jsperf.com/encoding-xhr-image-data/5

+12
source

All Articles