微信小程序——拍照、压缩转换base64不留存照片在本地相册 ...

标签:程序,拍照,压缩,转换,不留,留存,存照,照片,本地 发布时间:2021年04月20日 点击51

前言

通常使用wx.chooseImage这个api去拍照时通常会留下照片在本地相册,在一些需求情况下不必要留存照片所以在这里我们使用另一个wx.createCameraContext()

展示结果

js

var compress = require('../../../../libs/compress.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showCamera: false,
    ctx: null, //拍照实例
    device: 'back',
	Img1:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      ctx: wx.createCameraContext()
    }); //初始化相机实例
  },
  
  //拍照
  takePhotoZ: function () {
    let maxSize = 400;
    let dWidth = wx.getSystemInfoSync().windowWidth;
    let that = this;
    that.data.ctx.takePhoto({
      quality: 'normal',
      success: (res) => {
        console.log(res)
        var v = res.tempImagePath
        wx.getFileInfo({
          filePath: res.tempImagePath,
          success: function (res) {
            var cW = res.width, cH = res.height;
            that.cWidth = cW;
            that.cHeight = cH;
          }
        })
        console.log(res)
        compress.getLessLimitSizeImage('canvas', v, maxSize, dWidth, function (img) {
          wx.getFileInfo({
            filePath: img,
            success: function (res) {
              console.log('压缩后:' + res.size / 1024 + 'kb')
              var FSM = wx.getFileSystemManager();
              FSM.readFile({
                filePath: img,
                encoding: "base64",
                success: (data) => {
                  let Working = data.data;
                  that.getBase64ImageUrlF2(Working, that.data.index)
                }
              });
            }
          })
        })
      },
      fail: (res) => {
      },
      complete: (res) => { },
    });
  },

  //身份证压缩
  chooseImgF2(e) {
    var index = e.currentTarget.dataset.index
    let maxSize = 400;
    let dWidth = wx.getSystemInfoSync().windowWidth;
    console.log(dWidth);
    let that = this;
    wx.chooseImage({
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      count: 1,
      success: function (res) {
        wx.showLoading({
          title: '加载中',
          mask: true
        })
        // 返回选定图片的本地文件列表,tempFilePaths可以作为img标签的src列表
        // 当一次选择多张图片的情况
        var v = res.tempFilePaths[0]
        wx.getFileInfo({
          filePath: res.tempFilePaths[0],
          success: function (res) {
            var cW = res.width, cH = res.height;
            that.cWidth = cW;
            that.cHeight = cH;
          }
        })
        compress.getLessLimitSizeImage('canvas', v, maxSize, dWidth, function (img) {
          wx.getFileInfo({
            filePath: img,
            success: function (res) {
              console.log('压缩后:' + res.size / 1024 + 'kb')
              var FSM = wx.getFileSystemManager();
              FSM.readFile({
                filePath: img,
                encoding: "base64",
                success: (data) => {
                  let Working = data.data;
                  console.log(index)
                  that.getBase64ImageUrlF2(Working, index)
                }
              });
            }
          })
        })
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },

  getBase64ImageUrlF2: function (res, index) {
    var index = index
    var base64Data = res;
    base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
    var imgUrl = `data:image/png;base64,${base64Data}`
    var eqTagIndex = imgUrl.indexOf("=");
    imgUrl = eqTagIndex != -1 ? imgUrl.substring(0, eqTagIndex) : imgUrl;
    var strLen = imgUrl.length;
    var fileSize = strLen - (strLen / 8) * 2
    console.log(fileSize + '大小')
    this.setData({
      showCamera: false,
      Img1: `${base64Data}`,
    })
    console.log(this.data.Img1)
  },

  toPhoto: function (e) {    //打开摄像头
    this.setData({
      showCamera: true,
      index: e.currentTarget.dataset.index
    })
  },

  close: function () { //关闭摄像机
    this.setData({
      showCamera: false
    })
  },

  changeCamera: function () {    //切换摄像头
    if (this.data.device == 'front') {
      this.setData({
        device: 'back'
      })
    }
    else {
      this.setData({
        device: 'front'
      })
    }
  }

})
复制代码

wxml

<view class="flxc aic box" wx:if="{{!showCamera}}">
	<view class="idbox width100" bindtap="toPhoto" data-index="1">
		<view class="backblue width100 flxc aic jcc">
			<image wx:if="{{Img1==''}}" src="/packageB/imageB/front.png" style="width:364rpx;height:228rpx"></image>
			<image wx:else src="{{Img1}}" style="width:364rpx;height:228rpx"></image>
		</view>
	</view>
</view>

<camera class="height100 width100" device-position="{{device}}" wx:if="{{showCamera}}" flash="off">
	<cover-image class="cover-1" src="/packageB/imageB/btn_change.png" bindtap="changeCamera"></cover-image>
	<cover-image class="cover-3" src="/packageB/imageB/btn_shot.png" bindtap="takePhotoZ" data-index="1"></cover-image>
	<cover-image class="cover-2" src="/packageB/imageB/btn_donwarrow.png" bindtap="close"></cover-image>
</camera>
手机网站建设