生命的意义在于折腾

微信小程序拍照截取指定区域图片

效果图

实现步骤

  1. 获取拍摄图片(wx.createCameraContext())
  2. canvas绘制拍摄图片(wx.wx.createCanvasContext())
  3. canvas导出指定区域 (wx.canvasToTempFilePath())

话不多少 直接上代码

wxml

html

1<camera wx:if='{{isShowCamera}}' class="camera-box" devic-position="width" flash="off" style='width:{{windowWidth}}px; height:{{windowHeight}}px;'>
2  <cover-view class='camerabgImage'>
3    <cover-view class="active">
4      <cover-image class="active-image" src="https://oss.mukang.net/blog/2020/12/0716073342969601272.png"></cover-image>
5      <cover-view class="text">请将VIN码放入框中,点击拍照进行识别</cover-view>
6    </cover-view>
7    <cover-view class="btn" bindtap="takePhotoAction">
8      <cover-view class="button"></cover-view>
9    </cover-view>
10  </cover-view>
11</camera>
12
13<canvas wx:if='{{isShowImage}}' canvas-id="image-canvas" id="canvas"
14        style='width:{{windowWidth}}px; height:{{windowHeight}}px;'></canvas>

wxss

css

1
2 
3.camera-box {
4  width: 100vw;
5  height: 100vh
6}
7
8.camera-box .camerabgImage {
9  position: fixed;
10  top: 0;
11  left: 0;
12  right: 0;
13  bottom: 0
14}
15
16.camera-box .camerabgImage .active {
17  position: absolute;
18  top: 400rpx;
19  left: 36rpx;
20  right: 36rpx
21}
22
23.camera-box .camerabgImage .active-image {
24  display: block;
25  width: 680rpx;
26  height: 280rpx
27}
28
29.camera-box .camerabgImage .text {
30  text-align: center;
31  margin-top: 56rpx;
32  margin-bottom: 240rpx;
33  font-size: 28rpx;
34  font-weight: 400;
35  color: #D9D9D9;
36  line-height: 40rpx
37}
38
39.camera-box  .btn {
40  position: fixed;
41  left: 50%;
42  bottom: 120rpx;
43  margin-left: -55rpx;
44  width: 110rpx;
45  height: 110rpx;
46  border-radius: 50%;
47  background: #fff;
48  border: 6rpx solid#fff;
49  display: flex;
50  align-items: center;
51  justify-content: center;
52}
53
54.camera-box   .btn .button {
55  width: 102rpx;
56  height: 102rpx;
57  border-radius: 50%;
58  border: 4rpx solid#000
59}
60.canvas{
61  position: absolute;
62  top: -10000rpx;
63  left: -10000rpx;
64}

js

javascript

