前言:摄像头、手机拍摄等拍摄的图片是有方向的,在上传过程中,我们通过Canvas修正图片的方向,以便解决页面显示的图片方向和拍摄的方向一致性问题。
读取图片方向的工具:Exif.js
话不多说,接下来直接码代码了
$('.file').on('change', function selectFileImage(e) {
获取上传的文件
var files = e.target.files === undefined ? (e.target && e.target.value ? [{
name: e.target.value.replace(/^.+\\/, '')
}] : []) : e.target.files
//图片方向角 added by lzk
var Orientation = null;
不再派发事件
e.stopPropagation()
判断是否选择了文件
if (files.length === 0) {
return
}
获取第一个文件
var file = files[0],
filetype=file.type;
var dur = 0;
验证格式
if (files[0].type != 'image/png' && files[0].type != 'image/jpeg' && files[0].type != 'image/jpe' && files[0].type != 'image/gif') {
alert("提示:仅支持jpg、gif、png三种格式");
return;
}
EXIF.getData(file, function () {
dur = EXIF.getTag(this, 'Orientation');
// var URL = URL || webkitURL;
文件读取IO初始化
var reader = new FileReader();
图片加载完成
reader.onload = function (re) {
getImgData(this.result, dur, function (data) {
//data即为修正后的图片的Base64
c();
});
}
设置将要读取的图片
reader.readAsDataURL(file)
});
});
{string} img 图片的base64
{int} dir exif获取的方向信息
{function} next 回调方法,返回校正方向后的base64
function getImgData(img, dir, next) {
var image = new Image();
image.onload = function () {
var degree = 0, drawWidth, drawHeight, width, height;
drawWidth = this.naturalWidth;
drawHeight = this.naturalHeight;
var canvas = document.createElement('canvas');
canvas.width = width = drawWidth;
canvas.height = height = drawHeight;
var context = canvas.getContext('2d');
//判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
switch (dir) {
//iphone横屏拍摄,此时home键在左侧
case 3:
degree = 180;
drawWidth = -width;
drawHeight = -height;
break;
//iphone竖屏拍摄,此时home键在下方(正常拿手机的方向)
case 6:
canvas.width = height;
canvas.height = width;
degree = 90;
drawWidth = width;
drawHeight = -height;
break;
//iphone竖屏拍摄,此时home键在上方
case 8:
canvas.width = height;
canvas.height = width;
degree = 270;
drawWidth = -width;
drawHeight = height;
break;
}
//使用canvas旋转校正
context.rotate(degree * Math.PI / 180);
context.drawImage(this, 0, 0, drawWidth, drawHeight);
//返回校正图片
next(canvas.toDataURL());
}
image.src = img;
}