某些模块需要使用到手机拍照的功能,一般手机拍照后可以正常上传至服务器,但是有少数手机会存在问题,那就是拍照后图片会发生旋转90度、-90度甚至180度,下面是使用js处理该问题的方法。
使用前确保已经引入exif.js。点击跳转至下载y页面 var file=document.getElementById('imagefile').files[0];//获取文件流 correcctImageOrientation(file);//调用方法,将图片修正。
// 纠正图片旋转方向 function correcctImageOrientation(file) { var Orientation = null; if (file) { var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式 if (!rFilter.test(file.type)) { return; } // 获取照片方向角属性,用户旋转控制 EXIF.getData(file, function() { EXIF.getAllTags(this); Orientation = EXIF.getTag(this, 'Orientation');//获取图片旋转弧度 }); var oReader = new FileReader(); oReader.onload = function(e) { var image = new Image(); image.src = e.target.result; image.onload = function() { var expectWidth = this.naturalWidth; var expectHeight = this.naturalHeight; // 压缩图片。最大宽800,最大高1200 if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) { expectWidth = 800; expectHeight = expectWidth * this.naturalHeight / this.naturalWidth; } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) { expectHeight = 1200; expectWidth = expectHeight * this.naturalWidth / this.naturalHeight; } // 绘制canvas var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); canvas.width = expectWidth; canvas.height = expectHeight; ctx.drawImage(this, 0, 0, expectWidth, expectHeight); // base64 字符串 var base64 = null; if(Orientation != "" && Orientation != 1){ switch(Orientation){ case 6: // 需要顺时针(向左)90度旋转 rotateImg(this,'left',canvas); break; case 8: //需要逆时针(向右)90度旋转 rotateImg(this,'right',canvas); break; case 3: //需要180度旋转 rotateImg(this,'right',canvas);//转两次 rotateImg(this,'right',canvas); break; } } base64 = canvas.toDataURL("image/jpeg", 0.8); // 用base64回显 var myImageList = $('.myImage'); var len = $('.myImage').length; $('#myImg').attr("src", base64);//将处理好的图片流放到对应的元素中显示 }; }; oReader.readAsDataURL(file); } } // 对图片旋转处理 function rotateImg(img, direction,canvas) { // 最小与最大旋转方向,图片旋转4次后回到原方向 var min_step = 0; var max_step = 3; if (img == null)return; // img的高度和宽度不能在img元素隐藏后获取,否则会出错 var height = img.height; var width = img.width; var step = 2; if (step == null) { step = min_step; } if (direction == 'right') { step++; // 旋转到原位置,即超过最大值 step > max_step && (step = min_step); } else { step--; step < min_step && (step = max_step); } // 旋转角度以弧度值为参数 var degree = step * 90 * Math.PI / 180; var ctx = canvas.getContext('2d'); switch (step) { case 0: canvas.width = width; canvas.height = height; ctx.drawImage(img, 0, 0); break; case 1: canvas.width = height; canvas.height = width; ctx.rotate(degree); ctx.drawImage(img, 0, -height); break; case 2: canvas.width = width; canvas.height = height; ctx.rotate(degree); ctx.drawImage(img, -width, -height); break; case 3: canvas.width = height; canvas.height = width; ctx.rotate(degree); ctx.drawImage(img, -width, 0); break; } }
本文来自投稿,不代表微擎百科立场,如若转载,请注明出处:https://www.w7.wiki/code/2471.html