JavaScript:如何将jpeg图像标记转换为原始二进制文件?

时间:2017-06-24 11:13:53

标签: javascript image binary base64

这是我尝试的代码片段;

<img src= "hello.jpg">
var binary = atob(base64.replace(/\s/g, ''));
console.log(binary);

但它没有按预期工作。 如何将标记转换为二进制文件

有没有其他方法可以将图片标记转换为二进制文件?

1 个答案:

答案 0 :(得分:0)

您可以使用HTML5画布或使用FileReader()这里是两个示例:

&#13;
&#13;
from bs4 import BeautifulSoup
from selenium import webdriver

browser = webdriver.PhantomJS()
browser.get('https://www.flightradar24.com/56.16,-49.51/3')

soup = BeautifulSoup(browser.page_source, "html.parser")
result = soup.find_all("span", {"id": "menuPlanesValue"})

for item in result:
    print(item.text)

browser.quit()
&#13;
function convertImgToDataURLviaCanvas(url, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
    canvas = null;
  };
  img.src = url;
}

function convertFileToDataURLviaFileReader(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

$('#img2b64').submit(function(event) {
  var imageUrl = $(this).find('[name=url]').val();
  var convertType = $(this).find('[name=convertType]').val();
  var convertFunction = convertType === 'FileReader' ?
    convertFileToDataURLviaFileReader :
    convertImgToDataURLviaCanvas;

  convertFunction(imageUrl, function(base64Img) {
    $('.output')
      .find('.textbox')
      .val(base64Img)
      .end()
      .find('.link')
      .attr('href', base64Img)
      .text(base64Img)
      .end()
      .find('.img')
      .attr('src', base64Img)
      .end()
      .find('.size')
      .text(base64Img.length)
      .end()
      .find('.convertType')
      .text(convertType)
      .end()
      .show()
  });

  event.preventDefault();
});
&#13;
@import url('//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css');
body {
  padding: 20px;
}
&#13;
&#13;
&#13;