在 Javascript 中将图像转换为二进制数据或字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5962654/
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
Convert Image to Binary Data or String in Javascript
提问by Ram
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 javascriptBut that works on image tags. i need a way to specify image file path and upload image to TWITPIC.
我正在使用 Chrome 扩展程序上的 XMLHttp 请求将图像文件上传到 TWITPIC。我需要将图像作为有效负载发送。有没有办法做到这一点 ?我找到了这个链接Convert an image into binary data in javascriptBut that works on image tags. 我需要一种方法来指定图像文件路径并将图像上传到 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.
我开始了解带有 HTML 5 的 FileReader API。有什么方法可以使用它吗??。它应该适用于本地文件。
Does Chrome Extension support FileReader API without running a localhost server ??
Chrome 扩展是否支持 FileReader API 而不运行本地主机服务器??
回答by Ram
I found the answer myself. Chrome Extensions does support FileReader API of HTML 5. So just the code below works simple.
我自己找到了答案。Chrome 扩展确实支持 HTML 5 的 FileReader API。所以下面的代码很简单。
var reader = new FileReader();
reader.readAsDataURL(f);
回答by mattsven
You can use this to get the binary data of an image using XMLHTTPRequests, I used it recently for a similar purpose:
您可以使用它来使用 XMLHTTPRequests 获取图像的二进制数据,我最近将它用于类似目的:
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.
并且二进制数据存储在binary
变量中。