微信小程序学习笔记--测颜值

使用camera组件

<camera style="height:{{wh}}px;width:100% ;" flash="off"></camera>
/**
     * 页面的初始数据
     */
    data: {
        wh:0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const info = wx.getSystemInfoSync()
        this.setData({
            wh:info.windowHeight
        })
    },

自定义导航栏

app.json中增加"navigationStyle":"custom",使camera充满真个屏幕

{
  "pages":[
    "pages/home/home"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "Weixin",
    "navigationBarTextStyle":"black",
    "navigationStyle":"custom"
  },
  "sitemapLocation": "sitemap.json"
}

绘制按钮

增加三个image标签

<camera style="height:{{wh}}px;width:100% ;" flash="off">
    <view class="box-container">
        <image src='https://patchwiki.biligame.com/images/blhx/thumb/3/33/6aeqc2i8ao68ntotsrqs1y2i7em7kqo.jpg/30px-%E7%9A%87%E5%AE%B6%E6%96%B9%E8%88%9F%C2%B7META%E5%A4%B4%E5%83%8F.jpg'></image>
        <image src='https://patchwiki.biligame.com/images/blhx/thumb/c/c5/p7o2tijt25suhpsj58dy736q4vxsblu.jpg/30px-%E6%B5%B7%E4%BC%A6%E5%A8%9C%C2%B7META%E5%A4%B4%E5%83%8F.jpg'></image>
        <image src='https://patchwiki.biligame.com/images/blhx/thumb/f/fc/phqv7phgcjfrv5vuu6vyngs50gnh2sb.jpg/30px-%E6%A0%BC%E5%A5%88%E6%A3%AE%E7%91%99%C2%B7META%E5%A4%B4%E5%83%8F.jpg'></image>
    </view>
</camera>

修改样式

/* pages/home/home.wxss */
.box-container{
    display: flex;
    justify-content: space-around;
    position: absolute;
    bottom: 50px;
    width: 100%;
}
.box-container image{
    width: 50px;
    height: 50px;
    opacity: 0.7;
}

如果渲染有问题,可以将view替换为cover-view,将image替换为cover-image,对应的css也需要修改。

切换摄像头

增加camera device-position属性

<camera style="height:{{wh}}px;width:100% ;" flash="off" device-position='{{position}}'>
<cover-view class="box-container">
        <cover-image src='https://patchwiki.biligame.com/images/blhx/thumb/3/33/6aeqc2i8ao68ntotsrqs1y2i7em7kqo.jpg/30px-%E7%9A%87%E5%AE%B6%E6%96%B9%E8%88%9F%C2%B7META%E5%A4%B4%E5%83%8F.jpg' bindtap="reverseCamera" ></cover-image>
</cover-view>
</camera>
 data: {
        wh:0,
        position:'back',//摄像头朝向
    },

    reverseCamera(){
        const np = this.data.position === 'front' ? 'back' : 'front'
        this.setData({
            position:np
        })
    },

拍照

 <cover-image src='https://patchwiki.biligame.com/images/blhx/thumb/c/c5/p7o2tijt25suhpsj58dy736q4vxsblu.jpg/30px-%E6%B5%B7%E4%BC%A6%E5%A8%9C%C2%B7META%E5%A4%B4%E5%83%8F.jpg' bindtap="takePhoto"></cover-image>
data: {
        wh:0,
        position:'back',//摄像头朝向
        src:''
    },
    takePhoto(){//拍照
        const ctx = wx.createCameraContext()//创建相机实例对象
        ctx.takePhoto({//执行拍照
            quality:'high',//相片质量
            success:(res)=>{
                this.setData({
                    src:res.tempImagePath//成功获取的照片路径
                })
            },
            fail:()=>{
                console.log('拍照失败')
                this.setData({
                    src:''
                })
            }
        })
    },

从相册选取照片

 <cover-image src='https://patchwiki.biligame.com/images/blhx/thumb/f/fc/phqv7phgcjfrv5vuu6vyngs50gnh2sb.jpg/30px-%E6%A0%BC%E5%A5%88%E6%A3%AE%E7%91%99%C2%B7META%E5%A4%B4%E5%83%8F.jpg' bindtap="choosePhoto"></cover-image>
 choosePhoto(){
        wx.chooseImage({
          count: 1,//选取照片个数
          sizeType:['original'],//类型-原始尺寸
          sourceType:['album'],//照片来源
          success:(res)=>{
              if(res.tempFilePaths.length > 0){
                this.setData({
                    src:res.res.tempFilePaths[0]//成功获取的照片路径
                })
              }
          },
          fail:()=>{
            console.log('选择失败')
          }
        })
    },

展示选取的照片

增加数据isShowPic,默认为false,当选取或者拍照后设置为true。

<camera style="height:{{wh}}px;width:100% ;" flash="off" device-position='{{position}}' wx:if="{{isShowPic===false}}">
    <cover-view class="box-container">
    </cover-view>
</camera>

<view wx:else >
    <image src="{{src}}" style="height: {{wh}}px;width: 100%;" mode="aspectFill"></image>
