Exif.js 读取图像的元数据
在最近的活动中,遇到了用户上传图片时图片方向偏转的问题。针对这个问题,通过google得到exif.js可以获取照片的元数据,例如:拍照方向、相机设备型号、拍摄时间、ISO 感光度、GPS 地理位置等数据。EXIF 数据主要来自拍摄的照片,多用于移动端开发,PC 端也会用到,兼容性良好,兼容主流浏览器,IE10 以下不支持。
Exif.js使用方法
EXIF.getData(document.getElementById('imgElement'), function(){
EXIF.getAllTags(this);
EXIF.getTag(this, 'Orientation');
});
- API 方法
名称 | 说明 |
---|---|
EXIF.getData(img, callback) | 获取图像的数据 |
EXIF.getTag(img, tag) | 获取图像的某个数据 |
EXIF.getAllTags(img) | 获取图像的全部数据,值以对象的方式返回 |
EXIF.pretty(img) | 获取图像的全部数据,值以字符串的方式返回 |
2. Tiff相关
名称 | 说明 |
---|---|
ImageWidth | 图像宽度 |
ImageHeight | 图像高度 |
BitsPerSample | 比特采样率 |
Compression | 压缩方法 |
PhotometricInterpretation | 像素合成 |
Orientation | 拍摄方向 |
SamplesPerPixel | 像素数 |
PlanarConfiguration | 数据排列 |
YCbCrSubSampling | 色相抽样比率 |
YCbCrPositioning | 色相配置 |
XResolution | X方向分辨率 |
YResolution | Y方向分辨率 |
ResolutionUnit | 分辨率单位 |
StripOffsets | 图像资料位置 |
RowsPerStrip | 每带行数 |
StripByteCounts | 每压缩带比特数 |
JPEGInterchangeFormat | JPEG SOI 偏移量 |
JPEGInterchangeFormatLength | JPEG 比特数 |
TransferFunction | 转移功能 |
WhitePoint | 白点色度 |
PrimaryChromaticities | 主要色度 |
YCbCrCoefficients | 颜色空间转换矩阵系数 |
ReferenceBlackWhite | 黑白参照值 |
DateTime | 日期和时间 |
ImageDescription | 图像描述、来源 |
Make | 生产者 |
Model | 型号 |
Software | 软件 |
Artist | 作者 |
Copyright | 版权信息 |
主要用到的就是以上的部分。
Exif.js代码部分
EXIF.getData(e.target.files['0'],
function() {
EXIF.getAllTags(this);
Orientation = EXIF.getTag(this, 'Orientation');
});
var file = e.target.files.item(0);
var freader = new FileReader();
freader.readAsDataURL(file);
freader.onload = function(e) {
var i = new Image();
i.src = e.target.result;
i.onload = function() {
if (i.width >= 560 && i.height >= 720) {
if (i.width / i.hehight > 7 / 9) {
i.width = i.width / i.height * 720;
i.height = 720;
if (i.width < 560) {
i.height = i.height / i.width * 560;
i.width = 560;
}
} else {
i.height = i.height / i.width * 560;
i.width = 560;
if (i.height < 720) {
i.width = i.width / i.height * 720;
i.height = 720;
}
}
} else {
$(".problem-activity").addClass("pic-bigger");
$(".problem").css("display", "block");
}
var dataURL = "";
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
if (Orientation != "") {
switch (Orientation) {
case 6:
canvas.width = i.height;
canvas.height = i.width;
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(i, 0, -i.height, i.width, i.height);
break;
case 8:
canvas.width = i.height;
canvas.height = i.width;
ctx.rotate(270 * Math.PI / 180);
ctx.drawImage(i, -i.width, 0, i.width, i.height);
break;
case 3:
//需要180度旋转
canvas.width = i.width;
canvas.height = i.height;
ctx.rotate(180 * Math.PI / 180);
ctx.drawImage(i, -i.width, -i.height, i.width, i.height);
break;
default:
canvas.width = i.width;
canvas.height = i.height;
ctx.drawImage(i, 0, 0, i.width, i.height);
break;
}
}
}
以上代码对用户上传的图片先进行大小限制后,再对有偏移的图片进行旋转,使图片恢复正常视角。
以上为exif.js的使用介绍。