一、圖片裁剪
推薦一款輕量級圖片裁剪插件 kpsImageCuster:https://ext.dcloud.net.cn/plugin?id=1076。
其原理就是利用 uni.canvasToTempFilePath() 把當前畫布指定區域的內容導出生成指定大小的圖片,並返回文件路徑。
官方介紹見文檔:uni.canvasToTempFilePath(object, component)
setTimeout(() => { this.targetContext.drawImage(this.url, x, y, width, height, 0, 0, tw, th); this.targetContext.draw(false, () => { uni.canvasToTempFilePath({ canvasId: "target", success: (res) => { var path = res.tempFilePath; // #ifdef H5
if (this.blob) { path = this.parseBlob(path); } // #endif
this.$emit("ok", { path: path }); }, fail: (ev) => { console.log(ev); }, complete: () => { uni.hideLoading(); } }, this); }); }, 100);
二、解決uni-app在App端上傳圖片時路徑轉Base64的問題
在用uni-app開發項目的時候大家都會遇到這么一個問題,就是上傳圖片時在App上拿到的是文件路徑,然而后端要接收的卻是Base64字符串。但是在App端又無法調用Web Api(例如:Blob fileReader 等),這里推薦一款可以直接將Path轉為Base64的插件。
image-tools:插件地址 —— https://www.npmjs.com/package/image-tools
uniapp的插件:https://ext.dcloud.net.cn/plugin?id=123
其實就是一個工具類 js,可以選取里面的方法直接拿的用
import { pathToBase64 } from '@/utils/image-tools.js'
// 需要注意的是方法返回均是 promise,得使用promise的寫法
saveImg(e) { if(!e || !e.path) return pathToBase64(e.path).then(res => { this.uploadImg(res) }) },