首页 前端知识 前端二维码图片解析图片识别/网络图片解析成链接/图片网络链接转本地链接(Js/Vue/Jquery)

前端二维码图片解析图片识别/网络图片解析成链接/图片网络链接转本地链接(Js/Vue/Jquery)

2024-03-21 15:03:25 前端知识 前端哥 603 510 我要收藏

目录

1、远程图片链接本地化

        1.创建图片

        2. 绘画图片

        3.创建文件流

        4.上传到本地(此步骤根据实际需求选择)

2、解析二维码(网络图片示例)

        1.准备工作

                安装canvas :npm install canvas

                安装jsqr:npm install jsqr

                安装jquery:npm install jquery

        2.识别二维码(jquery--本地文件上传)

        3.识别二维码(vue网络二维码图片识别)


注:需要用到canvas/jsqr/jquery!

1、远程图片链接本地化

        页面:

<!-- 识别二维码用的 canvas-->
<canvas class="canvas" ref="canvas" style="display: none"></canvas>

        1.创建图片

 get2: function (src) {
  let _this = this;
  return new Promise((resolve, reject) => {
    let image = new Image(), resultBlob = '';
    image.setAttribute('crossOrigin', 'anonymous');
    image.src = src;
    image.onload = () => {
      let random = Math.random();
      // 调用方法获取blob格式,方法写在下边
      resultBlob = _this.get3(image,random+".jpg");
      resolve(resultBlob)
    };
    image.onerror = () => {
      reject()
    }
  })
},

        2. 绘画图片

get3(image, fileName) {
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");
  let initSize = image.src.length
  let { width } = image, { height } = image;
  //等比缩放第二种 宽或高超过1280,等比缩放
  let rate = 1920 / width > 1;
  let tate = 1920 / height > 1;
  if(!rate){
    let product = 1920 / width;
    width =  Math.floor((width * product)*100)/100;
    height =  Math.floor((height * product)*100)/100;
  }else if(!tate){
    let product = 1920 / height;
    width =  Math.floor((width * product)*100)/100;
    height =  Math.floor((height * product)*100)/100;
  }
  canvas.width = width
  canvas.height = height
  ctx.fillStyle = 'rgba(255, 255, 255, 0)';//透明色
  ctx.fillRect(0, 0, width, height)
  ctx.drawImage(image, 0, 0, width, height)

  // 进行最小压缩0.1
  let compressData = canvas.toDataURL('image/jpg', 0.8)

  // 压缩后调用方法进行base64转Blob,方法写在下边
  let newFile = this.get4(compressData, fileName);
  return newFile
},

        3.创建文件流

get4(dataurl, filename) {
  let arr = dataurl.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  //转换成file对象
  return new File([u8arr], filename, { type: mime });
},

        4.上传到本地(此步骤根据实际需求选择)

async get1(src){//当需要循环时获取结果使用异步
  let _this=this
  let res2 = await _this.get2(src);
  let formData = new FormData();
  let random = Math.random();
        
  formData.append("random", random);
  formData.append("files", res2);
   //后端接口
  let res = await _this.$http.postFile("/uploadImgForPc", formData);
},

2、解析二维码(网络图片示例)

        1.准备工作

        注:根据需要安装,如有本地文件也可引用!

                安装canvas :npm install canvas

                安装报错:

> canvas@2.11.2 install /Users/.../WORK/work/.../node_modules/canvas > node-pre-gyp install --fallback-to-build --update-binary

                解决报错:

npm install canvas@2.11.2  --canvas_binary_host_mirror=https://registry.npmmirror.com/-/binary/canvas
                安装jsqr:npm install jsqr
                安装jquery:npm install jquery

        2.识别二维码(jquery--本地文件上传)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片二维码识别</title>
  <script src="./jquery.min.js"></script>
  <script src="./jsQR.js"></script>
