簡體   English   中英

將捕獲的圖像傳遞給 JavaScript 函數

[英]Pass Captured Image to JavaScript Function

以下代碼段中的 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 函數以在其上運行任何邏輯?

您想在問題中附加更多信息,但如果您使用一些技術使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))

})


好的,讓我們將這個答案中的 jQuery 翻譯成您首選的原生 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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM