当前位置: 移动技术网 > IT编程>开发语言>JavaScript > iOS拍照后图片自动旋转90度的解决方法

iOS拍照后图片自动旋转90度的解决方法

2018年07月24日  | 移动技术网IT编程  | 我要评论
 
<!-- 解决图片旋转 -->
<script src="/libs/jquery/jquery.min.js"></script>
<script src="/libs/exif/exif.js"></script>
 
// html
<input type="file" accept="image/*;capture=camera">
 
 
// 此方法是旋转图片;
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 maxSide = Math.max(drawWidth, drawHeight);
if (maxSide > 1024) {
var minSide = Math.min(drawWidth, drawHeight);
minSide = minSide / maxSide * 1024;
maxSide = 1024;
if (drawWidth > drawHeight) {
drawWidth = maxSide;
drawHeight = minSide;
} else {
drawWidth = minSide;
drawHeight = maxSide;
}
}
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);
// 判断图片  类型 (可增加判断的类型  此处只判断了 jpeg 和png)
 var imgtype = img.includes('image/png') ? "image/png" : "image/jpeg";
//返回校正图片
next(canvas.toDataURL(imgtype, .8));
}
image.src = img;
};
 
 
 
$("input[type = file]").change(function () {
var _this = $(this);
var file = this.files[0];
// console.log(file)
var orientation;
var site = location.protocol + '//' + location.host + '/api/wx_user/upload_img/base_upload';
//EXIF js 可以读取图片的元信息 https://github.com/exif-js/exif-js
if (!/image.(png|jpg|jpeg|bmp)/.test(file.type)) {
alert('选择的文件类型不是图片');
return;
}
EXIF.getData(file, function () {
orientation = EXIF.getTag(this, 'Orientation');
});
var reader = new FileReader();
reader.onload = function (e) {
getImgData(this.result, orientation, function (data) {
//这里可以使用校正后的图片data了
// 此处ajax用于 base64路径转换成正常路径 
$.ajax({
url: site,
data: { str: data, type: file.type },
type: 'post',
dataType: 'json',
success: function (i) {
_this.siblings("img").attr('src', i.img_url);
}
})
});
}
reader.readAsDataURL(file);
});

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网