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

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

1、远程图片链接本地化

        页面:


        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

                安装报错:

> [email protected] install /Users/.../WORK/work/.../node_modules/canvas > node-pre-gyp install --fallback-to-build --update-binary

                解决报错:

npm install [email protected]  --canvas_binary_host_mirror=https://registry.npmmirror.com/-/binary/canvas
                安装jsqr:npm install jsqr
                安装jquery:npm install jquery

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





  
  
  图片二维码识别
  
  


  选择图片 
     

识别结果:

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

    
    
    //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博客

    你可能感兴趣的:(JavaScript,VUE,前端,javascript,vue.js,jquery)