«

微信小程序如何实现自定义拍摄组件

时间:2024-4-15 08:57     作者:韩俊     分类: Javascript


这篇“微信小程序如何实现自定义拍摄组件”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“微信小程序如何实现自定义拍摄组件”文章吧。

摄像头组件(wxml)

<!-- 拍照功能 自定义摄像头
          bindtap:takePhotoDepot----从图库获取
          bindtap:takePhoto----拍照
          bindtap:takeFrontBack---转换摄像头
 -->

<view wx:if="{{useCameraTakePhoto}}" class="scan_view">
    <!-- 摄像头组件 -->
    <camera device-position="back" mode="normal" flash="off" binderror="error" device-position="{{phopo_camera?'front':'back'}}" >
      <!-- 摄像头返回按钮 -->
       <cover-view class="camera_view">
         <cover-view class="back" bindtap="closeCamera">
           返回
         </cover-view>
         <cover-view >
           <cover-image bindtap="takePhotoDepot" class="take_photo_depot"src="../../images/phopo.png"></cover-image>
            <cover-image bindtap="takePhoto" class="take_photo" src="../../images/starCamera.png"></cover-image>
            <cover-image bindtap="takeFrontBack" class="take_photo_frontBack" src="../../images/transition.png"></cover-image>
          </cover-view>
        </cover-view>
      </camera>
    </view>

唤醒摄像头组件(wxml)

<view class="conPhopo_camera" bindtap="changePhoto">
        <text>拍摄照片</text>
</view>

自定义展示拍照后的图片(wxml)

<view  wx:if="{{tempFileList.length>0}}">
<!-- 图片缩小状态  -->
        <view  wx:for="{{tempFileList}}" wx:key="index">
          <view class="fileShow" wx:if="{{item.type ==='image' && item.thumb}}">  
            <image  src="data:image/png;base64,{{item.thumb}}" alt="" bindtap="changeMinImage" data-item="{{item}}" data-index="{{index}}" data-src='{{item.thumb}}' data-thumb='true' />
          </view>
          <view class="fileShow" wx:elif="{{item.type ==='image' &&item.path}}">
            <image  src="{{item.path}}" alt="" bindtap="changeMinImage" data-item="{{item}}" data-index="{{index}}" data-src='{{item.path}}' />
          </view>
        </view> 
<!-- 点击缩小图片放大展示-->
      <view wx:if="{{isSrc}}" >
          <view wx:if="{{thumb=='true'}}">
            <image  src="data:image/png;base64,{{src.src}}" alt="" />
          </view>
          <view wx:elif="{{thumb!='true'}}">
            <image  src="{{src.src}}" />
          </view>
          <i class="iconfont .icon-quxiao" bindtap="changeMaxImage" ></i>
        </view> 
</view>

接下来就是关键了,主要还得看js怎么实现

实现的方法

打开摄像头并且拍照

