用云函數(shù)這一利器改寫了ai摳圖

引言

上次寫了一篇用小程序?qū)崿F(xiàn)ai摳圖,就差一步可以能在小程序全盤使用第三方庫去摳圖,苦于不能將Buffer圖片源轉(zhuǎn)成base64賦給<image>,上了node.js后端去實現(xiàn),這兩天突然想起可以用云函數(shù)去實現(xiàn),果斷用云函數(shù)代替自己寫后端。

純微信小程序端實現(xiàn)ai摳圖代碼如下:

wx.chooseImage({
  count: 1, // 默認(rèn)9
  sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
  sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機(jī),默認(rèn)二者都有
  success: res => {
    var tempFilePaths = res.tempFilePaths
    const file = tempFilePaths[0]
    this.setData({
      origin: file
    })
    console.log(file)
    wx.uploadFile({
      header: {
        'X-Api-Key': 'your key'
      },
      url: ' https://api.remove.bg/v1.0/removebg',
      filePath: file,
      name: 'image_file',
      success: res => {
        const data = res.data
        console.log(data)
        console.log('base64')
        const base64 = data.toString('base64')
        console.log(base64)
        let url = base64
        this.setData({
          url: url
        })
      }
    })
  }
})
  

只可惜上面的代碼最終還是亂碼的,不能賦值給image來渲染

于是后來,才動用node.js koa框架寫了一個簡單的后端實現(xiàn)。

使用云函數(shù)改寫

koa就為了轉(zhuǎn)發(fā)一下請求,這一跳板有點大材小用,于是乎想到用云函數(shù),就免去買服務(wù)器,配后端環(huán)境,起koa項目。

建立云函數(shù)目錄并配置

在項目根目錄新建文件夾functions,并在project.config.json中增加如下設(shè)置

{
   "cloudfunctionRoot": "./functions/"
}

然后項目目錄下會出現(xiàn)如下標(biāo)識

云函數(shù)

添加云函數(shù)

鼠標(biāo)右擊functions文件,創(chuàng)建云函數(shù)ps,安裝依賴,npm install request-promise --save

具體代碼如下

// 云函數(shù)入口文件
const rp = require('request-promise')
// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
  // const wxContext = cloud.getWXContext()
  const file = event.file
  const buffer = new Buffer.from(file, 'base64')
  const result = await rp.post({
    url: 'https://api.remove.bg/v1.0/removebg',
    formData: {
      image_file: buffer,
      size: 'auto'
    },
    headers: {
      'X-Api-Key': 'wkMhcc4TRNFpxjL79Kf8mMU1'
    },
    encoding: null
  })
  const body = result
  const image = body.toString('base64')
  return {
    image
  }
}

原理就是將文件的base64編碼,再轉(zhuǎn)換成buffer,再提交給remove.bg這個ai摳圖api地址。于是現(xiàn)在只剩下一件事,就是將小程序端本來是用二進(jìn)制文件上傳的,要先將它改成用base64后,才能傳遞給云函數(shù)。

小程序端上傳傳base64編碼

這里使用小程序的FileSystemManager.readFile方法將圖片二進(jìn)制文件,轉(zhuǎn)成base64再提交給云函數(shù)。

相關(guān)文檔:
https://developers.weixin.qq.com/minigame/dev/api/file/FileSystemManager.readFile.html

于是完整的小程序前端代碼如下

wx.getFileSystemManager().readFile({
  filePath: file, //選擇圖片返回的相對路徑
  encoding: 'base64', //編碼格式
  success: res => {
    //成功的回調(diào)
    wx.cloud.callFunction({
      name: 'ps',
      data: {
        file: res.data
      },
      success: (res) => {
        console.log(res)
        const data = res.result.image
        let url = 'data:image/png;base64,' + data
        this.setData({
          url: url
        })
        //     //do something
        console.log(res)
      },
      fail(err) {
        console.log(err)
      }
    })
  }
})

先作base64編碼,然后調(diào)用云函數(shù),最后將云函數(shù)返回的base64圖片資源渲染到<image>,整個流程走完。

源碼

https://gitee.com/laeser/demo-weapp 代碼位于pages/ps-cloud文件夾下

關(guān)注我

mp
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容