将捕获的图像传递给JavaScript函数

问题描述 投票:-3回答:2

以下代码段中的input元素将浏览按钮放在HTML页面中。当从Android设备访问该页面时,它会显示一个浏览按钮,用于打开我的相机并选择捕获的图像。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<input type="file" accept="image/*" capture="camera" />
</body>
</html>

我的问题是,如何将选定的图像传递给JavaScript函数来运行任何逻辑?

javascript html5
2个回答
1
投票

您想在问题中添加更多信息,但如果您使用某些技巧让input保留您的图像源uri,那么您可以通过以下方式获取值:

<input id="image-input" type="file" accept="image/*" capture="camera" />

// js:
const input = document.querySelector("#image-input")
input.addEventListener('change', _ => {
  // if you want to read the image content
  const reader = new window.FileReader()
  // input.files[0] is the first image, you may want to directly use it instead of read it
  reader.readAsDataURL(input.files[0])
  // reader.result is the image content in base64 format
  reader.addEventListener('load', _ => console.log(reader.result))

})



0
投票

好吧,让我们将jQuery从this answer翻译成您首选的原生JavaScript。

function readURL(input) {

  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      // $('#blah').attr('src', e.target.result); becomes...
      document.getElementById("blah").setAttribute("src", e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

//$("#imgInp").change(function() {
  //readURL(this);
//}); becomes...
document.getElementById("imgInp").onchange = function() {
  readURL(this)
}
© www.soinside.com 2019 - 2024. All rights reserved.