H5 和小程式拍照圖片旋轉、壓縮和上傳
原文地址: ofollow,noindex">github.com/whinc/blog/…
最近接到一個“發表評論”的需求:使用者輸入評論並且可以拍照或從相簿選擇圖片上傳,即支援圖文評論。需要同時在 H5 和小程式兩端實現,該需求處理圖片的地方較多,本文對 H5 端的圖片處理實踐做一個小結。專案程式碼基於 Vue 框架,為了避免受框架影響,我將程式碼全部改為原生 API 的實現方式進行說明,同時專案程式碼中有很多其他額外的細節和功能(預覽、裁剪、上傳進度等)在這裡都省去,只介紹與圖片處理相關的關鍵思路和程式碼。小程式的實現方式與 H5 類似,不再重述,在文末附上小程式端的實現程式碼。

拍照
使用 <input>
標籤, type
設為 "file"
選擇檔案, accept
設為 "image/*"
選擇檔案為圖片型別和相機拍攝,設定 multiple
支援多選。監聽 change
事件拿到選中的檔案列表,每個檔案都是一個 Blob
型別。
<input type="file" accept="image/*" multiple /> <img class="preivew" /> <script type="text/javascript"> function onFileChange (event) { const files = Array.prototype.slice.call(event.target.files) files.forEach(file => console.log('file name:', file.name)) } document.querySelector('input').addEventListener('change', onFileChange) </script> 複製程式碼
圖片預覽
URL.createObjectURL
方法可建立一個本地的 URL 路徑指向本地資源物件,下面使用該介面建立所選圖片的地址並展示。
function onFileChange (event) { const files = Array.prototype.slice.call(event.target.files) const file = files[0] document.querySelector('img').src = window.URL.createObjectURL(file) } 複製程式碼

圖片旋轉

通過相機拍攝的圖片,由於拍攝時手持相機的方向問題,導致拍攝的圖片可能存在旋轉,需要進行糾正。糾正旋轉需要知道圖片的旋轉資訊,這裡藉助了一個叫 exif-js 的庫,該庫可以讀取圖片的 EXIF 元資料,其中包括拍攝時相機的方向,根據這個方向可以推算出圖片的旋轉資訊。
下面是 EXIF 旋轉標誌位,總共有 8 種,但是通過相機拍攝時只能產生1、3、6、8 四種,分別對應相機正常、順時針旋轉180°、逆時針旋轉90°、順時針旋轉90°時所拍攝的照片。

