IOS中html5上传图片方向问题解决方法
程序员文章站
2023-11-18 13:52:16
用html5编写图片裁切上传,在iphone手机上可能会遇到图片方向错误问题,在此把解决方法和大家分享一下,
用到了html5的 filereader和canvas,如果...
用html5编写图片裁切上传,在iphone手机上可能会遇到图片方向错误问题,在此把解决方法和大家分享一下,
用到了html5的 filereader和canvas,如果还没有接触的同学,先了解一下其方法。
//此方法为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 回调方法,返回校正方向后的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; }