vue项目中实现上传图片识别二维码-jsQR

效果图:

 jsQR 是一个纯 JavaScript 二维码解析库。该库读取原始图像或者是摄像头,并将定位,提取和解析其中的任何QR码。(来源:https://www.oschina.net/p/jsqr?hmsr=aladdin1e1

1、 安装jsQR :  npm install jsqr --save 

2、 jsQR方法使用实例:https://www.cnblogs.com/wenqd/p/11541030.html

var imageData = ctx.getImageData(0, 0, img.width, img.height);
const code = jsQR(imageData.data, imageData.width, imageData.height, {
    inversionAttempts: "dontInvert",
});
if(code){
    showCode(code.data)
}else{
    alert("识别错误")
}

 全部代码如下:

<template>
    <div id="app">
        <span>{{result}}</span>
        <br>
        <input type="file" accept="image/png, image/jpeg" @change="changeFile"> </input>
        <br>
        <img id="myimg" v-show="false">
        <canvas id="mycanvas"></canvas>
    </div>
</template>

<script>
    import jsQR from "jsqr"
    export default {
        data() {
            return {
                result: "",
            }
        },
        methods: {
            changeFile(e) {
                var that = this;
                that.result = "请上传二维码";
                console.dir(e.target.files[0].name);
                var fileReader = new FileReader();

                fileReader.onload = function(event) {
                    var data = event.target.result;
                    // console.dir(data);
                    var img = document.getElementById("myimg");
                    img.src = data;

                    img.onload = function() {
                        var mycanvas = document.getElementById("mycanvas");
                        var ctx = mycanvas.getContext("2d");
                        // canvas 的width/height重新设置的时候会清空画布
                        mycanvas.width = img.width;
                        mycanvas.height = img.height;

                        ctx.drawImage(img, 0, 0);
                        var imageData = ctx.getImageData(0, 0, img.width, img.height);
                        console.log(imageData);
                        
                        const code = jsQR(imageData.data, imageData.width, imageData.height, {
                            inversionAttempts: "dontInvert",
                        });
                        if (code) {
                            console.log(code.data);
                        } else {
                            console.log("识别错误");
                        }
                        that.result = code.data;
                    }
                }
                fileReader.readAsDataURL(e.target.files[0]);
            }
        }
    }
</script>
<style>

</style>
posted @ 2021-12-28 14:54  sunshine233  阅读(2914)  评论(0编辑  收藏  举报