微信小程序调用摄像头实现拍照

微信小程序开发文档:https://developers.weixin.qq.com/miniprogram/dev/component/camera.html
首先,需要用户授权摄像头权限,这一步是必须的
具体步骤:

  1. 获取用户当前授权状态,看是否已经授权,如果已经授权直接显示摄像头
  2. 如果用户还没有授权,则调起授权弹框,用户允许授权则显示摄像头
  3. 如果用户不允许,则提示用户去设置页面打开摄像头权限

用户授权之后,就可以进行拍摄了,微信的camera组件无法显示为圆形,我这里是用一张图片遮盖了
上代码:
wxml:

<view class='camera'>
  <image src="/images/border.png" mode="widthFix"></image>
  <camera wx:if="{{isAuth}}" device-position="back" flash="off" binderror="error"></camera>
</view>
<button class="takePhoto" type="primary" bindtap="takePhoto">拍照</button>

wxss:

.camera {
  width: 430rpx;
  height: 430rpx;
  border-radius: 50%;
  margin: 20px auto 0;
  position: relative;
}

.camera image {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 10;
}

.camera camera {
  width: 428rpx;
  height: 428rpx;
}

button.takePhoto:not([size='mini']) {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100vw;
  height: 90rpx;
  border-radius: 0;
}

js:

Page({
  data: {
    isAuth: false,
    src: ''
  },
  onLoad() {
    const _this = this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.camera']) {
          // 用户已经授权
          _this.setData({
            isAuth: true
          })
        } else {
          // 用户还没有授权,向用户发起授权请求
          wx.authorize({
            scope: 'scope.camera',
            success() { // 用户同意授权
              _this.setData({
                isAuth: true
              })
            },
            fail() { // 用户不同意授权
              _this.openSetting().then(res => {
                _this.setData({
                  isAuth: true
                })
              })
            }
          })
        }
      },
      fail: res => {
        console.log('获取用户授权信息失败')
      }
    })
  },

  // 打开授权设置界面
  openSetting() {
    const _this = this
    let promise = new Promise((resolve, reject) => {
      wx.showModal({
        title: '授权',
        content: '请先授权获取摄像头权限',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success(res) {
                if (res.authSetting['scope.camera']) { // 用户打开了授权开关
                  resolve(true)
                } else { // 用户没有打开授权开关, 继续打开设置页面
                  _this.openSetting().then(res => {
                    resolve(true)
                  })
                }
              },
              fail(res) {
                console.log(res)
              }
            })
          } else if (res.cancel) {
            _this.openSetting().then(res => {
              resolve(true)
            })
          }
        }
      })
    })
    return promise;
  },

  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath
        })
        wx.previewImage({
          current: res.tempImagePath, // 当前显示图片的http链接
          urls: [res.tempImagePath] // 需要预览的图片http链接列表
        })
      }
    })
  }
})
### 实现 UniApp 微信小程序调用摄像头功能 在 UniApp 中开发微信小程序实现调用摄像头的功能主要依赖于 `uni-camera` 组件以及相应的 API 接口。此组件允许开发者轻松集成摄像头访问权限,并执行诸如拍照或录制视频的操作。 #### 创建页面结构 为了启动摄像头,在页面布局文件 (如 `.vue`) 中引入 `<camera>` 标签来定义显示区域: ```html <template> <view class="content"> <!-- Camera component --> <camera device-position="back" flash="off" @error="handleError"></camera> <!-- Capture button --> <button type="primary" @click="takePhoto">拍摄</button> <!-- Preview image after capture --> <image v-if="photoPath" :src="photoPath" mode="aspectFit"></image> </view> </template> ``` 上述代码片段展示了如何配置相机方向 (`device-position`) 及闪光灯模式 (`flash`) 属性,同时也设置了错误处理事件监听器[@error] 和用于触发照片捕捉的方法 [@click][^1]. #### 编写 JavaScript 方法 接下来是在脚本部分编写逻辑函数以控制摄像行为: ```javascript export default { data() { return { photoPath: '' }; }, methods: { async takePhoto() { try { const res = await uni.chooseImage({ count: 1, sourceType: ['camera'] }); this.photoPath = res.tempFilePaths[0]; } catch (err) { console.error('Failed to take a picture:', err); } }, handleError(err) { console.warn(`Camera encountered an error: ${JSON.stringify(err)}`); } } } ``` 这段代码实现了当用户点击“拍摄”按钮时打开摄像头界面让用户选取图片,并将选中的临时路径保存至 `data()` 的属性中以便后续展示预览图像[^2]. 请注意,实际应用过程中可能还需要考虑更多细节问题,比如权限请求、设备兼容性检测等。此外,对于更复杂的需求(例如连续录像),可以查阅官方文档获取更多信息和支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值