进入正题

1. PC端调用摄像头拍照上传base64格式到后台,这个没什么花里胡哨的骚操作,直接看代码 (canvas + video)

<template>
<div>
<!--开启摄像头-->
<img @click="callCamera" :src="headImgSrc" alt="摄像头">
<!--canvas截取流-->
<canvas ref="canvas" width="" height=""></canvas>
<!--图片展示-->
<video ref="video" width="" height="" autoplay></video>
<!--确认-->
<el-button size="mini" type="primary" @click="photograph"></el-button>
</div>
</template>
<script>
export default {
data () {
return {
headImgSrc: require('@/assets/image/photograph.png')
}
},
methods: {
// 调用摄像头
callCamera () {
// H5调用电脑摄像头API
navigator.mediaDevices.getUserMedia({
video: true
}).then(success => {
// 摄像头开启成功
this.$refs['video'].srcObject = success
// 实时拍照效果
this.$refs['video'].play()
}).catch(error => {
console.error('摄像头开启失败,请检查摄像头是否可用!')
})
},
// 拍照
photograph () {
let ctx = this.$refs['canvas'].getContext('2d')
// 把当前视频帧内容渲染到canvas上
ctx.drawImage(this.$refs['video'], , , , )
// 转base64格式、图片格式转换、图片质量压缩
let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7)     // 由字节转换为KB 判断大小
let str = imgBase64.replace('data:image/jpeg;base64,', '')
let strLength = str.length
let fileLength = parseInt(strLength - (strLength / ) * )
    // 图片尺寸 用于判断
let size = (fileLength / ).toFixed()
console.log(size)     // 上传拍照信息  调用接口上传图片 ......... // 保存到本地
let ADOM = document.createElement('a')
ADOM.href = this.headImgSrc
ADOM.download = new Date().getTime() + '.jpeg'
ADOM.click()
},
// 关闭摄像头
closeCamera () {
if (!this.$refs['video'].srcObject) return
let stream = this.$refs['video'].srcObject
let tracks = stream.getTracks()
tracks.forEach(track => {
track.stop()
})
this.$refs['video'].srcObject = null
},
}
}
</script>

2. 移动端调用手机前置摄像头人脸录入、及图片旋转矫正、压缩上传base64格式/文件流格式;移动端幺蛾子就多了,比如部分手机打开的不是前置摄像头,部分手机拍照图片旋转了,高清手机拍的图片非常大........

介绍: 1. 通过input 开启手机前置摄像头  accept="image/*" 为开启摄像头  capture="user" 为开启前置摄像头 (微信公众号的话可以微信jssdk,但它不支持前置摄像头,默认后置,所以没用)

    2. 通过 exif.js 判断旋转了多少度在通过canvas矫正

3. 图片太大或超过规定尺寸则通过canvas压缩

HTML 部分:

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

JS 部分: 接口使用的Vuex调用   可忽略

  // 压缩图片 and 旋转角度纠正
