写一个方法获取图片的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:
- Include the
exif-js
library: Make sure the library is included in your HTML file. - Add a file input element: Add an
<input type="file" id="fileInput">
element to your HTML. - 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.