1. 关于图片自动旋转原因
在使用PS或者其他软件旋转图片时,图片旋转了,但Orientation不会改变,由于我们使用的图片预览器能够预处理图片,使其看起来与旋转后一致,但上传图片时,浏览器并不会预处理。所以导致图片旋转。
EXIF中,包含一个Orientation参数,用来记录拍摄照片时的方向,其中1是正常。
2. 解决旋转问题,需引入exif.js文件 下载链接 http://code.ciaoca.com/javascript/exif-js/
顺带对图片进行压缩上传
// 1.图片旋转及图片压缩 fileObj指input上传的图片文件,callback会将base64图片传入,自行处理显示
function compress(fileObj,callback) {
if(typeof (FileReader) === 'undefined'){
console.log("当前浏览器内核不支持base64图片压缩")
// getObjectURL()方法见下方,无法压缩图片时直接将fileObj处理为网页可显示的图片
callback(getObjectURL(fileObj))
}else{
try{
var reader = new FileReader();
reader.onload = function (e) {
var image = new Image();
image.onload = function () {
var Orientation
EXIF.getData(image, function() {
Orientation = EXIF.getTag(this, 'Orientation');
});
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
squareW = this.width, //定义画布大小,也就是图片压缩之后的像素
squareH = this.height;
if(Orientation == 3) {
canvas.width = squareW;
canvas.height = squareH;
context.rotate(Math.PI);
context.drawImage(image, 0, 0, -squareW, -squareH);
} else if(Orientation == 8) {
canvas.width = squareH;
canvas.height = squareW;
context.rotate(Math.PI * 3 / 2);
context.drawImage(image, 0, 0, -squareW, squareH);
} else if(Orientation == 6) {
canvas.width = squareH;
canvas.height = squareW;
context.rotate(Math.PI / 2);
context.drawImage(image, 0, 0, squareW, -squareH);
} else {
canvas.width = squareW;
canvas.height = squareH;
context.drawImage(image, 0, 0, squareW, squareH);
}
var data = canvas.toDataURL('image/jpeg')
callback(data)
}
image.src = e.target.result
};
reader.readAsDataURL(fileObj);
}catch (e) {
console.log('压缩失败!')
callback(getObjectURL(fileObj))
}
}
}
// getObjectURL() 将file类型转化为可显示的图片
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url;
}
//base64转file dataurl是base64地址,filename是图片的名字
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//base64转blob dataurl是base64地址
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}