Public account: wechat search front end tool person; Take more dry goods

Similar needs basic paste copy can be used

1 PC

Call the camera to take a photo and upload base64 format to the background. This is not a slick operation, just look at the code (Canvas + Video)

<template>

    <div>

<! -- Start camera -->

        <img @click="callCamera" :src="headImgSrc" alt="Camera">

<! Canvas intercepting stream -->

        <canvas ref="canvas" width="640" height="480"></canvas>

<! -- Picture display -->

        <video ref="video" width="640" height="480" autoplay></video>

<! - confirmation - >

        <el-button size="mini" type="primary" @click="photograph"></el-button>

    </div>

</template>   

<script>

export default {

  data () {

    return {

      headImgSrc: require('@/assets/image/photograph.png')

    }

  },

  methods: {

// Call the camera

    callCamera () {

// H5 calls PC camera API

      navigator.mediaDevices.getUserMedia({

        video: true

      }).then(success => {

// The camera is started successfully

        this.$refs['video'].srcObject = success

// Live photo effect

        this.$refs['video'].play()

      }).catch(error => {

        console.error('Camera failed to open, please check whether the camera is available! ')

      })

    },

/ / photo

    photograph () {

      let ctx = this.$refs['canvas'].getContext('2d')

// Render the current video frame to canvas

      ctx.drawImage(this.$refs['video'], 0, 0, 640, 480)

// Convert base64 format, image format conversion, image quality compression

      let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7)

      

// Determine the size by converting bytes to KB

      let str = imgBase64.replace('data:image/jpeg; base64,'.' ')

      let strLength = str.length

      let fileLength = parseInt(strLength - (strLength / 8) * 2)

// The size of the image is used for judging

      let size = (fileLength / 1024).toFixed(2)

      console.log(size)



// Upload photo information call interface upload picture.........



// Save to the local directory

      this.dialogCamera = false

      let ADOM = document.createElement('a')

      ADOM.href = this.headImgSrc

      ADOM.download = new Date().getTime() + '.jpeg'

      ADOM.click()

    },

// Turn off the camera

    closeCamera () {

      if(! this.$refs['video'].srcObject) {

        this.dialogCamera = false

        return

      }

      let stream = this.$refs['video'].srcObject

      let tracks = stream.getTracks()

      tracks.forEach(track => {

        track.stop()

      })

      this.$refs['video'].srcObject = null

    },

  }

}

</script>

Copy the code

(2) the mobile end

Call the phone’s front camera face input, and picture rotation correction, compression upload Base64 format/file stream format;

Mobile terminal unitary is much, such as part of the mobile phone is not open front camera, part of the mobile phone photo rotation, hd mobile phone photo is very large……..

Specific ideas:

  1. throughinputTurn on the front-facing camera of the phoneaccept="image/*"To enable the cameracapture="user"To enable the front camera; Wechat public account can be wechatjssdk, but it doesn’t support a front-facing camera, default is rear-facing.)
  2. throughexif.jsDetermine how many degrees of rotation is going throughcanvascorrect
  3. Pictures too large or larger than the specified size will be approvedcanvasThe compression

HTML part:

<input ref="file" type="file" accept="image/*" capture="user">

Copy the code

JS part: Vuex calls used by the interface can be ignored

<script>