// 控制摄像头是否显示
  changePhoto(e) {
    const {
      currentTab,
      isVideoModel,
    } = this.data;
     let casePhotoList = this.data.casePhotoList; 
     let facePhotoList = this.data.facePhotoList;
     let abnormalPhotoList = this.data.abnormalPhotoList; 
     let accessoryPhotoList = this.data.accessoryPhotoList; 
    const that = this;
    if (currentTab == 2) {
        // 摄像开始
      wx.chooseVideo({
        count: 1,
        mediaType: ['video'],
        sourceType: ['camera'],
        success: (res) => {
          // 添加formData
          let formData = new FormData();
          formData.append('type', currentTab);
          let src = {
            tempVideoPath: res.tempFilePath,
            size: res.size
          };
          abnormalPhotoList.push(src);
          that.setData({
            abnormalPhotoList: abnormalPhotoList,
            useCameraTakePhoto: false,
            isVideoModel: !isVideoModel,
          });
          for (const iterator of abnormalPhotoList) {
            formData.appendFile('files[]', iterator.tempVideoPath);
          }
          let tempFilesPath = abnormalPhotoList.map(item => ({
            type: item.type ? item.type : 'video', // 文件类型
            path: item.tempVideoPath, // 文件本地路径
            size: item.size ? item.size : '', // 文件大小
          }))
          let {
            videoTempFileList
          } = that.data;
          that.setData({
            videoTempFileList: videoTempFileList.concat(tempFilesPath)
          })
          let data = formData.getData();
            // 2.2.异步上传,发送请求 这里就不写了
          ...
        }
      })
    } else {
       this.setData({
         useCameraTakePhoto: true,
         isjustSrc: e.currentTarget.dataset.isphoto
       })
      // 拍照开始
         wx.chooseMedia({
           success: res => {
             let newTempFiles = {
               tempImagePath:res.tempFiles[0].tempFilePath,
               type:res.tempFiles[0].fileType,
               size:res.tempFiles[0].size
             }
             let formData = new FormData();
             formData.append('type', currentTab);
             if (currentTab == 0) {
                casePhotoList.push(res.tempFiles[0])
                that.setData({
                  casePhotoList: casePhotoList,
                  useCameraTakePhoto: false
                })
                for (const iterator of newTempFiles) {
                 console.log(newTempFiles,244);
                 formData.appendFile('files[]', newTempFiles.tempImagePath);
                 }
               // 2.选择文件后,页面显示选择的文件的本地临时文件,且进行异步上传
               // 2.1.返回选定文件的本地文件路径列表,可以作为img标签的src属性显示图片
                let tempFilesPath = casePhotoList.map(item => ({
                  type: newTempFiles.fileType ? newTempFiles.fileType : 'image', // 文件类型
                  path: newTempFiles.tempImagePath, // 文件本地路径
                  size: newTempFiles.size ? newTempFiles.size : '', // 文件大小
                }))
               let {
                 tempFileList
               } = that.data;
               console.log(tempFileList,257);
               that.setData({
                 tempFileList: tempFileList.concat(newTempFiles)
               },()=>{console.log(that.data);})
             } else if (currentTab == 1) {
               facePhotoList.push(...newTempFiles)
               that.setData({
                 facePhotoList: facePhotoList,
                 useCameraTakePhoto: false
               })
               for (const iterator of [...newTempFiles]) {
                 formData.appendFile('files[]', iterator.tempImagePath);
               }
               let tempFilesPath = facePhotoList.map(item => ({
                 type: item.type ? item.type : 'image', // 文件类型
                 path: item.tempImagePath, // 文件本地路径
                 size: item.size ? item.size : '', // 文件大小
               }))
               let {
                 facetTempFileList
               } = that.data;
               that.setData({
                 facetTempFileList: facetTempFileList.concat(tempFilesPath)
               })
             } else if (currentTab == 3) {
               accessoryPhotoList.push(...newTempFiles)
               that.setData({
                 accessoryPhotoList: accessoryPhotoList,
                 useCameraTakePhoto: false
               })
               for (const iterator of accessoryPhotoList) {
                 formData.appendFile('files[]', iterator.tempImagePath);
               }
             }
             let data = formData.getData();
             // 2.2.异步上传,发送请求 上传照片
           }
         })
    }
  },

转换摄像头

// 转换摄像头
  takeFrontBack() {
    const {
      phopo_camera
    } = this.data
    this.setData({
      phopo_camera: !phopo_camera
    })
  },

打开手机相册

