微信、支付宝、百度(drawImage及canvasGetImageData、支付宝(getImageData))踩坑,uni-app 获取图片底色像素值

数不尽的坑,其实都是自己没有耐心每端小程序去阅读api导致。

首先以微信实现为例,this.saveImgPath为当前选中图片地址。(选中图片部分就不赘述了,uni.chooseImage。自行查阅)

基本思路,将选中的图片,通过各端drawImage绘制到canvas中,然后获取截图部分canvasGetImageData(采用图片(10,10)作标点的像素)

微信端

  1. canvas取 canvas-id,
  2. drawImage参数为
    drawImage(String imageResource, Number sx, Number sy, Number sWidth, Number sHeight,Number dx, Number dy, Number dWidth, Number dHeight)
  3. 调用uni.canvasGetImageData,获取像素数组(一维)

支付宝端
4. canvas取 id,
5. drawImage参数为
drawImage(String base64, Number sx, Number sy, Number sWidth, Number sHeight,Number dx, Number dy, Number dWidth, Number dHeight) 注意,图片为base64
6. 调用canvas的实例方法getImageData,获取像素数组(一维)

百度端
7. canvas取 canvas-id,
8. drawImage参数为
drawImage(String imageResource, Number dx, Number dy, Number dWidth, Number dHeight,Number sx, Number sy, Number sWidth, Number sHeight)
9. 调用uni.canvasGetImageData,获取像素对象(一维)需用Array.from(colors)处理

<template>
    <view style="height: 100vh;width: 100vw;position: fixed; left: 200%">
      
      <canvas canvas-id="image-canvas" style="width:100%;height: 100%;">canvas>
      
      
      <canvas id="image-canvas" style="width:100%;height: 100%;">canvas>
      
    view>
template>
    getColor() {
      return new Promise((resolve, reject) => { 
        const testc = uni.createCanvasContext('image-canvas');
        const { x, y, width, height } = this
        let fun = uni.canvasGetImageData
        // #ifdef MP-WEIXIN
        testc.drawImage(this.saveImgPath, 10, 10, 20, 20, 0, 0, width, height)
        // #endif
        // #ifdef MP-BAIDU
        testc.drawImage(this.saveImgPath, 0, 0, width, height, 10, 10, 20, 20)
        // #endif
        // #ifdef MP-ALIPAY
        testc.drawImage(this.base64, 10, 10, 20, 20, 0, 0, width, height)
        fun = testc.getImageData
        // #endif
        testc.draw(false, () => {
          fun({
            x: 0,
            y: 0,
            width,
            height,
            canvasId: 'image-canvas',
            success: (imageData) => {
              const colors = imageData?.data
              
              // #ifndef MP-BAIDU
              resolve(colors)
              // #endif

              // #ifdef MP-BAIDU
              resolve(Array.from(colors))
              // 因返回结果字符过长,会导致iOS系统结果无法展示问题,这里将数据进行截断展示
              // #endif
            },
            fail: (err) => {
              console.log('err', err)
              reject([0, 0, 0])
            }
          })
        })
      })
    },

你可能感兴趣的:(微信,uni-app)