html
<input class="xfile" name="file_img" type="file" accept="image/*" multiple type="hidden">
<canvas id="myCanvas" style="position: absolute;left:-200%;top:-200%;"></canvas>
js
//上传图片请求
function preview(input) {
console.log("上传图片接口");
console.log(input);
if (input.files && input.files[0]) {
$.ajax({
})
} else {
alert("请上传png格式图片");
return;
}
};
//base64格式图片 转为Blob
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 File([u8arr], 'a.jpg', {
type: 'image/jpg'
});
}
//图片处理函数
function fileFun(input, Orientation, file) {
console.log(Orientation);
var reader = new FileReader();
var image = new Image();
reader.readAsDataURL(file);
reader.onload = function (ev) {
image.src = ev.target.result;
image.onload = function () {
var imgWidth = this.width,
imgHeight = this.height; //获取图片宽高
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
canvas.width = imgWidth;
canvas.height = imgHeight;
if (Orientation && Orientation != 1) {
switch (Orientation) {
case 6: // 需要顺时针(向左)旋转90度
canvas.width = imgHeight;
canvas.height = imgWidth;
ctx.rotate(Math.PI / 2);
ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
break;
case 3: // 旋转180度
ctx.rotate(Math.PI);
// ctx.rotate(Math.PI);
ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
break;
case 8: // 需要逆时针(向右)旋转-90度
canvas.width = imgHeight;
canvas.height = imgWidth;
ctx.rotate(3 * Math.PI / 2);
// ctx.rotate(3 * Math.PI / 2);
ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
break;
}
} else {
ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
}
var dataurl = canvas.toDataURL("image/jpeg", 0.8); //canvase 转为base64
var blob = dataURLtoBlob(dataurl); //base64转为blog
preview(input, blob);
}
}
}
$('[name=file_img]').change(function (e) {
console.log("图片change");
var that = this;
var file = e.currentTarget.files[0];
// 方法2
EXIF.getData(file, function () {
var Orientation = EXIF.getTag(file, 'Orientation');
console.log("EXIF======Orientation");
console.log(Orientation);
if (Orientation && Orientation != 1) { //图片角度不正确
console.log("需处理图片");
fileFun(that, Orientation, file);
} else {
//不需处理直接上传
console.log("不需处理直接上传");
preview(file);
}
});
});