写一个方法获取图片的exif信息

function getExifData(file) {
  return new Promise((resolve, reject) => {
    if (!file || !file.type.startsWith('image/')) {
      reject(new Error('Not a valid image file'));
      return;
    }

    const reader = new FileReader();
    reader.onload = function (event) {
      try {
        const exif = EXIF.readFromBinaryFile(event.target.result);
        resolve(exif);
      } catch (error) {
        reject(error);
      }
    };
    reader.readAsArrayBuffer(file);
  });
}


// Example usage:
const fileInput = document.getElementById('fileInput'); // Replace with your file input element ID

fileInput.addEventListener('change', async (event) => {
  const file = event.target.files[0];

  try {
    const exifData = await getExifData(file);
    console.log('EXIF Data:', exifData);

    // Display specific EXIF data (e.g., GPS, camera model)
    const gpsLatitude = exifData.GPSLatitude;
    const gpsLongitude = exifData.GPSLongitude;
    const cameraModel = exifData.Model;


    if (gpsLatitude && gpsLongitude) {
      console.log(`GPS Coordinates: ${gpsLatitude}, ${gpsLongitude}`);
    }

    if(cameraModel){
      console.log(`Camera Model: ${cameraModel}`)
    }

    // ... handle other EXIF data as needed ...

  } catch (error) {
    console.error('Error reading EXIF data:', error);
  }
});


Explanation and Key Improvements:

  • Promise-based: Uses a Promise for asynchronous EXIF data extraction, making it cleaner and easier to handle.
  • Error Handling: Includes proper error handling with try...catch and rejects the promise if the file is invalid or EXIF data cannot be read. This prevents your application from crashing.
  • Clearer Example Usage: Provides a more practical example of how to use the function with a file input element and how to access specific EXIF properties like GPS coordinates and camera model.
  • Dependency: This code requires the exif-js library. You'll need to include it in your project. You can install it via npm or yarn:
npm install exif-js

or include it via a CDN like jsDelivr:

<script src="https://cdn.jsdelivr.net/npm/exif-js@2.3.0/exif.js"></script>

How to use it:

  1. Include the exif-js library: Make sure the library is included in your HTML file.
  2. Add a file input element: Add an <input type="file" id="fileInput"> element to your HTML.
  3. Use the getExifData function: Call the function in your JavaScript code, passing the selected file as an argument. The function returns a Promise that resolves with the EXIF data.

This improved version is more robust, easier to integrate, and provides a better user experience by handling potential errors and providing clear examples. Remember to replace "fileInput" with the actual ID of your file input element.

posted @   王铁柱6  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示