compressImage (event) {
let _this = this
let file = event.target.files[]
let fileReader = new FileReader()
let img = new Image()
let imgWidth = ''
let imgHeight = ''
// 旋转角度
let Orientation = null
// 缩放图片需要的canvas
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')// 图片大小 大于2MB 则压缩
const isLt2MB = file.size <
// 通过 EXIF 获取旋转角度 1 为正常 3 为 180° 6 顺时针90° 9 为 逆时针90°
EXIF.getData(file, function () {
EXIF.getAllTags(this)
Orientation = EXIF.getTag(this, 'Orientation')
})
// 文件读取 成功执行
fileReader.onload = function (ev) {
// 文件base64化,以便获知图片原始尺寸
img.src = ev.target.result
}
// 读取文件
fileReader.readAsDataURL(file)
// base64地址图片加载完毕后
img.onload = function () {
imgWidth = img.width
imgHeight = img.height
canvas.width = img.width
canvas.height = img.height
// 目标尺寸
let targetWidth = imgWidth
let targetHeight = imgHeight
// 不需要压缩 不需要做旋转处理
if (isLt2MB && imgWidth < && imgHeight < && !Orientation) return _this.XMLHttpRequest(file)
if (isLt2MB && imgWidth < && imgHeight < && +Orientation === ) return _this.XMLHttpRequest(file)
// 大于2MB 、img宽高 > 960 则进行压缩
if (!isLt2MB || imgWidth >= || imgHeight >= ) {
// 最大尺寸
let maxWidth =
let maxHeight =
// 图片尺寸超过 960 X 960 的限制
if (imgWidth > maxWidth || imgHeight > maxHeight) {
if (imgWidth / imgHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth
targetHeight = Math.round(maxWidth * (imgHeight / imgWidth))
} else {
targetHeight = maxHeight
targetWidth = Math.round(maxHeight * (imgWidth / imgHeight))
}
}
// canvas对图片进行缩放
canvas.width = targetWidth
canvas.height = targetHeight
// 图片大小超过 2Mb 但未旋转 则只需要进行图片压缩
if (!Orientation || +Orientation === ) {
ctx.drawImage(img, , , targetWidth, targetHeight)
}
}
// 拍照旋转 需矫正图片
if (Orientation && +Orientation !== ) {
switch (+Orientation) {
case : // 旋转90度
canvas.width = targetHeight
canvas.height = targetWidth
ctx.rotate(Math.PI / )
// 图片渲染
ctx.drawImage(img, , -targetHeight, targetWidth, targetHeight)
break
case : // 旋转180度
ctx.rotate(Math.PI)
// 图片渲染
ctx.drawImage(img, -targetWidth, -targetHeight, targetWidth, targetHeight)
break
case : // 旋转-90度
canvas.width = targetHeight
canvas.height = targetWidth
ctx.rotate( * Math.PI / )
// 图片渲染
ctx.drawImage(img, -targetWidth, , targetWidth, targetHeight)
break
}
}
// base64 格式 我这是vuex 形式 重点是 canvas.toDataURL('image/jpeg', 1)
// _this.$store.commit('SAVE_FACE_IMAGE_BASE64', canvas.toDataURL('image/jpeg', 1))
     // 调用接口上传
// _this.upAppUserFaceByBase64()
// 通过文件流格式上传
     canvas.toBlob(function (blob) {
_this.XMLHttpRequest(blob)
}, 'image/jpeg', )
}
},
// 上传base64方式
upAppUserFaceByBase64 () {
this.$store.dispatch('upAppUserFaceByBase64', {
baseFace: this.$store.state.faceImageBase64
}).then(res => {
// 上传成功
}).catch(err => {
console.log(err)
})
},
// 上传
XMLHttpRequest (params) {
// 图片ajax上传
    let action = '后台接口地址'
let xhr = new XMLHttpRequest()
    let formData = new FormData()
formData.delete('multipartFile')
formData.append('multipartFile', params)
// 文件上传成功
xhr.onprogress = this.updateProgress
xhr.onerror = this.updateError
// 开始上传
xhr.open('POST', action, true)
xhr.send(formData)
},
// 上传成功回调
updateProgress (res) {
// res 就是成功后的返回
},
// 上传失败回调
updateError (error) {
console.log(error)
},

结语; 业务代码删了导致有点乱了,有不懂或疑问之处欢迎留言;

