通过security.imgSecCheck实现图片安全识别
发布于 4 年前 作者 fang70 4709 次浏览 来自 分享

1.云函数

1.1配置config.json,需要做一个授权的配置。

  "permissions": {
    "openapi": [
      "security.imgSecCheck"
    ]
  }

1.2编写云函数代码

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const checkImgResult = await cloud.openapi.security.imgSecCheck({
      media: {
        header:{'Content-Type':'application/octet-stream'},
        contentType: 'image/png',
        value: Buffer.from(event.value)
      }
    })
    return checkImgResult 
} catch (err) {
    return err
  }
}

2.本地js调用

2.1选取需要检测的图片

  //选取需要检测的图片
  checkImage(){
    let that = this
    wx.chooseImage({
      count: 1, 
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {        
        let tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        that.getFileBuffer(tempFilePaths[0])
      },
      fail(err) {
        console.log(err)
      }
    })
  }

2.2获取临时文件的buffer

注意事项:<span style="color: rgba(0, 0, 0, 0.9); letter-spacing: normal; font-size: 16px;">图片security.imgSecCheck 方法只可以接收buffer,所以需要把临时图片转化为buffer的形式进行传递,因此需要用到 </span><strong style="color: rgba(0, 0, 0, 0.9); letter-spacing: normal; font-size: 16px;">getFileSystemManager</strong><span style="color: rgba(0, 0, 0, 0.9); letter-spacing: normal; font-size: 16px;"> 的方法</span>
  //获取临时图片buffer
  getFileBuffer(tempFilePaths){
    let that = this
    wx.getFileSystemManager().readFile({
      filePath: tempFilePaths,
      success: res => {
        console.log('getFileBuffer执行成功',res.data)
        that.cloudCheckImage(res.data)
      },
      fail:err => {
        console.log('getFileBuffer执行失败',err)
      }
    })
  }

2.3调用云函数检测图片

注意事项:<span style="color: rgba(0, 0, 0, 0.9); letter-spacing: normal; font-size: 16px;">需要注意的是用微信自带API做图片安全检查,图片大小不能超过1MB</span>
  //调用云函数检测图片是否违规
  cloudCheckImage(buffer){
    wx.cloud.callFunction({
      name: 'checkImage',
      data: {
        value: buffer
      },
      success(res) {
        console.log('cloudCheckImage执行成功', res)
        if (res.result.errCode == 87014) {
          wx.showToast({
            title: '图片有违法违规内容',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: '图片通过审核',
            icon: 'success'
          })
        }
      },
      fail(err) {
        console.log('cloudCheckImage执行失败',err)
      }
    })
  }
1 回复

你的不报错吗?

ArrayBuffer byteLength 大点(可能50000+)就报错 请求实体过大

回到顶部