<!-- 解決圖片旋轉 --> <script src="/libs/jquery/jquery.min.js"></script> <script src="/libs/exif/exif.js"></script> // html <input type="file" accept="image ...
<!-- 解決圖片旋轉 --> <script src="/libs/jquery/jquery.min.js"></script> <script src="/libs/exif/exif.js"></script> // html <input type="file" accept="image/*;capture=camera"> // 此方法是旋轉圖片; 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); // 判斷圖片 類型 (可增加判斷的類型 此處只判斷了 jpeg 和png) var imgtype = img.includes('image/png') ? "image/png" : "image/jpeg"; //返回校正圖片 next(canvas.toDataURL(imgtype, .8)); } image.src = img; }; $("input[type = file]").change(function () { var _this = $(this); var file = this.files[0]; // console.log(file) var orientation; var site = location.protocol + '//' + location.host + '/api/wx_user/upload_img/base_upload'; //EXIF js 可以讀取圖片的元信息 https://github.com/exif-js/exif-js if (!/image.(png|jpg|jpeg|bmp)/.test(file.type)) { alert('選擇的文件類型不是圖片'); return; } EXIF.getData(file, function () { orientation = EXIF.getTag(this, 'Orientation'); }); var reader = new FileReader(); reader.onload = function (e) { getImgData(this.result, orientation, function (data) { //這裡可以使用校正後的圖片data了 // 此處ajax用於 base64路徑轉換成正常路徑 $.ajax({ url: site, data: { str: data, type: file.type }, type: 'post', dataType: 'json', success: function (i) { _this.siblings("img").attr('src', i.img_url); } }) }); } reader.readAsDataURL(file); });