写一个方法获取图片的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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了