有没有一种特殊的方法可以将 phone 相机中的图像加载到 Android Firefox 的 img 中

Is there a special way to load an image from a phone's camera into img for Android Firefox

我正在尝试将 phone 相机中的图像加载到图像标签中。除了 Android 上的 Firefox,它在任何地方都很好用。 Firefox 版本是 83.1.0 以下是产生问题的简单 JavaScript 和 HTML。我想要做的就是使用相机拍照并将其加载到 img 标签中进行显示。在 Chrome 甚至三星笨拙的互联网浏览器中运行良好。只是不在 Firefox 中。图像不显示。 我做错了什么?

window.onload = function() {
let imgInput = document.querySelector('#imageInput');
   
   imgInput.addEventListener('change',function(event) {
      var files = this.files;
      var fr = new FileReader();
   
      fr.onload = function () {
         document.getElementById('image').src = fr.result;
      }

      fr.readAsDataURL(files[0]);
   });
};

...

<input id="imageInput" type="file" accept="image/*" capture="camera">
<img id="image" style="height: 300px; width: auto;"/>

你好,欢迎来到 SO :) 我对你的代码有点困惑,因为你提到“从相机加载图像”,但你也在加载文件。

更新答案:使用 WebRTC

如@evilpie 所述,ImageCapture 目前在 Firefox 中不受支持。但是,MDN 还有另一篇关于 using WebRTC to take still pictures.

的好文章

这是文章中描述的 takepicture 函数。它使用 video element 接收 WebRTC 流,然后在 Canvas 中呈现该元素的内容。然后将内容转换为数据 URL 以在另一个组件中显示。

  function takepicture() {
    var context = canvas.getContext('2d');
    if (width && height) {
      canvas.width = width;
      canvas.height = height;
      context.drawImage(video, 0, 0, width, height);
    
      var data = canvas.toDataURL('image/png');
      photo.setAttribute('src', data);
    } else {
      clearphoto();
    }
  }

旧答案(不起作用:Firefox 不支持 ImageCapture

MDN 网站有一个 nice example exactly for loading an image from the camera. The example works across all the browsers (a demo is available here):

var takePhotoButton = document.querySelector('button#takePhoto');
var canvas = document.querySelector('canvas');

takePhotoButton.onclick = takePhoto;

function takePhoto() {
  imageCapture.takePhoto().then(function(blob) {
    console.log('Took photo:', blob);
    img.classList.remove('hidden');
    img.src = URL.createObjectURL(blob);
  }).catch(function(error) {
    console.log('takePhoto() error: ', error);
  });
}

演示的完整 JS 代码是 available on GitHub

我认为可能存在两个潜在问题:

  • 您的 Android 版本的 Firefox 已过时。有一个问题报告显示通过 <input type="file"> 的图像捕获在旧版本中可能会被破坏:https://github.com/mozilla-mobile/fenix/issues/8711
  • 数据的用法:URL 而不是 blob:URL。 Android 的 Firefox 似乎对数据有相当低的限制:URL 长度。高分辨率图像可能太大。 URL.createObjectURL 创建一个 blob URL。

我在 Android Nightly 的 Firefox 上成功测试了以下实现:

<input type=file accept="image/*" id="imageInput">
<img id="image">
<script>
var imgInput = document.querySelector("#imageInput");
imgInput.addEventListener('change',function(event) {
  var file = event.target.files[0];
  var url = URL.createObjectURL(file);
  document.getElementById('image').src = url;
});
</script>