问题产生的原因:
iOS上拍摄/储存的图片会附带属性orientation(方向角)。orientation为6时,图片会被旋转。
可使用 exif.js 插件获取图片角度值,再利用 megapix-image.js 插件修复被旋转的角度。
以下是从项目中复制过来的一些代码,可进行参考
<input id="face" type="file" accept="image/*"> <label for="face"> <img id="faceImg"/> </label>
$("#face").change(function () { toBase64(this, ‘#faceImg‘, function(url) { //url:压缩/旋转处理后的base64图片 }) })
1 //本地图片转base64 2 function toBase64(eleInput, eleImg, callback){ 3 var file = eleInput.files[0]; 4 var reader = new FileReader(); 5 reader.onloadend = function (e) { 6 $(eleImg).attr("style", "display:inline-block"); 7 $(eleImg).attr("src", e.target.result); 8 dealImage(reader.result, 500, file, function(base64) { 9 callback(base64) 10 }) 11 } 12 if (file) { 13 reader.readAsDataURL(file); 14 } 15 }
//base64图片压缩 function dealImage(base64, w, file, callback) { var newImage = new Image(); var quality = 0.6; //压缩系数0-1之间 newImage.src = base64; newImage.setAttribute("crossOrigin", ‘Anonymous‘); //url为外域时需要 var imgWidth, imgHeight; newImage.onload = function () { imgWidth = this.width; imgHeight = this.height; var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); if (Math.max(imgWidth, imgHeight) > w) { if (imgWidth > imgHeight) { canvas.width = w; canvas.height = w * imgHeight / imgWidth; } else { canvas.height = w; canvas.width = w * imgWidth / imgHeight; } } else { canvas.width = imgWidth; canvas.height = imgHeight; quality = 0.6; } ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(this, 0, 0, canvas.width, canvas.height); var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句 // 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间,请加以下语句,quality初始值根据情况自定 // while (base64.length / 1024 > 150) { // quality -= 0.01; // base64 = canvas.toDataURL("image/jpeg", quality); // } // 防止最后一次压缩低于最低尺寸,只要quality递减合理,无需考虑 // while (base64.length / 1024 < 50) { // quality += 0.001; // base64 = canvas.toDataURL("image/jpeg", quality); // } //iphone需要对图片进行角度判断后旋转图片,保证图片正向 if(navigator.userAgent.match(/iphone/i)) { var myorientation = 0; EXIF.getData(file, function() { //图片方向角 var Orientation = null; EXIF.getAllTags(this); //获取方向角值 myorientation = EXIF.getTag(this, ‘Orientation‘); var mpImg = new MegaPixImage(newImage); mpImg.render(canvas, { maxWidth: 500, maxHeight: 700, quality: quality || 0.8, orientation: myorientation }); base64 = canvas.toDataURL(file.type, quality || 0.8); callback(base64) }); return } // 修复android // if(navigator.userAgent.match(/Android/i)) { // var encoder = new JPEGEncoder(); // base64 = encoder.encode(ctx.getImageData(0, 0, w, h), quality * 100 || 80); // } callback(base64);//必须通过回调函数返回,否则无法及时拿到该值 } }