通过图片网址将图片转换为二进制文件。
我有以下网址: - <div class="col-md-3" style="padding-bottom: 10px; margin-bottom: 50px;">
<img class="img-responsive" src="img/other/sch1.png">
<img class="img-responsive" src="img/other/sch2.png">
<table id="contesttable" class="table" style="text-align: center;">
..........
</table>
</div>
。我想使用JavaScript将此"D:/MyProject/Image/image.jpg"
转换为二进制格式字符串。
答案 0 :(得分:5)
找到base64 encoding to binary function online,如下所示:
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);
}
要使用此功能,您可以使用binEncode
字符串作为参数调用base64
。
要将图片转换为base64
编码字符串,您可以执行以下操作:
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,/, '');
要获得base64
到binary
:
binEncode(dataInBase64);