【开源】【猫咪卡通变 - 小程序】拍摄猫咪或上传猫咪照片,使其转化为卡通猫咪.(且上传图片必须为猫咪)

【来源】https://juejin.cn/post/7028624704491487269

一 前言

废话不多说,直接看吧!

涉及技术:微信小程序云开发

涉及API接口:百度云-图像增强百度云-图像识别

二 展示情况

【上传检查】

上传检查.gif

【整体流程】

整体.gif

三 链接要点(API接口的准备工作)

涉及百度云的API接口,我们需要申请注册百度云。
调用API接口,需要用到百度云的access_tokenaccess_token又需要请求一个接口方可能获取到。(并且access_token有效时间是一个月)

流程(获取access_token官方实例):

注册后——》来到所需的产品服务页面——》创建应用——》管理应用

image.png
——》拿到请求access_token的参数client_idclient_secret
image.png
——》发送请求获取access_tokenhttps://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】(只需要修改百度云应用的AK和SK改成应用里的对应API Key和Secret Key)
image.png
——》然后就可以查看对应的接口文档进行使用啦~
这里展示的是:动物识别
image.png

四 核心代码

微信小程序·云开发

【识别猫照 · 云函数代码】

checkAnimal文件夹下index.js 云函数代码

// 云函数入口文件
const cloud = require('wx-server-sdk')
var rp = require('request-promise')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  let datas = event.datas
  datas.access_token = '你的百度云access_token' // 这里需要添加
  return new Promise((resolve, reject) => {
    rp({
      url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/animal',
      method: "POST",
      json: true,
      form: event.datas,
    }, function (error, response, body) {
      console.log("响应" + body)
      resolve(body)
      if (!error && response.statusCode == 200) {
        try {} catch (e) {
          reject()
        }
      }
    })
  })
}

【变卡通 · 云函数代码】

catChange文件夹下index.js 云函数代码

// 云函数入口文件
const cloud = require('wx-server-sdk')
var rp = require('request-promise')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const DB = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  let datas = event.datas
  datas.access_token = '你的百度云access_token' // 这里需要添加
  return new Promise((resolve, reject) => {
    rp({
      url: 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime',
      method: "POST",
      json: true,
      form: event.datas,
    }, function (error, response, body) {
      console.log("响应" + body)
      resolve(body)
      if (!error && response.statusCode == 200) {
        try {} catch (e) {
          reject()
        }
      }
    })
  })
}

页面的js代码

【识别猫照 · js代码】

    // 检查图片是不是动物,再判断是否为猫咪
    // baseImg传的是base64格式,并且前面是没有'data:image/png;base64'
    wx.cloud.callFunction({
      name: 'checkAnimal',
      data: {
        datas: {
          image: baseImg,
        }
      }
    }).then(res => {
      console.log(res)
      var checkName = res.result.result[0].name
      console.log(checkName.indexOf("猫"))
      if (!checkName || checkName.indexOf("猫") == -1) {
        wx.showToast({
          title: '请添加有猫咪的照片!',
          icon: 'none'
        })
      } else {
        that.setData({
          image,
          baseImg
        })
      }
      // that.setData({
      //   image: 'data:image/png;base64,' + res.result.image,
      //   baseImg: res.result.image,
      // }) 
    }).catch(err => {
    }).finally(() => {
    })

【变卡通 · js代码】

    // baseImg传的是base64格式,并且前面是没有'data:image/png;base64'
    wx.cloud.callFunction({
      name: 'catChange',
      data: {
        datas: {
          image: that.data.baseImg,
        }
      }
    }).then(res => {
      console.log(res)
      that.setData({
        image: 'data:image/png;base64,' + res.result.image,
        baseImg: res.result.image,
      })
    }).catch(err => {
    }).finally(() => {
    })

五 完整代码

cat_change.wxml代码】

<view style='width:0;height:0;overflow:hidden;' wx:if="{{cut}}">
  <canvas class='image-canvas' canvas-id="shareImg" wx:if="{{cut}}"></canvas>
</view>
<view>
  <view class='head'>
    <view>点击加号上传图片</view>
  </view>

  <view class='image-box'>
    <view class='image' style="border: 20px solid white;">
      <image class='image' src='{{image}}'></image>
    </view>
  </view>
  <view style='position:absolute;top: 59%;width:100%;text-align: center;'><text
      style="font-size: 24rpx;color: rgb(90, 90, 90);" space="emsp">滑动看看更多小猫咪↔</text></view>
  <view id="kuang" class='image-kuang' bindtap='chooseImage'>
    <image class='image' src='{{image1}}'></image>
  </view>
  <scroll-view scroll-x class='top' scroll-with-animation='true' bindscroll='scroll'>
    <view id='-1' class='pic-box' bindtap='chooseKuang'>
     <!-- 这里图片需要换 -->
      <image class='pic'
        src='cloud://develop-3gb3s6m1d5806159.6465-develop-3gb3s6m1d5806159-1304559061/images/tool/cat_change/add.png'></image>
    </view>
  </scroll-view>
  <view class="bottom">
    <button type='primary' bindtap='changePic' class=''>猫咪卡通变</button>
    <button type='primary' bindtap='savePic' class=''>保存小猫</button>
  </view>
</view>

cat_change.css代码】

page {
  background: #e5e5e5;
}

.image-canvas {
  position: absolute;
  /*启用绝对定位*/
  top: 100%;
  width: 1000px;
  height: 1000px;
}

page,
.cropper-wrapper {
  width: 100%;
  height: 100%;
}

