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