</head>
<body>
  <span lan_id="bc">选择图片</span> <input type="file"  id="pictureChange"/>
     <div>
         <h2>识别结果:</h2>
         <ul id="result"></ul>
     </div>
  </body>
  <script type="text/javascript">
        $("body").append('<canvas id="qrcanvas" style="display:none;"></canvas>')
        $("#pictureChange").change(function (e) {
            var file = e.target.files[0];
            if(window.FileReader) {
                var fr = new FileReader();
                fr.readAsDataURL(file);
                fr.onloadend = function(e) {
                    var base64Data = e.target.result;
                    base64ToqR(base64Data)
                }
            }
        })
        function base64ToqR(data) {
            var c = document.getElementById("qrcanvas");
            var ctx = c.getContext("2d");
     
            var img = new Image();
            img.src = data;
            img.onload = function() {
                $("#qrcanvas").attr("width",img.width)
                $("#qrcanvas").attr("height",img.height)
                ctx.drawImage(img, 0, 0, img.width, img.height);
                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("识别错误")
                }
            };
        }
        function showCode(code){
            $("#result").append("<li>"+code+"</li>")
        }
    </script>
</html>

        3.识别二维码(vue网络二维码图片识别)

<!-- 识别二维码用的 canvas-->
<canvas class="canvas" ref="canvas" style="display: none"></canvas>
//e 为网络图片路径
async identifyImg(e) {
      let _this = this;
      return new Promise(async (resolve, reject) => {
        function get2(src) {
          return new Promise((res, rej) => {
            let image = new Image(),
              resultBlob = "";
            image.setAttribute("crossOrigin", "anonymous");
            image.src = src;
            image.onload = () => {
              let random = Math.random();
              resultBlob = get3(image, random + ".jpg");
              res(resultBlob);
            };
            image.onerror = () => {
              rej();
            };
          });
        }

        function get3(image, fileName) {
          let canvas = _this.$refs.canvas;
          let ctx = canvas.getContext("2d");
          let { width } = image,
            { height } = image;
          //等比缩放第二种 宽或高超过1280,等比缩放
          let rate = 1920 / width > 1;
          let tate = 1920 / height > 1;
          if (!rate) {
            let product = 1920 / width;
            width = Math.floor(width * product * 100) / 100;
            height = Math.floor(height * product * 100) / 100;
          } else if (!tate) {
            let product = 1920 / height;
            width = Math.floor(width * product * 100) / 100;
            height = Math.floor(height * product * 100) / 100;
          }
          canvas.width = width;
          canvas.height = height;
          ctx.fillStyle = "rgba(255, 255, 255, 0)"; //透明色
          ctx.fillRect(0, 0, width, height);
          ctx.drawImage(image, 0, 0, width, height);

          // 进行最小压缩0.1
          let compressData = canvas.toDataURL("image/jpg", 0.8);

          // 压缩后调用方法进行base64转Blob,方法写在下边
          let newFile = get4(compressData, fileName);
          return newFile;
        }

        function get4(dataurl, filename) {
          let arr = dataurl.split(",");
          let mime = arr[0].match(/:(.*?);/)[1];
          let bstr = atob(arr[1]);
          let n = bstr.length;
          let u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          //转换成file对象
          return new File([u8arr], filename, { type: mime });
        }

        const file = await get2(e);
        const reader = new FileReader();
        reader.onload = () => {
          const img = new Image();
          img.onload = () => {
            const canvas = _this.$refs.canvas;
            const context = canvas.getContext("2d");
            context.drawImage(img, 0, 0, canvas.width, canvas.height);
            const imageData = context.getImageData(
              0,
              0,
              canvas.width,
              canvas.height
            );
            const code = jsQR(
              imageData.data,
              imageData.width,
              imageData.height
            );

            if (code) {
              // console.log("识别成功---", code);
              resolve(code.data);
            } else {
              // console.log("无法识别---", code);
              resolve(false);
            }
          };
          img.src = reader.result;
        };
        reader.readAsDataURL(file);
      });
    },

参考文章:

1.前端JS识别二维码内容_js 解析二维码-CSDN博客

2.js/vue实现远程图片链接本地化_js远程图片本地化_liuliu2021.12的博客-CSDN博客

转载请注明出处或者链接地址:https://www.qianduange.cn//article/4054.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!