</view>
data: {
        wh:0,
        position:'back',//摄像头朝向
        src:'',
        isShowPic:false,//是否展示照片
    },
    choosePhoto(){
        wx.chooseImage({
          count: 1,//选取照片个数
          sizeType:['original'],//类型-原始
          sourceType:['album'],//照片来源
          success:(res)=>{
              if(res.tempFilePaths.length > 0){
                this.setData({
                    src:res.tempFilePaths[0],//成功获取的照片路径
                    isShowPic:true
                })

              }
          },
          fail:()=>{
            console.log('选择失败')
            this.setData({
                src:'',
                isShowPic:false
            })
          }
        })
    },

重新选择照片

<view wx:else >
    <image src="{{src}}" style="height: {{wh}}px;width: 100%;" mode="aspectFill"></image>
    <button type="warn" class="reChooose" bindtap="reChooose">重新选择照片</button>
</view>
  reChooose(){//重选照片
        this.setData({
            isShowPic:false,
            src:''
        })
    },
.reChooose{
    position: fixed;
    bottom: 30px;
    left:50%;
    transform: translate(-50%);
    box-shadow: 0px 1px 5px #555;
}

测颜值函数

  getFaceInfo(){//测颜值函数

    },
choosePhoto(){
        wx.chooseImage({
          count: 1,//选取照片个数
          sizeType:['original'],//类型-原始
          sourceType:['album'],//照片来源
          success:(res)=>{
              if(res.tempFilePaths.length > 0){
                this.setData({
                    src:res.tempFilePaths[0],//成功获取的照片路径
                    isShowPic:true
                },()=>{
                    this.getFaceInfo() //	确定照片后调用测颜值函数
                })

              }
          },
          fail:()=>{
            console.log('选择失败')
            this.setData({
                src:'',
                isShowPic:false
            })
          }
        })
    },

在百度API开放平台注册账号,在管理中心中,人脸识别里创建应用,得到key
在小程序加载时进行百度api鉴权,并保存全局数据access_token。
client_id和client_secret可在自己创建的应用中获取。

//全局共享数据
  globalData:{
    access_token:''
  },
  /**
   * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
   */
  onLaunch: function () {
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=111111111111&client_secret=111111111111111111111',
      method:'POST',
      success:(res)=>{
        this.globalData.access_token = res.data.access_token
      },
      fail:()=>{
        wx.showToast({
          title: '鉴权失败',
        })
      }
    })
  },

在页面中使用access_token

 getFaceInfo(){//测颜值函数
        const app = getApp()//引用全局数据
        console.log(app.access_token)
    },

完善测颜值函数

先将照片转换为base64格式,然后再请求对应api

 getFaceInfo(){//测颜值函数
        const app = getApp()//引用全局数据
        const token = app.globalData.access_token
        if(!token) return wx.showToast({
          title: '鉴权失败',
        })
        //图片格式转换
        const fileManager = wx.getFileSystemManager()
        const filestr = fileManager.readFileSync(this.data.src,'base64')
        //请求百度api
        wx.request({
            method:'POST',
            url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' + token,
            header:{
                'Content-Type':'application/json'
            },
            data:{
                image_type:'BASE64',
                image:filestr,
                face_field:'age,expression,face_shape,gender,glasses,landmark,landmark150,quality,eye_status,emotion,face_type,mask,spoofing'
            },
            success:(res)=>{
                console.log(res)
                if(!res.data.result || res.data.resule.face_num<=0){
                    return wx.showToast({
                      title: '未检测到人脸',
                    })
                }
                this.setData({
                    faceInfo:res.data.resule.face_list[0]
                })
            },
            fail:()=>{
                wx.showToast({
                  title: '颜值检测失败',
                })
            }
        })
    },

api好像需要花钱,用几次报了个错误,决定自己造数据了,反正是测试QAQ

数据结构渲染

<view wx:else >
    <image src="{{src}}" style="height: {{wh}}px;width: 100%;display: block;" mode="aspectFill"></image>
    <view class="faceinfo_box">
        <view class="face_row">
            <text>年龄:{{faceInfo.age}}岁</text>
            <text>性别:{{faceInfo.gender.type}}</text>
        </view>
        <view class="face_row">
            <text>颜值:{{faceInfo.beauty}}</text>
            <text>表情:{{faceInfo.expression.type}}</text>
        </view>
        <view class="face_row">
            <text>眼镜:{{faceInfo.glasses.typ}}岁</text>
            <text>情绪:{{faceInfo.emotion.type}}</text>
        </view>
    </view>
    <button type="warn" class="reChooose" bindtap="reChooose">重新选择照片</button>
</view>
.faceinfo_box{
    position: absolute;
    left: 50%;
    top:50%;
    transform: translate(-50% ,-50%);
    width: 80%;
    height: 200px;
    background-color: rgba(255,255,255,0.7);
    border-radius: 5px;
    box-shadow: 0px 1px 1px #eee;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
}
.face_row{
    display: flex;
    justify-content: space-around;
    font-size: 13px;
}

信息跳变

<view class="faceinfo_box" wx:if="{{isShowBox}}">

数据请求成功设置isShowBox:true

this.setData({
            isShowBox:true,
           })

重选后设置isShowBox:true

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值