所以糾正圖片旋轉角度,只要讀取圖片的 EXIF 旋轉標誌位,判斷旋轉角度,在畫布上對圖片進行旋轉後,重新匯出新的圖片即可。其中關於畫布的旋轉操作可以參考 canvas 影象旋轉與翻轉姿勢解鎖 這篇文章。下面函式實現了對圖片檔案進行旋轉角度糾正,接收一個圖片檔案,返回糾正後的新圖片檔案。
/** * 修正圖片旋轉角度問題 * @param {file} 原圖片 * @return {Promise} resolved promise 返回糾正後的新圖片 */ function fixImageOrientation (file) { return new Promise((resolve, reject) => { // 獲取圖片 const img = new Image(); img.src = window.URL.createObjectURL(file); img.onerror = () => resolve(file); img.onload = () => { // 獲取圖片元資料(EXIF 變數是引入的 exif-js 庫暴露的全域性變數) EXIF.getData(img, function() { // 獲取圖片旋轉標誌位 var orientation = EXIF.getTag(this, "Orientation"); // 根據旋轉角度,在畫布上對圖片進行旋轉 if (orientation === 3 || orientation === 6 || orientation === 8) { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); switch (orientation) { case 3: // 旋轉180° canvas.width = img.width; canvas.height = img.height; ctx.rotate((180 * Math.PI) / 180); ctx.drawImage(img, -img.width, -img.height, img.width, img.height); break; case 6: // 旋轉90° canvas.width = img.height; canvas.height = img.width; ctx.rotate((90 * Math.PI) / 180); ctx.drawImage(img, 0, -img.height, img.width, img.height); break; case 8: // 旋轉-90° canvas.width = img.height; canvas.height = img.width; ctx.rotate((-90 * Math.PI) / 180); ctx.drawImage(img, -img.width, 0, img.width, img.height); break; } // 返回新圖片 canvas.toBlob(file => resolve(file), 'image/jpeg', 0.92) } else { return resolve(file); } }); }; }); } 複製程式碼
圖片壓縮
現在的手機拍照效果越來越好,隨之而來的是圖片大小的上升,動不動就幾MB甚至十幾MB,直接上傳原圖,速度慢容易上傳失敗,而且後臺對請求體的大小也有限制,後續載入圖片展示也會比較慢。如果前端對圖片進行壓縮後上傳,可以解決這些問題。
下面函式實現了對圖片的壓縮,原理是在畫布上繪製縮放後的圖片,最終從畫布匯出壓縮後的圖片。方法中有兩處可以對圖片進行壓縮控制:一處是控制圖片的縮放比;另一處是控制匯出圖片的質量。
/** * 壓縮圖片 * @param {file} 輸入圖片 * @returns {Promise} resolved promise 返回壓縮後的新圖片 */ function compressImage(file) { return new Promise((resolve, reject) => { // 獲取圖片(載入圖片是為了獲取圖片的寬高) const img = new Image(); img.src = window.URL.createObjectURL(file); img.onerror = error => reject(error); img.onload = () => { // 畫布寬高 const canvasWidth = document.documentElement.clientWidth * window.devicePixelRatio; const canvasHeight = document.documentElement.clientHeight * window.devicePixelRatio; // 計算縮放因子 // 這裡我取水平和垂直方向縮放因子較大的作為縮放因子,這樣可以保證圖片內容全部可見 const scaleX = canvasWidth / img.width; const scaleY = canvasHeight / img.height; const scale = Math.min(scaleX, scaleY); // 將原始圖片按縮放因子縮放後,繪製到畫布上 const canvas = document.createElement('canvas'); const ctx = canvas.getContext("2d"); canvas.width = canvasWidth; canvas.height = canvasHeight; const imageWidth = img.width * scale; const imageHeight = img.height * scale; const dx = (canvasWidth - imageWidth) / 2; const dy = (canvasHeight - imageHeight) / 2; ctx.drawImage(img, dx, dy, imageWidth, imageHeight); // 匯出新圖片 // 指定圖片 MIME 型別為 'image/jpeg', 通過 quality 控制匯出的圖片質量,進行實現圖片的壓縮 const quality = 0.92 canvas.toBlob(file => resolve(tempFile), "image/jpeg", quality); }; }); }, 複製程式碼
圖片上傳
通過 FormData
建立表單資料,發起 ajax POST
請求即可,下面函式實現了上傳檔案。
注意:傳送 FormData
資料時,瀏覽器會自動設定 Content-Type
為合適的值,無需再設定 Content-Type
,否則反而會報錯,因為 HTTP 請求體分隔符 boundary 是瀏覽器生成的,無法手動設定。
/** * 上傳檔案 * @param {File} file 待上傳檔案 * @returns {Promise} 上傳成功返回 resolved promise,否則返回 rejected promise */ function uploadFile (file) { return new Promise((resolve, reject) => { // 準備表單資料 const formData = new FormData() formData.append('file', file) // 提交請求 const xhr = new XMLHttpRequest() xhr.open('POST', uploadUrl) xhr.onreadystatechange = function () { if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { resolve(JSON.parse(this.responseText)) } else { reject(this.responseText) } } xhr.send(formData) }) } 複製程式碼
小結
有了上面這些輔助函式,處理起來就簡單多了,最終呼叫程式碼如下:
function onFileChange (event) { const files = Array.prototype.slice.call(event.target.files) const file = files[0] // 修正圖片旋轉 fixImageOrientation(file).then(file2 => { // 建立預覽圖片 document.querySelector('img').src = window.URL.createObjectURL(file2) // 壓縮 return compressImage(file2) }).then(file3 => { // 更新預覽圖片 document.querySelector('img').src = window.URL.createObjectURL(file3) // 上傳 return uploadFile(file3) }).then(data => { console.log('上傳成功') }).catch(error => { console.error('上傳失敗') }) } 複製程式碼
H5 提供了處理檔案的介面,藉助畫布可以在瀏覽器中實現複雜的圖片處理,本文總結了移動端 H5 上傳圖片這個場景下的一些圖片處理實踐,以後遇到類似的需求可作為部分參考。
附小程式實現參考
// 拍照 wx.chooseImage({ sourceType: ["camera"], success: ({ tempFiles }) => { const file = tempFiles[0] // 處理圖片 } }); /** * 壓縮圖片 * @param {Object} params * filePath: String 輸入的圖片路徑 * success: Function 壓縮成功時回撥,並返回壓縮後的新圖片路徑 * fail: Function 壓縮失敗時回撥 */ compressImage({ filePath, success, fail }) { // 獲取圖片寬高 wx.getImageInfo({ src: filePath, success: ({ width, height }) => { const systemInfo = wx.getSystemInfoSync(); const canvasWidth = systemInfo.screenWidth; const canvasHeight = systemInfo.screenHeight; // 更新畫布尺寸 this.setData({ canvasWidth, canvasHeight }) // 計算縮放比例 const scaleX = canvasWidth / width; const scaleY = canvasHeight / height; const scale = Math.min(scaleX, scaleY); const imageWidth = width * scale; const imageHeight = height * scale; // 將縮放後的圖片繪製到畫布 const ctx = wx.createCanvasContext("hidden-canvas"); let dx = (canvasWidth - imageWidth) / 2; let dy = (canvasHeight - imageHeight) / 2; ctx.drawImage(filePath, dx, dy, imageWidth, imageHeight); ctx.draw(false, () => { // 匯出壓縮後的圖片到臨時檔案 wx.canvasToTempFilePath({ canvasId: "hidden-canvas", width: canvasWidth, height: canvasHeight, destWidth: canvasWidth, destHeight: canvasHeight, fileType: "jpg", quality: 0.92, success: ({ tempFilePath }) => { // 隱藏畫布 this.setData({ canvasWidth: 0, canvasHeight: 0 }) // 壓縮完成 success({ tempFilePath }); }, fail: error => { // 隱藏畫布 this.setData({ canvasWidth: 0, canvasHeight: 0 }) fail(error); } }); }); }, fail: error => { fail(error); } }); } /** * 上傳檔案 */ uploadFile({ uploadUrl, filePath, onData, onError }) { wx.uploadFile({ url: uploadUrl filePath: filePath, name: "file", header: { Cookie: cookie }, success: res => { if (res.statusCode === 200) { onData(res.data) } else { onError(res); } }, fail: error => { onError(error); } }); } 複製程式碼