使用Exif.js读取图片EXIF数据返回空值与undefined问题求助
解决方案
1. 修正window.onload的赋值方式
你当前代码里window.onload = getExif(img);会立即执行getExif函数,而非等待页面加载完成后触发。window.onload需要接收函数引用,而非函数执行结果。
修改示例:
const img = document.getElementById("someImage"); // 改为函数引用,确保页面加载完成后再执行 window.onload = () => getExif(img); function getExif(file) { try { EXIF.getData(file, function () { var make = EXIF.getTag(this, "Make"); var model = EXIF.getTag(this, "Model"); var allMetaData = EXIF.pretty(this); console.log(JSON.stringify(allMetaData, null, 2)); console.log(make, model); if (!allMetaData) { console.error("EXIF data has not been found or incomplete."); } }); } catch (error) { console.error("Error reading EXIF data", error); } }
2. 确保图片完全加载
即使window.onload触发,图片可能仍未完成加载。建议直接监听图片自身的onload事件:
const img = document.getElementById("someImage"); // 监听图片加载完成事件 img.onload = function() { getExif(this); }; // 处理图片已缓存的情况,手动触发加载事件 if (img.complete) { img.onload(); } function getExif(file) { try { EXIF.getData(file, function () { var make = EXIF.getTag(this, "Make"); var model = EXIF.getTag(this, "Model"); var allMetaData = EXIF.pretty(this); console.log(JSON.stringify(allMetaData, null, 2)); console.log(make, model); if (!allMetaData) { console.error("EXIF data has not been found or incomplete."); } }); } catch (error) { console.error("Error reading EXIF data", error); } }
3. 处理跨域问题(针对外部图片)
如果图片来自外部域名,需设置图片的crossOrigin属性,否则Exif.js会因浏览器同源策略限制无法读取数据:
const img = document.getElementById("someImage"); img.crossOrigin = "anonymous"; // 添加跨域配置 img.onload = function() { getExif(this); }; if (img.complete) { img.onload(); } // 后续getExif函数保持不变
4. 验证图片本身的EXIF数据
确认测试用图确实包含EXIF元数据——可以通过系统自带工具(Windows:属性→详细信息;Mac:显示简介)检查,避免使用无EXIF的截图或压缩后丢失数据的图片。
5. 扩展内资源的路径问题
如果图片是扩展本地资源,需使用chrome.runtime.getURL获取正确的绝对路径:
const img = document.getElementById("someImage"); img.src = chrome.runtime.getURL("images/test.jpg"); // 替换为你的实际图片路径 img.crossOrigin = "anonymous"; img.onload = function() { getExif(this); };
内容的提问来源于stack exchange,提问作者user26540420
相关产品推荐
相关产品推荐

