Convert Image to Binary Data or String in Javascript

徘徊边缘 提交于 2019-12-22 11:26:41

问题


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.



来源:https://stackoverflow.com/questions/5962654/convert-image-to-binary-data-or-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!