用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; }
【IOS中html5上傳圖片偏向成績處理辦法】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!