// 打开手机相册
takePhotoDepot() {
    const that = this;
    const {
      currentTab,
    } = this.data;
    let casePhotoList = this.data.casePhotoList; 
    let facePhotoList = this.data.facePhotoList; 
    let abnormalPhotoList = this.data.abnormalPhotoList; 
    let accessoryPhotoList = this.data.accessoryPhotoList; 
    if (currentTab == 2) {
      wx.chooseVideo({
        count: 1,
        mediaType: ['video'],
        sourceType: ['album'],
        success: (res) => {
          let src = {
            tempVideoPath: res.tempFilePath,
            size: res.size
          };
          abnormalPhotoList.push(src);
          this.setData({
            abnormalPhotoList: abnormalPhotoList,
            useCameraTakePhoto: false,
            isVideoModel: false,
          });
        }
      })
    } else {
      wx.chooseMedia({
        count: 1, // 选择数量
        mediaType: ['image'], // 文件类型 图片
        sourceType: ['album'], // 图片来源  album:从相册选
        success: res => {
          let formData = new FormData();
          formData.append('type', currentTab);
          let src = {
            tempImagePath: res.tempFiles[0].tempFilePath,
            size: res.tempFiles[0].size,
            fileType: res.tempFiles[0].fileType,
          }
          if (currentTab == 0) {
            casePhotoList.push(src)
            that.setData({
              casePhotoList: casePhotoList,
              useCameraTakePhoto: false
            })
            for (const iterator of casePhotoList) {
              formData.appendFile('files[]', iterator.tempImagePath);
            }
            // 2.选择文件后,页面显示选择的文件的本地临时文件,且进行异步上传
            // 2.1.返回选定文件的本地文件路径列表,可以作为img标签的src属性显示图片
            let tempFilesPath = casePhotoList.map(item => ({
              type: item.type ? item.type : 'image', // 文件类型
              path: item.tempImagePath, // 文件本地路径
              size: item.size ? item.size : '', // 文件大小
            }))
            let {
              tempFileList
            } = that.data;
            that.setData({
              tempFileList: tempFileList.concat(tempFilesPath)
            })
          } else if (currentTab == 1) {
            facePhotoList.push(src)
            that.setData({
              facePhotoList: facePhotoList,
              useCameraTakePhoto: false
            })
            for (const iterator of [facePhotoList]) {
              formData.appendFile('files[]', iterator.tempImagePath);
            }
            let tempFilesPath = facePhotoList.map(item => ({
              type: item.type ? item.type : 'image', // 文件类型
              path: item.tempImagePath, // 文件本地路径
              size: item.size ? item.size : '', // 文件大小
            }))
            let {
              facetTempFileList
            } = that.data;
            that.setData({
              facetTempFileList: facetTempFileList.concat(tempFilesPath)
            })
          } else if (currentTab == 3) {
            accessoryPhotoList.push(src)
            that.setData({
              accessoryPhotoList: accessoryPhotoList,
              useCameraTakePhoto: false
            })
            for (const iterator of accessoryPhotoList) {
              formData.appendFile('files[]', iterator.tempImagePath);
            }
          }
          let data = formData.getData();
          // 2.2.异步上传,发送请求 上传图片
          ...
            
        },
      })
    }
  },

关闭相机 

//关闭系统相机页面
  closeCamera: function () {
    this.setData({
      useCamera: false,
      useCameraTakePhoto: false,
    })
  },

点击小图片放大功能

// 点击拍照后的图片
  changeMinImage(e) {
    wx.showLoading({
      title: '加载中',
      icon: 'loading'
    })
    let item = e.target.dataset.item;
    const that = this;
    // 1. 预览分为本地预览和下载预览, 进行判断
    if (item.type === 'image' && item.path) {
      // 1.1.本地预览,在新页面中全屏预览图片
      wx.previewImage({
        urls: [item.path], // 需要预览的图片http链接列表 Array.<string>
        success() {
          wx.hideLoading()
        },
        fail() {
          wx.showToast({
            title: '预览失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else {
      // 1.2.下载预览,下载文件资源到本地,单次下载允许的最大文件为200MB
      wx.downloadFile({
        url: `${app.host}order/attachments/${item.store_name}/download`,
        header: {
          'Content-Type': 'application/json',
          'token': '自己的Token'
        },
        success(res) {
          wx.hideLoading()
          if (item.type == "video") {
            that.setData({
              isSrc: true,
              src: res.tempFilePath,
            })
            wx.openVideoEditor({
              filePath: res.tempFilePath,
              success(res) {}
            })
          } else {
            wx.previewImage({ // 在新页面中全屏预览图片
              urls: [res.tempFilePath], // 需要预览的图片http链接列表 Array.<string>
            })
          }

        },
        fail() {
          wx.showToast({
            title: '预览失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },

放大后的图片关闭

// 点击放大后的图片进行关闭
  changeMaxImage() {
    this.setData({
      isSrc: false,
      src: {}
    })
  },

标签: javascript 微信小程序

热门推荐