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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:52:35  来源:igfitidea点击:

How convert image into binary format using javascript

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 binEncodewith a base64string as parameter.

要使用该函数,您将binEncode使用base64字符串作为参数调用。

To convert your image into a base64encoded 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 base64to binary:

要获取base64binary

binEncode(dataInBase64);