前言
近期有个手机端html5上传图片功能的项目,在android手机上体验很好但在IOS手机上,图片有时会出现角度旋转。google后找到了解决方法,现在总结下供以后使用。
html页面
<div class="uploadImage"><input type="file"></div>
<img id="myImage">
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="js/exif.js"></script>
<script type="text/javascript" src="js/uploadImage.js"></script>
exif.js
是获取图片角度的javascript插件
uploadImage.js
$(".uploadImage input").change(function () {
selectFileImage($(this)[0]);
});
function selectFileImage(fileObj) {
var file = fileObj.files[0];
// 图片方向角
var Orientation = null;
if (file) {
var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
if (!rFilter.test(file.type)) {
alert("请选择jpeg、png格式的图片");
return;
}
//获取照片方向角属性
EXIF.getData(file, function () {
EXIF.getAllTags(this);
Orientation = EXIF.getTag(this, 'Orientation');
});
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, this.naturalWidth, this.naturalHeight);
var base64 = null;
if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
var width = this.naturalWidth;
var height = this.naturalHeight;
switch (Orientation) {
case 6://需要顺时针90度旋转
canvas.width = height;
canvas.height = width;
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(this, 0, -height);
break;
case 8://需要逆时针90度旋转
canvas.width = height;
canvas.height = width;
ctx.rotate(-90 * Math.PI / 180);
ctx.drawImage(this, -width, 0);
break;
case 3://需要180度旋转
ctx.rotate(180 * Math.PI / 180);
ctx.drawImage(this, -width, -height);
break;
}
}
base64 = canvas.toDataURL("image/png");
$("#myImage").attr("src", base64);
};
};
}
本文转载于:猿2048html5 IOS端上传图片角度旋转