-3

The input element in the following snippet puts a browse button in an HTML page. When the page is accessed from an Android device, it shows a browse button which opens my camera and selects the captured image.

<!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>

My problem is, how can I pass the selected image to a JavaScript function to run any logic on it?

Ahmed Tawila
  • 789
  • 2
  • 13
  • 19

2 Answers2

1

You'd like to append more info to your question, but if you have use some techniques to make the input hold your image source uri, then you can get the value via:

<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))

})


sunfy
  • 1,867
  • 11
  • 17
0

Ok let's translate the jQuery from this answer to your preferred native 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)
}
gilbert-v
  • 1,036
  • 1
  • 9
  • 20