export default {

  data () {

    return {}

  },

  methods: {

// Compress the image and rotate the Angle to correct

    compressImage (event) {

      let _this = this

      let file = event.target.files[0]

      let fileReader = new FileReader()

      let img = new Image()

      let imgWidth = ' '

      let imgHeight = ' '

// Rotate the Angle

      let Orientation = null

// The canvas needed to scale the image

      let canvas = document.createElement('canvas')

      let ctx = canvas.getContext('2d') // Compress images larger than 2MB

      const isLt2MB = file.size < 2097152

// Use EXIF to obtain rotation Angle 1: normal, 3:180°, 6:90° clockwise, 9:90° counterclockwise

      EXIF.getData(file, function () {

        EXIF.getAllTags(this)

        Orientation = EXIF.getTag(this, 'Orientation')

      })

// File read successfully

      fileReader.onload = function (ev) {

// Base64 files to get the original image size

        img.src = ev.target.result

      }

// Read the file

      fileReader.readAsDataURL(file)

// Base64 after the address image is loaded

      img.onload = function () {

        imgWidth = img.width

        imgHeight = img.height

        canvas.width = img.width

        canvas.height = img.height

// Target size

        let targetWidth = imgWidth

        let targetHeight = imgHeight

// No compression, no rotation

        if(isLt2MB && imgWidth < 960 && imgHeight < 960 && ! Orientation)return _this.XMLHttpRequest(file)

        if (isLt2MB && imgWidth < 960 && imgHeight < 960 && +Orientation === 1) return _this.XMLHttpRequest(file)

// If the size is greater than 2MB and img width and height is greater than 960, compress it

        if(! isLt2MB || imgWidth >= 960 || imgHeight >= 960) {

// Maximum size

          let maxWidth = 850

          let maxHeight = 850

// The image size exceeds the 960 X 960 limit

          if (imgWidth > maxWidth || imgHeight > maxHeight) {

            if (imgWidth / imgHeight > maxWidth / maxHeight) {

// Make it wider

              targetWidth = maxWidth

              targetHeight = Math.round(maxWidth * (imgHeight / imgWidth))

            } else {

              targetHeight = maxHeight

              targetWidth = Math.round(maxHeight * (imgWidth / imgHeight))

            }

          }

// Canvas scales the image

          canvas.width = targetWidth

          canvas.height = targetHeight

// Images larger than 2Mb but not rotated need to be compressed

          if(! Orientation || +Orientation === 1) {

            ctx.drawImage(img, 0, 0, targetWidth, targetHeight)

          }

        }

// Take a photo rotation to correct the image

        if(Orientation && +Orientation ! = = 1) {

          switch (+Orientation) {

            case6: // Rotate 90 degrees

              canvas.width = targetHeight

              canvas.height = targetWidth

              ctx.rotate(Math.PI / 2)

// Image rendering

              ctx.drawImage(img, 0, -targetHeight, targetWidth, targetHeight)

              break

            case3: // Rotate 180 degrees

              ctx.rotate(Math.PI)

// Image rendering

              ctx.drawImage(img, -targetWidth, -targetHeight, targetWidth, targetHeight)

              break

            case8: // Rotate -90 degrees

              canvas.width = targetHeight

              canvas.height = targetWidth

              ctx.rotate(3 * Math.PI / 2)

// Image rendering

              ctx.drawImage(img, -targetWidth, 0, targetWidth, targetHeight)

              break

          }

        }

// Base64 format this is vuex form focus is canvas.todataurl ('image/jpeg'1),

        // _this.$store.commit('SAVE_FACE_IMAGE_BASE64', canvas.toDataURL('image/jpeg', 1))

// Call interface upload

        // _this.upAppUserFaceByBase64()

// Upload in file stream format

     canvas.toBlob(function (blob) {

          _this.XMLHttpRequest(blob)

        }, 'image/jpeg'1),

      }

    },

// Upload base64 mode

    upAppUserFaceByBase64 () {

      this.$store.dispatch('upAppUserFaceByBase64', {

        baseFace: this.$store.state.faceImageBase64

      }).then(res => {

// Upload succeeded

      }).catch(err => {

        console.log(err)

      })

    },

/ / upload

    XMLHttpRequest (params) {

// Image ajax upload

    let action = 'Background interface address'

      let xhr = new XMLHttpRequest()

    let formData = new FormData()

      formData.delete('multipartFile')

      formData.append('multipartFile', params)

// The file was successfully uploaded

      xhr.onprogress = this.updateProgress

      xhr.onerror = this.updateError

// Start uploading

      xhr.open('POST', action, true)

      xhr.send(formData)

    },

// Upload success callback

    updateProgress (res) {

// res is the return on success

    },

// Upload failed callback

    updateError (error) {

      console.log(error)

    }

  }

}

</script>

Copy the code

At the end

Article source: your blog post: https://www.cnblogs.com/ljx20180807/p/10839713.html

Irrelevant code deletion caused a bit of chaos, do not understand or questions welcome to leave a message;