VUE 拍照总结

1.调用相机

<!-- 相机 -->
<input type="file" accept="image/*" capture="camera">  

<!-- 录像 -->
<input type="file" accept="video/*" capture="camcorder">
 
<!-- 系统相册 -->
<input type="file" accept="audio/*" capture="microphone">
 
<!-- 多选 -->
<input type="file" accept="image/*" multiple>

注:在电脑上测试时,如果没有摄像头会自动进入选择上传照片;手机上可正常使用。

2.获取拍照图片

<input type="file" accept="image/*" capture="camera" @change="onImageChange" > 

onImageChange(e){  // e =》event:事件对象
    let file = e.target.files[0];
    console.log(file);
}

 如果用的原生html,可以参考以下代码


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>input file capture</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, minimal-ui, shrink-to-fit=no">
    <style>
        body {
            font-family: Arial, Roboto, 'Droid Sans', 'Hiragino Sans GB', 'Microsoft YaHei', 'Simsun', STXihei, 'sans-serif';
            font-size: 14px;
        }

        dl:not(:last-child) {
            overflow: hidden;
            padding: 10px;
            margin-bottom: 10px;
            border-bottom: 1px dashed #dedede;
        }

        dt {
            padding-bottom: 10px;
            font-weight: bold;
            color: #f32600;
        }

        dd {
            margin: 0;
            padding: 5px 0 0 20px;
            border-left: 2px solid #cddc39;
        }
    </style>
</head>
<body>

<dl>
    <dt><code>capture="environment"</code> 前置摄像头 图片</dt>
    <dd><input onchange="onImageChange(value)" type="file" capture="environment" accept="image/*"></dd>
    <dd>
        <p>使用 <code>capture="camera"</code> 开启前置摄像头时,设定为<strong>图片</strong>类型文件。</p>
    </dd>
</dl>
<script>
    function onImageChange(value) {
        alert(value)
    }
</script>
</body>
</html>

3.压缩图片

compressImage  (file) {
    return new Promise((resolve, reject) => {
        const { type, name, size } = file
        
        let img = new Image()

        // 创建一个reader实例
        let reader = new FileReader()

        // 读取拿到的文件
        reader.readAsDataURL(file)
        reader.onload = (e) => {
            // 文件加载成功后去转成Img对象
            img.src = e.target.result

            img.onload = () => {

                // 创建画布canvas
                let canvas = document.createElement('canvas')
                let content = canvas.getContext('2d')
                // 设置画布的宽高
                canvas.width = img.width
                canvas.height = img.height 
                // 将图片画在画布上
                content.drawImage(img, 0, 0, canvas.width, canvas.height)
                //画布转成blob格式的图片
                canvas.toBlob((blob) => {  // canvas.toBlob(回调函数:必传,类型,压缩程度)
                    // 将【blob格式】的图片转成【file对象】
                    let file = new File([blob], name, { type, size })
                    resolve(file)
                }, type, 0.5)
            }
        }
    })
}

4.图片转base64格式

getBase64(file) {
    return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
            imgResult = reader.result
        }
        reader.onerror = function (error) {
            reject(error)
        }
        reader.onloadend = function () {
            resolve(imgResult)
        }
    })
},

传入图片后会返回一段字符串“data:image/jpeg;base64,......”,其中data:image/jpeg;base64 表示jpeg图片数据,除了jpeg格式还支持以下格式:

data:, 文本数据
data:text/plain, 文本数据
data:text/html, HTML代码
data:text/html;base64, base64 编码的HTML代码
data:text/css, CSS代码
data:text/css;base64, base64编码的CSS代码
data:text/javascript, Javascript代码
data:text/javascript;base64, base64编码的Javascript代码
data:image/gif;base64, base64编码的gif图片数据
data:image/png;base64, base64编码的png图片数据
data:image/jpeg;base64, base64编码的jpeg图片数据
data:image/x-icon;base64, base64编码的icon图片数据

 此时只要是将base64格式的图片赋值给标签<img>的src 属性即可。

<img src= "data:image/png;base64,图片的base64字符串" />

5.汇总案例

需求:vue 调用相机并获取拍照图片,当图片大于2MB时压缩图片大小,最后转为base64格式。

<template>
    <input type="file" accept="image/*" capture="camera" @change="onImageChange">
</template>

<script>
export default {
methods: {
    // 调用
    async onImageChange(e) {
        let file = e.target.files[0];

        this.fileimg = await this.compressImage(file)
        console.log(this.fileimg);
    },
    // 压缩图片
    compressImage(file){
        return new Promise((resolve, reject)=> {
            let thumb = '';
            let isLt2M = file.size / 1024 / 1024 < 2;
                    
            let img = new Image();
            // 创建一个reader实例
            let reader = new FileReader()
            
            // 读取拿到的文件
            reader.readAsDataURL(file);
            reader.onload = function(e) {
                // 文件加载成功后去转成Img对象
                img.src = e.target.result
                let content = img.src.slice(img.src.indexOf(',') + 1,img.src.length);

                if (isLt2M) {
                    resolve(content)
                    return
                }

                img.onload = function () {
                    // 创建画布canvas
                    let canvas = document.createElement('canvas'),
                        context = canvas.getContext('2d');
                    // 设置画布的宽高
                    let originWidth = this.width,  // 此处 this===img
                        originHeight = this.height;
                    // 最大尺寸限制
                    let maxWidth = 1024, 
                        maxHeight = 1024;
                    // 该图片尺寸
                    let targetWidth = originWidth, 
                        targetHeight = originHeight;
                    // 该图片宽或高大于最大尺寸限制时
                    if (originWidth > maxWidth || originHeight > maxHeight) {
                        // 以图片最长边为最大尺寸进去等比例缩放
                        if (originWidth / originHeight > maxWidth / maxHeight) { // 更宽
                            targetWidth = maxWidth;
                            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                        } else {
                            targetHeight = maxHeight;
                            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                        }
                    }
                    // canvas对图片进行缩放
                    canvas.width = targetWidth;
                    canvas.height = targetHeight;
                    // 清除画布
                    context.clearRect(0, 0, targetWidth, targetHeight);
                    // 将图片画在画布上
                    context.drawImage(img, 0, 0, targetWidth, targetHeight);
                    // 转为base64格式
                    thumb = canvas.toDataURL('image/jpeg'),
                    thumb = thumb.slice(thumb.indexOf(',') + 1,thumb.length);

                    if (img.src.length === 0) {
                        reject(false)
                    }
                    let data = {
                        // 原始图片大小
                        content,
                        // 压缩后图片大小
                        thumb
                    }
                    console.log("图片大小对比",data);
                    resolve(thumb)
                }
            };
        })
    }
}
}
</script>

<style>
</style>

猜你喜欢

转载自blog.csdn.net/m0_63057114/article/details/128639316