import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Webcam from 'react-webcam';//引入第三方拍照组件
class Test extends PureComponent {
constructor(props) {
super(props);
this.state = {
photo: null,//用于获取照片
};
this.webcamRef = React.createRef();//获取其实际的DOM节点,调用其原生方法
}
//拍照功能--获取到的图片base64编码还要解码转地址!!
takeSnapshot = () => {
//操作DOM元素调用原生的方法获取当前画面的base64编码
const base64Image = this.webcamRef.current.getScreenshot();
// console.log(base64Image)
//Base64 编码的图片数据
const byteCharacters = base64Image.split(',')[1];
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: 'image/jpeg'});
const imageUrl = URL.createObjectURL(blob);
console.log(imageUrl)
// 将 imageUrl 显示在页面上或者上传到服务器
this.setState({ photo: imageUrl });
};
render() {
const { photo } = this.state;
const imgSrc = photo ? photo : '';
return (
<div className={'page-body'}>
<div className={'content-body'}>
<div>
{/*使用第三方拍照组件*/}
<Webcam
ref={this.webcamRef}
audio={false}
height={350}
width={350}
screenshotFormat="image/jpeg"
/>
{imgSrc && <img src={imgSrc} alt="Snapshot" />}
<button className='miniBtn' onClick={this.takeSnapshot}>
拍照
</button>
</div>
</div>
</div>
);
}
}
export default connect()(Test);
引入react-webcam实现拍照功能
于 2024-05-15 09:39:34 首次发布