微信小程序拍照截取指定区域图片(话不多说,直接上代码)

效果图

wxml

<camera wx:if='{{isShowCamera}}' class="camera-box" devic-position="width" flash="off" style='width:{{windowWidth}}px; height:{{windowHeight}}px;'>
  <cover-view class='camerabgImage'>
    <cover-view class="active">
      <cover-image class="active-image" src="https://oss.nodekoa.com/blog/2020/12/0716073342969601272.png"></cover-image>
      <cover-view class="text">请将VIN码放入框中,点击拍照进行识别</cover-view>
      <cover-view class="btn" bindtap="takePhotoAction">
        <cover-view class="button"></cover-view>
      </cover-view>

    </cover-view>
  </cover-view>
</camera>

<canvas wx:if='{{isShowImage}}' canvas-id="image-canvas"
        style='width:{{windowWidth}}px; height:{{windowHeight}}px;'></canvas>

wxss

.camera-box {
  width: 100vw;
  height: 100vh
}

.camera-box .camerabgImage {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0
}

.camera-box .camerabgImage .active {
  position: absolute;
  top: 400rpx;
  left: 36rpx;
  right: 36rpx
}

.camera-box .camerabgImage .active-image {
  display: block;
  width: 680rpx;
  height: 280rpx
}

.camera-box .camerabgImage .text {
  text-align: center;
  margin-top: 56rpx;
  margin-bottom: 240rpx;
  font-size: 28rpx;
  font-weight: 400;
  color: #D9D9D9;
  line-height: 40rpx
}

.camera-box .camerabgImage .btn {
  width: 110rpx;
  height: 110rpx;
  border-radius: 50%;
  background: #fff;
  border: 6rpx solid#fff;
  margin: 0 auto
}

.camera-box .camerabgImage .btn .button {
  width: 102rpx;
  height: 102rpx;
  border-radius: 50%;
  border: 4rpx solid#000
}

js

// 获取全局应用程序实例对象
// const app = getApp();

// 创建页面实例对象
Page({
  // 页面的初始数据
  data: {
    isShowCamera: false,
    isShowImage: true,
    image: '',
    windowWidth: '',
    windowHeight: ''
  },
  onLoad() {
    this.ctx = wx.createCameraContext()
    let {windowWidth, windowHeight} = wx.getSystemInfoSync()
    this.setData({windowWidth, windowHeight})
  },
  onShow: function () {
    var that = this
    wx.authorize({
      scope: 'scope.camera',
      success: function (res) {
        that.setData({
          isShowCamera: true,
        })
      },
      fail: function (res) {
        console.log("" + res);
        wx.showModal({
          title: '请求授权您的摄像头',
          content: '如需正常使用此小程序功能,请您按确定并在设置页面授权用户信息',
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              wx.openSetting({
                success: function (res) {
                  console.log('成功');
                  console.log(res);
                  if (res.authSetting['scope.camera']) { //设置允许获取摄像头
                    console.log('设置允许获取摄像头')
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    that.setData({
                      isShowCamera: true,
                    })

                  } else { //不允许
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                    wx.navigateBack({delta: 1})
                  }
                }
              })
            } else { //取消
              wx.showToast({
                title: '授权失败',
                icon: 'none',
                duration: 1000
              })
              wx.navigateBack({delta: 1})

            }
          }
        })

      }
    })
  },
  /**
   * 拍照
   */
  takePhotoAction: function () {
    var that = this
    that.ctx.takePhoto({
      quality: 'high', //高质量
      success: (res) => {
        that.loadTempImagePath(res.tempImagePath);
      },
      fail(error) {
        console.log(error)
      }
    })
  },
  loadTempImagePath: function (options) {
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        // px与rpx之间转换的公式:px = rpx / 750 * wx.getSystemInfoSync().windowWidth;
        // 矩形的位置
        // var image_x = 0;
        // var image_y = 0;
        // var image_width = that.data.windowWidth;
        // var image_height = that.data.windowHeight
        var image_x = 36 / 750 * wx.getSystemInfoSync().windowWidth;
        var image_y = 400 / 750 * wx.getSystemInfoSync().windowWidth;
        var image_width = 680 / 750 * wx.getSystemInfoSync().windowWidth;
        var image_height = 280 / 750 * wx.getSystemInfoSync().windowWidth;
        console.log(image_x, image_y, image_width, image_height)
        wx.getImageInfo({
          src: options,
          success: function (res) {
            that.setData({
              isShowImage: true,
            })
            that.canvas = wx.createCanvasContext("image-canvas", that)
            //过渡页面中,图片的路径坐标和大小
            that.canvas.drawImage(options, 0, 0, that.data.windowWidth, that.data.windowHeight)
            wx.showLoading({
              title: '数据处理中...',
              icon: 'loading',
              duration: 10000
            })
            // 这里有一些很神奇的操作,总结就是MD拍出来的照片规格居然不是统一的过渡页面中,对裁剪框的设定
            that.canvas.setStrokeStyle('black')
            that.canvas.strokeRect(image_x, image_y, image_width, image_height)
            that.canvas.draw()
            setTimeout(function () {
              wx.canvasToTempFilePath({ //裁剪对参数
                canvasId: "image-canvas",
                x: image_x, //画布x轴起点
                y: image_y, //画布y轴起点
                width: image_width, //画布宽度
                height: image_height, //画布高度
                destWidth: image_width, //输出图片宽度
                destHeight: image_height, //输出图片高度
                success: function (res) {
                  that.setData({
                    image: res.tempFilePath,
                  })
                  //清除画布上在该矩形区域内的内容。
                  // that.canvas.clearRect(0, 0, that.data.width, that.data.height)
                  // that.canvas.drawImage(res.tempFilePath, image_x, image_y, image_width, image_height)
                  // that.canvas.draw()
                  wx.hideLoading()

                  console.log(res.tempFilePath);
                  wx.getFileSystemManager().readFile({
                    filePath: res.tempFilePath,  //图片路径
                    encoding: 'base64', //编码格式
                    success: result => { //成功的回调
                      console.log('data:image/png;base64,' + result.data)
                  //在此可进行网络请求

                },
                fail: function (e) {
                  wx.hideLoading()
                  wx.showToast({
                    title: '出错啦...',
                    icon: 'loading'
                  })

                }
              });
            }, 1000);
          }
        })
      }
    })
  },

});

  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值