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);

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