4

Convert image into binary by image url.

I have URL Like :- "D:/MyProject/Image/image.jpg". I want to convert this "image.jpg" into binary format string using JavaScript.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Nilesh Pathade
  • 71
  • 1
  • 1
  • 6

1 Answers1

6

Found a base64 encoding to binary function online that goes something like this:

function binEncode(data) {
    var binArray = []
    var datEncode = "";

    for (i=0; i < data.length; i++) {
        binArray.push(data[i].charCodeAt(0).toString(2)); 
    } 
    for (j=0; j < binArray.length; j++) {
        var pad = padding_left(binArray[j], '0', 8);
        datEncode += pad + ' '; 
    }
    function padding_left(s, c, n) { if (! s || ! c || s.length >= n) {
        return s;
    }
    var max = (n - s.length)/c.length;
    for (var i = 0; i < max; i++) {
        s = c + s; } return s;
    }
    console.log(binArray);
}

To use the function you would call binEncode with a base64 string as parameter.

To convert your image into a base64 encoded string, you could do:

var myCanvas = $('<canvas/>');
var myImageSrc = myCanvas.attr('src', 'http://www.google.com/imgres?imgurl=http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg&imgrefurl=http://www.gettyimages.co.uk/&h=280&w=562&tbnid=Gd_Suvvlpe2UbM:&docid=tUvJ118IkhewgM&ei=kZjVVcXQO8np-QGkjoSYAQ&tbm=isch&ved=0CDIQMygAMABqFQoTCIXdpbqnt8cCFcl0PgodJAcBEw');
myCanvas.attr('src', myImageSrc);
var dataInBase64 = $(myCanvas)[0].toDataURL('image/png').replace(/data\:image\/png;base64,/, '');

To get the base64 to binary:

binEncode(dataInBase64);
Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29