Convert Image to Binary Data or String in Javascri

2019-06-01 11:02发布

问题:

I am working on uploading image file to TWITPIC using XMLHttp Request on a Chrome Extension . I need to send the image as payload. Is there a way to do this ? I found this link Convert an image into binary data in javascript But that works on image tags. i need a way to specify image file path and upload image to TWITPIC.

I came to know about FileReader API with HTML 5. Is there any way to work using that??. It should work on a local file.

Does Chrome Extension support FileReader API without running a localhost server ??

回答1:

I found the answer myself. Chrome Extensions does support FileReader API of HTML 5. So just the code below works simple.

  var reader = new FileReader();
  reader.readAsDataURL(f);


回答2:

You can use this to get the binary data of an image using XMLHTTPRequests, I used it recently for a similar purpose:

var dataToBinary = function(data){
    var data_string = "";
    for(var i=0; i<data.length; i++){
        data_string += String.fromCharCode(data[i].charCodeAt(0) & 0xff);
    }
    return data_string;
};

$.ajax("http://some.site.com/myImage.jpg", {
    success: function(data){
        binary = dataToBinary(data);
        //or: 'binary = data', dataToBinary might not be needed
    },
    mimeType: "text/plain; charset=x-user-defined"
});

And the binary data is stored in the binary variable.