1// 创建页面实例对象
2Page({
3  // 页面的初始数据
4  data: {
5    isShowCamera: false,
6    isShowImage: true,
7    image: '',
8    windowWidth: '',
9    windowHeight: ''
10  },
11  onLoad() {
12    /**
13     * @name: 创建 拍照  获取  可视区域宽高
14     * @description:
15     * @version: 
16     * @author: WangJian
17     * @time: 2021-01-22 10:34:39
18     */
19    this.ctx = wx.createCameraContext()
20    let {windowWidth, windowHeight} = wx.getSystemInfoSync()
21    this.setData({windowWidth, windowHeight})
22  },
23  onShow: function () {
24    /**
25     * @name: 获取摄像头权限
26     * @description: 授权失败返回上一页
27     * @version: 
28     * @author: WangJian
29     * @time: 2021-01-22 10:35:28
30     */
31    var that = this
32    wx.authorize({
33      scope: 'scope.camera',
34      success: function (res) {
35        that.setData({
36          isShowCamera: true,
37        })
38      },
39      fail: function (res) {
40        console.log("" + res);
41        wx.showModal({
42          title: '请求授权您的摄像头',
43          content: '如需正常使用此小程序功能,请您按确定并在设置页面授权用户信息',
44          confirmText: '确定',
45          success: res => {
46            if (res.confirm) {
47              wx.openSetting({
48                success: function (res) {
49                  console.log('成功');
50                  console.log(res);
51                  if (res.authSetting['scope.camera']) { //设置允许获取摄像头
52                    console.log('设置允许获取摄像头')
53                    wx.showToast({
54                      title: '授权成功',
55                      icon: 'success',
56                      duration: 1000
57                    })
58                    that.setData({
59                      isShowCamera: true,
60                    })
61
62                  } else { //不允许
63                    wx.showToast({
64                      title: '授权失败',
65                      icon: 'none',
66                      duration: 1000
67                    })
68                    wx.navigateBack({delta: 1})
69                  }
70                }
71              })
72            } else { //取消
73              wx.showToast({
74                title: '授权失败',
75                icon: 'none',
76                duration: 1000
77              })
78              wx.navigateBack({delta: 1})
79
80            }
81          }
82        })
83
84      }
85    })
86  },
87  /**
88   * @name: 拍照
89   * @description: 详细参数可参考官方文档
90   * @version: 
91   * @author: WangJian
92   * @time: 2021-01-22 10:36:17
93   */
94  takePhotoAction: function () {
95    var that = this
96    that.ctx.takePhoto({
97      quality: 'high', //高质量
98      success: (res) => {
99        that.loadTempImagePath(res.tempImagePath);
100      },
101      fail(error) {
102        console.log(error)
103      }
104    })
105  },
106  /**
107   * @name: canvas绘制拍照图片
108   * @description:
109   * @version: 
110   * @author: WangJian
111   * @time: 2021-01-22 10:36:45
112   */
113  loadTempImagePath: function (options) {
114    var that = this
115    wx.getSystemInfo({
116      success: function (res) {
117        // px与rpx之间转换的公式:px = rpx / 750 * wx.getSystemInfoSync().windowWidth;
118        var image_x = 36 / 750 * that.data.windowWidth; // x 坐标位置
119        var image_y = 400 / 750 * that.data.windowWidth; // y 坐标位置
120        var image_width = 680 / 750 * that.data.windowWidth; // 图片宽度
121        var image_height = 280 / 750 * that.data.windowWidth; // 图片高度
122        console.log(image_x, image_y, image_width, image_height)
123        wx.getImageInfo({
124          src: options,
125          success: function (res) {
126            that.setData({
127              isShowImage: true,
128            })
129            that.canvas = wx.createCanvasContext("image-canvas", that)
130            //过渡页面中,图片的路径坐标和大小
131            that.canvas.drawImage(options, 0, 0, that.data.windowWidth, that.data.windowHeight)
132            wx.showLoading({
133              title: '数据处理中...',
134              icon: 'loading',
135              duration: 10000
136            })
137            that.canvas.draw()
138            setTimeout(function () {
139              wx.canvasToTempFilePath({ //裁剪对参数
140                canvasId: "image-canvas",
141                x: image_x, //画布x轴起点
142                y: image_y, //画布y轴起点
143                width: image_width, //画布宽度
144                height: image_height, //画布高度
145                destWidth: image_width, //输出图片宽度
146                destHeight: image_height, //输出图片高度
147                success: function (res) {
148                  // 生成本地文件路径  可上传服务器
149                  console.log(res.tempFilePath);
150                  that.setData({
151                    image: res.tempFilePath,
152                  })
153                  // 生成base64 图片格式
154                  wx.hideLoading()
155                  console.log(res.tempFilePath);
156                  wx.getFileSystemManager().readFile({
157                    filePath: res.tempFilePath,  //图片路径
158                    encoding: 'base64', //编码格式
159                    success: result => { //成功的回调
160                      console.log('data:image/png;base64,' + result.data)
161                    },
162                    fail: function (e) {
163                      wx.hideLoading()
164                      wx.showToast({
165                        title: '出错啦...',
166                        icon: 'loading'
167                      })
168                    }
169                  });
170                }
171              })
172            }, 1000);
173          }
174        })
175      }
176    })
177  },
178});
阅读量:2513发布日期:2021-06-11 17:06:22

博客描述

微信小程序拍照截取指定区域图片

留言板