Converting an image to binary in javascript using base64

强颜欢笑 提交于 2019-12-23 19:19:02

问题


I have to convert an image to binary for storing it through IPFS and retrieve it again as a viewable image.

I should do this with javascript code. Does any body have any clear example of how to do this? Will Base64 help me?

Thanks in advance


回答1:


Use File Reader:

/******************for base 64 *****************************/
function uploadFile(inputElement) {
  var file = inputElement.files[0];
  var reader = new FileReader();
  reader.onloadend = function() {
    console.log('Encoded Base 64 File String:', reader.result);
    
    /******************* for Binary ***********************/
    var data=(reader.result).split(',')[1];
     var binaryBlob = atob(data);
     console.log('Encoded Binary File String:', binaryBlob);
  }
  reader.readAsDataURL(file);
}
<input type="file" onchange="uploadFile(this)" />


来源:https://stackoverflow.com/questions/51533584/converting-an-image-to-binary-in-javascript-using-base64

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