1. 程式人生 > 其它 >淺析uniapp如何做圖片裁剪及遇到問題 uni.canvasToTempFilePath 在APP下返回的是臨時路徑,如何把路徑轉為base64的解決方案

淺析uniapp如何做圖片裁剪及遇到問題 uni.canvasToTempFilePath 在APP下返回的是臨時路徑,如何把路徑轉為base64的解決方案

一、圖片裁剪

  推薦一款輕量級圖片裁剪外掛 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)
    })
},