参考:https://www.cnblogs.com/Joe-and-Joan/p/10957818.html
<input class="myimg" accept="image/*" type="file" />
引入: <script type="text/javascript" src="../js/exif.js" ></script>
$(".myimg").change(function(e){
var file = this.files[0];//获取用户选择的文件
fixImageOrientation(file).then(file2 => {
console.log("新文件=="+file2);
console.log("新文件=="+window.URL.createObjectURL(file2));
//图片预览
//document.querySelector('.img_common').src = window.URL.createObjectURL(file2);
//上传文件到后台(我是上传到七牛云)
var formData = new FormData();
formData.append('file',file2);
formData.append('token',qiniuToken);
netupfile(formData);
})
});
/**
* 修正图片旋转角度问题
* @param {file} 原图片
* @return {Promise} resolved promise 返回纠正后的新图片
*/
function fixImageOrientation (file) {
return new Promise((resolve, reject) => {
// 获取图片
const img = new Image();
img.src = window.URL.createObjectURL(file);
img.onerror = () => resolve(file);
img.onload = () => {
// 获取图片元数据(EXIF 变量是引入的 exif-js 库暴露的全局变量)
EXIF.getData(img, function() {
// 获取图片旋转标志位
var orientation = EXIF.getTag(this, "Orientation");
//console.log("获取图片旋转标志位=="+orientation);
// 根据旋转角度,在画布上对图片进行旋转
if (orientation === 3 || orientation === 6 || orientation === 8) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
switch (orientation) {
case 3: // 旋转180°
canvas.width = img.width;
canvas.height = img.height;
ctx.rotate((180 * Math.PI) / 180);
ctx.drawImage(img, -img.width, -img.height, img.width, img.height);
break;
case 6: // 旋转90°
canvas.width = img.height;
canvas.height = img.width;
ctx.rotate((90 * Math.PI) / 180);
ctx.drawImage(img, 0, -img.height, img.width, img.height);
break;
case 8: // 旋转-90°
canvas.width = img.height;
canvas.height = img.width;
ctx.rotate((-90 * Math.PI) / 180);
ctx.drawImage(img, -img.width, 0, img.width, img.height);
break;
}
// 返回新图片
canvas.toBlob(file => resolve(file), 'image/jpeg', 0.92)
} else {
return resolve(file);
}
});
};
});
}
//上传图片
function netupfile(formData){
jQuery.support.cors = true;
$.ajax({
type:"post",
url:img_url,
data:formData,
dataType: 'json',
processData: false,
contentType: false,
async:true,
cache:false,
processData: false,//不转化为信息
crossDomain: true == !(document.all),
success: function(res) {
console.log("上传结果=="+JSON.stringify(res));
},
error:function(res) {
}
});
}