如何解决IOS中html5上传图片方向问题?


本文摘自PHP中文网,作者零下一度,侵删。

这篇文章主要介绍了IOS中html5上传图片方向问题解决方法的相关资料,需要的朋友可以参考下

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

//此方法为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);

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

// @param {string} img 图片的base64

// @param {int} dir exif获取的方向信息

// @param {function} next 回调方法,返回校正方向后的base64

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);

  //返回校正图片

  next(canvas.toDataURL("image/jpeg",.8));

 }

 image.src=img;

}

以上就是如何解决IOS中html5上传图片方向问题?的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

html5实现上传图片预览效果代码

移动端h5中百度地图的click事件的介绍(代码示例)

浅谈bootstrap中如何上传图片

利用js+html5实现图片上传预览效果(实例)

iOS页面边框是显示不出来怎么办?border-image实例教程

如何解决iOS中html5上传图片方向问题?

html5/css3 经典案例-无插件拖拽上传图片(一)

html5和原生app如何进行交互?

html+css如何实现自定义图片上传按钮

html5上传图片 移动端、pc端的通用代码分享

更多相关阅读请进入《iOS》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...