美文网首页
MiniProgram - Combine Images

MiniProgram - Combine Images

作者: 7dbe8fdb929f | 来源:发表于2020-08-28 13:55 被阅读0次

When I understand myself, I understand you, and out of that understanding comes love.
-- Jiddu Krishnamurti

Sometimes we need to combine a few images to one image, such as card and coupon generation. For mini program, we can use canvas and context api to accomplish this task.

Steps:
  1. Download images
  2. Draw images to canvas
  3. Get image data from canvas
  4. Convert image data and save image

<canvas canvas-id="canvas"></canvas>

Firstly, we need to download images and save the local temp file paths, it's more convenient compared to remote resource and can save us from unpredictable trouble.

wx.downloadFile({
  url: "IMAGE_URL", 
  success(res) {
    if (res.statusCode === 200) {
      let url1 = res.tempFilePath
    }
  }
})

Then draw images to the canvas.

// Draw and transform
context.drawImage(url1, 0, 0, width1, height1)
context.drawImage(url2, 0, 0, width2, height2)
context.draw(true, () => {
  // do the next step
})

Get binary image data, use upng.js to encode, convert array buffer to base64 and save it to local file.

wx.canvasGetImageData({
  canvasId: 'canvas',
  x: 0,
  y: 0,
  width: MAX_WIDTH,
  height: MAX_HEIGHT,
  success(res) {
    let pngData = UPNG.encode([res.data.buffer], res.width, res.height)
    let base64 = wx.arrayBufferToBase64(pngData)
    let src = 'data:image/png;base64,' + base64
    saveBase64src(src, res => {
      // res will be what you wanted
    })
  }
})
const saveBase64src = function (base64data, cb) {
  const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
  if (!format) {
    return (new Error('ERROR_BASE64SRC_PARSE'));
  }
  const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
  const buffer = wx.base64ToArrayBuffer(bodyData);
  let fsm = wx.getFileSystemManager()
  fsm.writeFile({
    filePath,
    data: buffer,
    encoding: 'binary',
    success() {
      cb(filePath);
    },
    fail() {
      return (new Error('ERROR_BASE64SRC_WRITE'));
    },
  })
}

相关文章

网友评论

      本文标题:MiniProgram - Combine Images

      本文链接:https://www.haomeiwen.com/subject/psrlsktx.html