IOS中html5上传图片方向问题解决方法

王氏家族王者

王氏家族王者

2016-02-19 09:03

下面图老师小编要跟大家分享IOS中html5上传图片方向问题解决方法,简单的过程中其实暗藏玄机,还是要细心学习,喜欢还请记得收藏哦!

用html5编写图片裁切上传,在iphone手机上可能会遇到图片方向错误问题,在此把解决方法和大家分享一下,
用到了html5的 FileReader和Canvas,如果还没有接触的同学,先了解一下其方法。

(本文来源于图老师网站,更多请访问https://m.tulaoshi.com/bianchengyuyan/)
 //此方法为file input元素的change事件 function change(){  var file = this.files[0];  var orientation;  //EXIF js 可以读取图片的元信息 https://github.com/exif-js/exif-js  EXIF.getData(file,function(){orientation=EXIF.getTag(this,'Orientation');  });  var reader = new FileReader();  reader.onload = function(e) {  getImgData(this.result,orientation,function(data){  //这里可以使用校正后的图片data了 });   }  reader.readAsDataURL(file);}
// @param {string} img 图片的base64// @param {int} dir exif获取的方向信息// @param {function} next 回调方法,返回校正方向后的base64function 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);  //返回校正图片  next(canvas.toDataURL("image/jpeg",.8)); } image.src=img;}
展开更多 50%)
分享

猜你喜欢

IOS中html5上传图片方向问题解决方法

编程语言 网络编程
IOS中html5上传图片方向问题解决方法

夏季装修问题解决方法

装修 夏季 家具
夏季装修问题解决方法

s8lol主宰符文怎么配

英雄联盟 网络游戏
s8lol主宰符文怎么配

Windows Vista中QQ蓝屏问题解决方法

电脑入门
Windows Vista中QQ蓝屏问题解决方法

《模拟城市5》交通问题解决方法

电脑网络
《模拟城市5》交通问题解决方法

lol偷钱流符文搭配推荐

英雄联盟 网络游戏
lol偷钱流符文搭配推荐

ios8.4定位不准发烫问题解决方法

iphone iPhone 5s iPhone 6 iphone刷机
ios8.4定位不准发烫问题解决方法

《侠盗猎车手5》各种问题解决方法攻略

电脑网络
《侠盗猎车手5》各种问题解决方法攻略

lolAD刺客新符文搭配推荐

英雄联盟
lolAD刺客新符文搭配推荐

Android读取用户号码,手机串号,SIM卡序列号的实现代码

Android读取用户号码,手机串号,SIM卡序列号的实现代码

简单小函数让Excel统计出勤情况更直观

简单小函数让Excel统计出勤情况更直观
下拉加载更多内容 ↓