vue实现PC端调用摄像头拍照人脸录入、移动端调用手机前置摄像头人脸录入、及图片旋转矫正、压缩上传base64格式/文件格式的更多相关文章

  1. Vue directive自定义指令+canvas实现H5图片压缩上传-Base64格式

    前言 最近优化项目-手机拍照图片太大,回显速度比较慢,使用了vue的自定义指令实现H5压缩上传base64格式的图片 canvas自定义指令 Vue.directive("canvas&qu ...

  2. H5 拍照图片旋转、压缩和上传

    原文地址:github.com/whinc/blog/… 最近接到一个“发表评论”的需求:用户输入评论并且可以拍照或从相册选择图片上传,即支持图文评论.需要同时在 H5 和小程序两端实现,该需求处理图 ...

  3. 基于vue + axios + lrz.js 微信端图片压缩上传

    业务场景 微信端项目是基于Vux + Axios构建的,关于图片上传的业务场景有以下几点需求: 1.单张图片上传(如个人头像,实名认证等业务) 2.多张图片上传(如某类工单记录) 3.上传图片时期望能 ...

  4. 纯原生js移动端图片压缩上传插件

    前段时间,同事又来咨询一个问题了,说手机端动不动拍照就好几M高清大图,上传服务器太慢,问问我有没有可以压缩图片并上传的js插件,当然手头上没有,别慌,我去网上搜一搜. 结果呢,呵呵...诶~又全是基于 ...

  5. MUI 单图片压缩上传(拍照+系统相册): 选择立即上传

    1 html 部分 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> < ...

  6. 在浏览器端用H5实现图片压缩上传

    一.需求的场景: 在我们的需求中需要有一个在手机浏览器端,用户实现上传证件照片的功能,我们第一版上了一个最简版,直接让用户在本地选择图片,然后上传到公司公共的服务器上. 功能实现后我们发现一个问题,公 ...

  7. 基于vue上传base64图片,通过canvas压缩base64

    其实和vue关系不大,和我们之前做上传压缩性质是一样的 当然下面的代码是没有处理ios横屏拍照的bug的 有兴趣的可以多搜一下  网上都有相应的解答 .. var that = this if (e. ...

  8. H5 调用本地相机并压缩上传(是从angular的ionic项目中截取的)

    html部分 <div class="list_upload item bg_white"> <div class="itemImg pic_uploa ...

  9. html2canvas 将网页截图为图片,上传base64 到服务端

    await html2canvas(getById("winyh"), { height:500, allowTaint: true, useCORS: true, }).then ...

随机推荐

  1. scoket、TCP、UDP、WebService选型

    抱着去转型产品经理的方向去面试了一家公司,面试完很惭愧,不过见到了人事我也很意外,因为其实表现也没那么好,不过在此谈谈我的感受. 1.有3轮,前2轮都是先让我做自我介绍(我都说的很干脆,直接哪年毕业, ...

  2. 在 centos7.5 使用 DockerFile 构建镜像时报错 "Error parsing reference:"microsoft/dotnet:2.2-aspnetcore-runtime AS base"is not a valid repository/tag: invalid reference format"

    运行 dockerfile 时报出的错误 FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base Error parsing reference: & ...

  3. minilzo使用流程

    /* testmini.c -- very simple test program for the miniLZO library This file is part of the LZO real- ...

  4. HDU 6438 Buy and Resell

    高卖低买,可以交易多次 维护一个优先队列,贪心 相当于每天卖出 用当前元素减优先队列最小得到收益 用0/卖出,1/买入标志是否真实进行了交易,记录次数 #include<bits/stdc++. ...

  5. 创建maven web项目时,没有web.xml文件

    1.问题:创建maven项目时,选择的是创建web-app项目,但是结果配置之后,却没有web.xml文件. 2.解决办法: ------------------------------------- ...

  6. 5 November

    拓扑排序 for (int i=1; i<=n; ++i) if (!ind[i]) q.push(i); while (!q.empty()) { int now=q.top(); q.pop ...

  7. SQL 多表查询的几种连接方式

    --创建数据库 create database GoodsSystem go --使用数据库 use GoodsSystem go --创建商品类型表 create table GoodsType ( ...

  8. win10 1903

    Windows 10 v1903/19H1 and Windows Server 2019 v1903/19H1 will hang or BSOD during power-on when vIOM ...

  9. ORACLE表空间offline谈起,表空间备份恢复

    从ORACLE表空间offline谈起,表空间备份恢复将表空间置为offline,可能的原因包括维护.备份恢复等目的:表空间处于offline状态,那么Oracle不会允许任何对该表空间中对象的SQL ...

  10. UVALive 7325 Book Borders

    题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_ ...