javascript 如何使用javascript将图像转换为二进制格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32113907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How convert image into binary format using javascript
提问by Nilesh Pathade
Convert image into binary by image url.
通过图像 url 将图像转换为二进制。
I have URL Like :- "D:/MyProject/Image/image.jpg"
. I want to convert this "image.jpg"
into binary format string using JavaScript.
我有 URL Like :- "D:/MyProject/Image/image.jpg"
。我想"image.jpg"
使用 JavaScript将其转换为二进制格式的字符串。
回答by Moishe Lipsker
Found a base64 encoding to binary function online that goes something like this:
在网上找到了一个 base64 编码的二进制函数,它是这样的:
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.
要使用该函数,您将binEncode
使用base64
字符串作为参数调用。
To convert your image into a base64
encoded string, you could do:
要将图像转换为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,/, '');
To get the base64
to binary
:
要获取base64
到binary
:
binEncode(dataInBase64);