JavaScript - 如何在网络摄像头中使用 EXIF 数据拍照?

JavaScript - How to take a picture in webcam with EXIF data?

我目前在网页上使用网络摄像头(不是本机相机)在用户的手机上拍照phone。像这样:

var video: HTMLVideoElement;
...
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, width, height);
var jpegData = canvas.toDataURL('image/jpeg', compression);

这样我就可以成功的从网络摄像头生成一个JPEG图像数据,并显示在网页上了。

但是,我发现EXIF数据丢失了。 根据 this

Canvas.drawImage() will ignore all EXIF metadata in images, including the Orientation. This behavior is especially troublesome on iOS devices. You should detect the Orientation yourself and use rotate() to make it right.

我希望 JPEG 图像包含 EXIF GPS 数据。有没有一种简单的方法可以在此过程中包含相机 EXIF 数据?

谢谢!

首先,根据我目前的发现,在 canvas 上下文绘制期间无法包含 exif 数据。

其次,还有一种解决方法,就是从原始JPEG文件中提取exif数据,然后在canvas上下文绘制后,将提取的exif数据放回新绘制的JPEG文件中.

它很乱而且有点老套,但现在这是解决方法。 谢谢!

很遗憾,无法从 canvas 中提取 exif。

不过,如果您可以访问 jpeg,则可以从中提取 exif。为此,我建议 exifr 而不是广受欢迎的 exif-js,因为 exif-js 已经有两年没有维护了,并且仍然存在重大错误(n 未定义)。

使用 exifr,您可以解析所有内容

exifr.parse('./myimage.jpg').then(output => {
  console.log('Camera:', output.Make, output.Model))
})

或者只是几个标签

let output = await exifr.parse(file, ['ISO', 'Orientation', 'LensModel'])

在 Pixel 3 上测试过 - 可以。请注意 - 有时它不适用于某些桌面 web-cameras。您将需要 exif-js 从示例中获取 EXIF 对象。

  const stream = await navigator.mediaDevices.getUserMedia({ video : true });
  const track = stream.getVideoTracks()[0];
  let imageCapture = new ImageCapture(track);
  imageCapture.takePhoto().then((blob) => {
      const newFile = new File([blob], "MyJPEG.jpg", { type: "image/jpeg" });
      EXIF.getData(newFile, function () {
          const make = EXIF.getAllTags(newFile);
          console.log("All data", make);
     });
  });