原文地址: github.com/whinc/blog/…
最近接到一個“發(fā)表評論”的需求:用戶輸入評論并且可以拍照或從相冊選擇圖片上傳,即支持圖文評論。需要同時在 H5 和小程序兩端實現(xiàn),該需求處理圖片的地方較多,本文對 H5 端的圖片處理實踐做一個小結。項目代碼基于 Vue 框架,為了避免受框架影響,我將代碼全部改為原生 API 的實現(xiàn)方式進行說明,同時項目代碼中有很多其他額外的細節(jié)和功能(預覽、裁剪、上傳進度等)在這里都省去,只介紹與圖片處理相關的關鍵思路和代碼。小程序的實現(xiàn)方式與 H5 類似,不再重述,在文末附上小程序端的實現(xiàn)代碼。
拍照
使用 <input> 標簽, type 設為 "file" 選擇文件, accept 設為 "image/*" 選擇文件為圖片類型和相機拍攝,設置 multiple 支持多選。監(jiān)聽 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 方法可創(chuàng)建一個本地的 URL 路徑指向本地資源對象,下面使用該接口創(chuàng)建所選圖片的地址并展示。
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 元數(shù)據(jù),其中包括拍攝時相機的方向,根據(jù)這個方向可以推算出圖片的旋轉信息。
下面是 EXIF 旋轉標志位,總共有 8 種,但是通過相機拍攝時只能產(chǎn)生1、3、6、8 四種,分別對應相機正常、順時針旋轉180°、逆時針旋轉90°、順時針旋轉90°時所拍攝的照片。
所以糾正圖片旋轉角度,只要讀取圖片的 EXIF 旋轉標志位,判斷旋轉角度,在畫布上對圖片進行旋轉后,重新導出新的圖片即可。其中關于畫布的旋轉操作可以參考 canvas 圖像旋轉與翻轉姿勢解鎖 這篇文章。下面函數(shù)實現(xiàn)了對圖片文件進行旋轉角度糾正,接收一個圖片文件,返回糾正后的新圖片文件。
/** * 修正圖片旋轉角度問題 * @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 = () => { // 獲取圖片元數(shù)據(jù)(EXIF 變量是引入的 exif-js 庫暴露的全局變量) EXIF.getData(img, function() { // 獲取圖片旋轉標志位 var orientation = EXIF.getTag(this, "Orientation"); // 根據(jù)旋轉角度,在畫布上對圖片進行旋轉 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); } }); }; });}
圖片壓縮
現(xiàn)在的手機拍照效果越來越好,隨之而來的是圖片大小的上升,動不動就幾MB甚至十幾MB,直接上傳原圖,速度慢容易上傳失敗,而且后臺對請求體的大小也有限制,后續(xù)加載圖片展示也會比較慢。如果前端對圖片進行壓縮后上傳,可以解決這些問題。
下面函數(shù)實現(xiàn)了對圖片的壓縮,原理是在畫布上繪制縮放后的圖片,最終從畫布導出壓縮后的圖片。方法中有兩處可以對圖片進行壓縮控制:一處是控制圖片的縮放比;另一處是控制導出圖片的質(zhì)量。
/** * 壓縮圖片 * @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; // 計算縮放因子 // 這里我取水平和垂直方向縮放因子較大的作為縮放因子,這樣可以保證圖片內(nèi)容全部可見 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 控制導出的圖片質(zhì)量,進行實現(xiàn)圖片的壓縮 const quality = 0.92 canvas.toBlob(file => resolve(tempFile), "image/jpeg", quality); }; });},
圖片上傳
通過 FormData 創(chuàng)建表單數(shù)據(jù),發(fā)起 ajax POST 請求即可,下面函數(shù)實現(xiàn)了上傳文件。
注意:發(fā)送 FormData 數(shù)據(jù)時,瀏覽器會自動設置 Content-Type 為合適的值,無需再設置 Content-Type ,否則反而會報錯,因為 HTTP 請求體分隔符 boundary 是瀏覽器生成的,無法手動設置。
/** * 上傳文件 * @param {File} file 待上傳文件 * @returns {Promise} 上傳成功返回 resolved promise,否則返回 rejected promise */function uploadFile (file) { return new Promise((resolve, reject) => { // 準備表單數(shù)據(jù) 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) })}
小結
有了上面這些輔助函數(shù),處理起來就簡單多了,最終調(diào)用代碼如下:
function onFileChange (event) { const files = Array.prototype.slice.call(event.target.files) const file = files[0] // 修正圖片旋轉 fixImageOrientation(file).then(file2 => { // 創(chuàng)建預覽圖片 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 提供了處理文件的接口,借助畫布可以在瀏覽器中實現(xiàn)復雜的圖片處理,本文總結了移動端 H5 上傳圖片這個場景下的一些圖片處理實踐,以后遇到類似的需求可作為部分參考。
附小程序實現(xiàn)參考
// 拍照wx.chooseImage({ sourceType: ["camera"], success: ({ tempFiles }) => { const file = tempFiles[0] // 處理圖片 }});/** * 壓縮圖片 * @param {Object} params * filePath: String 輸入的圖片路徑 * success: Function 壓縮成功時回調(diào),并返回壓縮后的新圖片路徑 * fail: Function 壓縮失敗時回調(diào) */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); } });}
總結
以上所述是小編給大家介紹的HTML5 和小程序實現(xiàn)拍照圖片旋轉、壓縮和上傳功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答