微信小程序—调用imgSecCheck接口实现多张图片鉴黄,敏感过滤

之前写过单张图片调用微信小程序—智能鉴黄、敏感识别的文章,突然有客户要求批量上传图片时实现这个功能,以为很简单,结果发现还是有很大差别的。

效果如下:

在这里插入图片描述

体验路径:

在这里插入图片描述

客户端代码:

// miniprogram/pages/index/pages/imgSecCheck/imgSecCheck.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cWidth: "",
    cHeight: "",
    srcList: [],
    srcTips:[],
    imgList:[],
    finalImgList:[]
  },
  
  chooseImage() {
    let that = this;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 指定只能为压缩图,首先进行一次默认压缩
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      async success(photo) {
        console.log("原始图片",photo)
        that.setData({
          srcList: photo.tempFilePaths
        })
        wx.showLoading({
          title: '正在检测图片',
        })
        var srcTips = []
        var imgList= []
        for (var i = 0; i < that.data.srcList.length; i++){
          srcTips.push("")
          imgList.push("")
        }
        that.setData({
          srcTips:srcTips,
          imgList:imgList
        })
        for(var i = 0;i<that.data.srcList.length;i++){
          let a = await that.compressImg(that.data.srcList[i],i)
          console.log("最终结果",srcTips)
        }
      },
    })
  },

  // 压缩功能  参数说明:图片的路径、
  async compressImg(photoSrc, index,ratio = 2, limitNum = 200) {
    let that = this;
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: photoSrc,
        success(res) {
          var canvasWidth = res.width //图片原始长宽
          var canvasHeight = res.height
          console.log('图片的基本信息', res)
          while (canvasWidth > limitNum || canvasHeight > limitNum) { // 保证宽高在400以内
            canvasWidth = Math.trunc(res.width / ratio)
            canvasHeight = Math.trunc(res.height / ratio)
            ratio++;
          }
          that.setData({
            cWidth: canvasWidth,
            cHeight: canvasHeight
          })
          console.log("图片宽度:" + canvasWidth + ";图片高度:" + canvasHeight)
          //----------绘制图形并取出图片路径--------------
          var ctx = wx.createCanvasContext('canvas')
          ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
          ctx.draw(false, setTimeout(() => {
            wx.canvasToTempFilePath({
              canvasId: 'canvas',
              destWidth: canvasWidth,
              destHeight: canvasHeight,
              fileType: "jpg",
              success: function (res) {
                var imgList = that.data.imgList
                console.log("最终图片路径", res.tempFilePath)//最终图片路径
                imgList[index] = res.tempFilePath
                that.setData({
                  imgList:imgList
                })
                console.log(imgList)
                const fsm = wx.getFileSystemManager();
                fsm.readFile({
                  filePath: res.tempFilePath,
                  success: function (res) {
                    console.log(res)
                    wx.cloud.callFunction({
                      name: 'imgSecCheck',
                      data: {
                        contentType: "image/jpg",
                        arrayBuffer: res.data
                      },
                      success: function (res) {
                        var srcTips = that.data.srcTips
                        if (res.result.errCode == 0) {
                          srcTips[index] = "合法图片"
                        } else if (res.result.errCode == 87014) {
                          srcTips[index] = "违法图片"
                        } else {
                          srcTips[index] = "接口异常"
                        }
                        that.setData({
                          srcTips: srcTips
                        })
                        console.log("srcTips", that.data.srcTips)
                        resolve(srcTips)
                        wx.hideLoading()
                      },
                      fail: function (e) {
                        var srcTips = that.data.srcTips
                        srcTips[index] = "接口异常"
                        that.setData({
                          srcTips:srcTips
                        })
                        if (index == (that.data.srcList.length - 1)) {
                          wx.hideLoading()
                          var finalImgList = []
                          for (var i = 0; i < that.data.srcTips.length; i++) {
                            if (that.data.srcTips[i] == "合法图片") {
                              finalImgList.push(that.data.imgList[i])
                            }
                          }
                          console.log("最终去除违法图片后的图片列表", finalImgList)
                          that.data.finalImgList = finalImgList
                        }
                      }
                    })
                  },
                  fail: function (e) { }
                })
              },
              fail: function (res) {
                console.log(res.errMsg)
              }
            })
          }, 500))
        },
        fail: function (res) {
          console.log(res.errMsg)
        },
      })
    })
  }
})
<canvas canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"></canvas>

<view class="container">
  <block wx:for="{{imgList}}" wx:key="srcUnique">
    <image style="background:white;margin:20rpx;border-radius:10rpx;width:250rpx;height:250rpx" mode='aspectFit' src='{{item}}'></image>
    <view>{{srcTip[index]}}</view>
  </block>

  <button style="width:60%;margin:20rpx;" type="primary" bindtap='chooseImage'>上传图片校验</button>
</view>

服务端代码:

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var arrayBuffer = event.arrayBuffer
  var contentType = event.contentType
  var buf = Buffer.from(arrayBuffer)
  try {
    var result = await cloud.openapi.security.imgSecCheck({
      media: {
        contentType: 'image/jpg',
        value: buf
      }
    })
    return result
  } catch (err) {
    return err
  }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玩烂小程序

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值