.head {
  width: 750rpx;
  height: 250rpx;
  display: flex;
  justify-content: center;
  /*垂直居中*/
  align-items: center;
  /*水平居中*/
  font-size: 28rpx;
  color: rgb(90, 90, 90);
  flex-direction: column;
  /*纵向排布*/
}

.top {
  height: 200rpx;
  white-space: nowrap;
  display: flex;
  position: absolute;
  /*启用绝对定位*/
  top: 65%;
}

.pic-box {
  border: 5rpx solid white;
  width: 150rpx;
  height: 150rpx;
  display: inline-block;
  margin: 0.1rem;
  /* padding-left: 0.3125rem; */
}

.pic-white {
  display: inline-block;
  width: 125rpx;
}

.pic {
  height: 100%;
  width: 100%;
}

.image-box {
  position: absolute;
  /*启用绝对定位*/
  top: 15%;
  width: 750rpx;
  height: 500rpx;
  display: flex;
  justify-content: center;
  /*垂直居中*/
  align-items: center;
  /*水平居中*/
}

.image-kuang {
  position: absolute;
  /*启用绝对定位*/
  top: 15%;
  width: 750rpx;
  height: 500rpx;
  display: flex;
  z-index: 100;
  justify-content: center;
  /*垂直居中*/
  align-items: center;
  /*水平居中*/
}

.image {
  width: 500rpx;
  height: 500rpx;
}

.bottom {
  display: flex;
  position: fixed;
  top: 82%;
  width: 100%;
  color: rgb(90, 90, 90);
  font-size: 24rpx;
  justify-content: center;
  /*垂直居中*/
  align-items: center;
  /*水平居中*/
}

cat_change.js代码】

Page({

  data: {
    image1: '',
    baseImg: '', // base64没有data:image/jpg;base64,
    image: 'cloud://develop-3gb3s6m1d5806159.6465-develop-3gb3s6m1d5806159-1304559061/images/tool/cat_change/add.png', // 这里图片需要换
  },

  chooseImage() {
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#FAD143",
      success: function (res) {
        if (!res.cancel) {
          wx.showLoading({
            title: '正在读取...',
          })
          // wx.showToast({
          //   title: '正在读取...',
          //   icon: 'loading'
          // })
          if (res.tapIndex == 0) {
            that.chooseWxImage1('album', 1)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage1('camera', 1)
          }
        }
      }
    })
  },
  chooseWxImage1(type, imglng) {
    var that = this;
    console.log(imglng)
    wx.chooseImage({
      count: imglng, // 最大图片数量
      sizeType: ['original'], // ['original', 'compressed'], // compressed : 压缩图
      sourceType: [type],
      success: function (res) {
        // that.setData({
        //   image: res.tempFilePaths
        // })
        //以下为图片路径转base64位
        //图片base64位
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: (res) => {
            wx.showLoading({
              title: '正在检查图片...',
            })
            let baseImg = res.data
            let image = 'data:image/png;base64,' + res.data
            // console.log(baseImg)

            // 检查图片是不是动物,再判断是否为猫咪
            wx.cloud.callFunction({
              name: 'checkAnimal',
              data: {
                datas: {
                  image: baseImg,
                }
              }
            }).then(res => {
              console.log(res)
              var checkName = res.result.result[0].name
              console.log(checkName.indexOf("猫"))
              if (!checkName || checkName.indexOf("猫") == -1) {
                wx.showToast({
                  title: '请添加有猫咪的照片!',
                  icon: 'none'
                })
              } else {
                that.setData({
                  image,
                  baseImg
                })
              }
              // that.setData({
              //   image: 'data:image/png;base64,' + res.result.image,
              //   baseImg: res.result.image,
              // }) 
            }).catch(err => {

            }).finally(() => {
              wx.hideLoading()
            })
          }
        })
        // } catch (err) {
        //   console.log(err)
        // }
        console.log(res.tempFilePaths[0])
      }
    })
    wx.hideLoading()
  },
  /**
   * 变卡通
   */
  changePic: function (e) {
    let that = this

    var baseImg = that.data.baseImg
    if (baseImg.length < 8) {
      wx.showToast({
        title: '请先添加小猫照片噢~',
        icon: 'none'
      })
      return
    }


    wx.showLoading({
      title: '正在变身...',
    })
    wx.cloud.callFunction({
      name: 'catChange',
      data: {
        datas: {
          image: that.data.baseImg,
        }
      }
    }).then(res => {
      console.log(res)
      that.setData({
        image: 'data:image/png;base64,' + res.result.image,
        baseImg: res.result.image,
      })
    }).catch(err => {

    }).finally(() => {
      wx.hideLoading()
    })
  },
  savePic(e) {
    let that = this
    var baseImg = that.data.baseImg
    if (baseImg.length < 8) {
      wx.showToast({
        title: '请先生成卡通猫咪~',
        icon: 'none'
      })
      return
    }
    //保存图片
    var save = wx.getFileSystemManager();
    var number = Math.random();
    save.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
      data: baseImg,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
          success: function (res) {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail: function (err) {
            console.log(err)
          }
        })
        console.log(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  /**
   * 页面接受参数 
   */
  onLoad: function (options) {},
})

cat_change.json代码】

{
  "navigationBarTitleText": "猫咪卡通变",
  "navigationBarBackgroundColor": "#ffffff",
  "navigationBarTextStyle": "black",
  "backgroundColor": "#eeeeee",
  "backgroundTextStyle": "light",
  "enablePullDownRefresh":false
}

六 完整项目源码地址

gitee地址:https://gitee.com/nanfangzhe/wechat_demo

我是程序员南方者,谢谢你的观看~

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南方者

你的鼓励将驱动我的开源

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

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

打赏作者

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

抵扣说明:

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

余额充值