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


    目录

    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、远程图片链接本地化

            页面:

    1. <canvas class="canvas" ref="canvas" style="display: none">canvas>

            1.创建图片

    1.  get2: function (src) {
    2.   let _this = this;
    3.   return new Promise((resolve, reject) => {
    4.     let image = new Image(), resultBlob = '';
    5.     image.setAttribute('crossOrigin', 'anonymous');
    6.     image.src = src;
    7.     image.onload = () => {
    8.       let random = Math.random();
    9.       // 调用方法获取blob格式,方法写在下边
    10.       resultBlob = _this.get3(image,random+".jpg");
    11.       resolve(resultBlob)
    12.     };
    13.     image.onerror = () => {
    14.       reject()
    15.     }
    16.   })
    17. },

            2. 绘画图片

    1. get3(image, fileName) {
    2.   let canvas = document.createElement("canvas");
    3.   let ctx = canvas.getContext("2d");
    4.   let initSize = image.src.length
    5.   let { width } = image, { height } = image;
    6.   //等比缩放第二种 宽或高超过1280,等比缩放
    7.   let rate = 1920 / width > 1;
    8.   let tate = 1920 / height > 1;
    9.   if(!rate){
    10.     let product = 1920 / width;
    11.     width =  Math.floor((width * product)*100)/100;
    12.     height =  Math.floor((height * product)*100)/100;
    13.   }else if(!tate){
    14.     let product = 1920 / height;
    15.     width =  Math.floor((width * product)*100)/100;
    16.     height =  Math.floor((height * product)*100)/100;
    17.   }
    18.   canvas.width = width
    19.   canvas.height = height
    20.   ctx.fillStyle = 'rgba(255, 255, 255, 0)';//透明色
    21.   ctx.fillRect(0, 0, width, height)
    22.   ctx.drawImage(image, 0, 0, width, height)
    23.   // 进行最小压缩0.1
    24.   let compressData = canvas.toDataURL('image/jpg', 0.8)
    25.   // 压缩后调用方法进行base64转Blob,方法写在下边
    26.   let newFile = this.get4(compressData, fileName);
    27.   return newFile
    28. },

            3.创建文件流

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

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

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

    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--本地文件上传)

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>图片二维码识别title>
    7. <script src="./jquery.min.js">script>
    8. <script src="./jsQR.js">script>
    9. head>
    10. <body>
    11. <span lan_id="bc">选择图片span> <input type="file" id="pictureChange"/>
    12. <div>
    13. <h2>识别结果:h2>
    14. <ul id="result">ul>
    15. div>
    16. body>
    17. <script type="text/javascript">
    18. $("body").append('')
    19. $("#pictureChange").change(function (e) {
    20. var file = e.target.files[0];
    21. if(window.FileReader) {
    22. var fr = new FileReader();
    23. fr.readAsDataURL(file);
    24. fr.onloadend = function(e) {
    25. var base64Data = e.target.result;
    26. base64ToqR(base64Data)
    27. }
    28. }
    29. })
    30. function base64ToqR(data) {
    31. var c = document.getElementById("qrcanvas");
    32. var ctx = c.getContext("2d");
    33. var img = new Image();
    34. img.src = data;
    35. img.onload = function() {
    36. $("#qrcanvas").attr("width",img.width)
    37. $("#qrcanvas").attr("height",img.height)
    38. ctx.drawImage(img, 0, 0, img.width, img.height);
    39. var imageData = ctx.getImageData(0, 0, img.width, img.height);
    40. const code = jsQR(imageData.data, imageData.width, imageData.height, {
    41. inversionAttempts: "dontInvert",
    42. });
    43. if(code){
    44. showCode(code.data)
    45. }else{
    46. alert("识别错误")
    47. }
    48. };
    49. }
    50. function showCode(code){
    51. $("#result").append("
    52. "+code+"
    53. ")
  • }
  • script>
  • html>
  •         3.识别二维码(vue网络二维码图片识别)

    1. <canvas class="canvas" ref="canvas" style="display: none">canvas>
    2. //e 为网络图片路径
    3. async identifyImg(e) {
    4. let _this = this;
    5. return new Promise(async (resolve, reject) => {
    6. function get2(src) {
    7. return new Promise((res, rej) => {
    8. let image = new Image(),
    9. resultBlob = "";
    10. image.setAttribute("crossOrigin", "anonymous");
    11. image.src = src;
    12. image.onload = () => {
    13. let random = Math.random();
    14. resultBlob = get3(image, random + ".jpg");
    15. res(resultBlob);
    16. };
    17. image.onerror = () => {
    18. rej();
    19. };
    20. });
    21. }
    22. function get3(image, fileName) {
    23. let canvas = _this.$refs.canvas;
    24. let ctx = canvas.getContext("2d");
    25. let { width } = image,
    26. { height } = image;
    27. //等比缩放第二种 宽或高超过1280,等比缩放
    28. let rate = 1920 / width > 1;
    29. let tate = 1920 / height > 1;
    30. if (!rate) {
    31. let product = 1920 / width;
    32. width = Math.floor(width * product * 100) / 100;
    33. height = Math.floor(height * product * 100) / 100;
    34. } else if (!tate) {
    35. let product = 1920 / height;
    36. width = Math.floor(width * product * 100) / 100;
    37. height = Math.floor(height * product * 100) / 100;
    38. }
    39. canvas.width = width;
    40. canvas.height = height;
    41. ctx.fillStyle = "rgba(255, 255, 255, 0)"; //透明色
    42. ctx.fillRect(0, 0, width, height);
    43. ctx.drawImage(image, 0, 0, width, height);
    44. // 进行最小压缩0.1
    45. let compressData = canvas.toDataURL("image/jpg", 0.8);
    46. // 压缩后调用方法进行base64转Blob,方法写在下边
    47. let newFile = get4(compressData, fileName);
    48. return newFile;
    49. }
    50. function get4(dataurl, filename) {
    51. let arr = dataurl.split(",");
    52. let mime = arr[0].match(/:(.*?);/)[1];
    53. let bstr = atob(arr[1]);
    54. let n = bstr.length;
    55. let u8arr = new Uint8Array(n);
    56. while (n--) {
    57. u8arr[n] = bstr.charCodeAt(n);
    58. }
    59. //转换成file对象
    60. return new File([u8arr], filename, { type: mime });
    61. }
    62. const file = await get2(e);
    63. const reader = new FileReader();
    64. reader.onload = () => {
    65. const img = new Image();
    66. img.onload = () => {
    67. const canvas = _this.$refs.canvas;
    68. const context = canvas.getContext("2d");
    69. context.drawImage(img, 0, 0, canvas.width, canvas.height);
    70. const imageData = context.getImageData(
    71. 0,
    72. 0,
    73. canvas.width,
    74. canvas.height
    75. );
    76. const code = jsQR(
    77. imageData.data,
    78. imageData.width,
    79. imageData.height
    80. );
    81. if (code) {
    82. // console.log("识别成功---", code);
    83. resolve(code.data);
    84. } else {
    85. // console.log("无法识别---", code);
    86. resolve(false);
    87. }
    88. };
    89. img.src = reader.result;
    90. };
    91. reader.readAsDataURL(file);
    92. });
    93. },

    参考文章:

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

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

  • 相关阅读:
    18数据接口和selenium
    python爬虫出现问题
    智慧水利水务数字孪生应用,典型业务场景分享
    【springboot异常处理】
    HarmonyOS—代码Code Linter检查
    PostGIS是否有方法能将一个Polygon面切割成若干份小的Polygon面,且每一份的面积差不多大
    多维数据库中的高效计算机制是什么?
    奈奎斯特定理、香农定理
    [InternLM训练营第二期笔记]6.Lagent & AgentLego 智能体应用搭建
    统计学习:逻辑回归与交叉熵损失(Pytorch实现)
  • 原文地址:https://blog.csdn.net/weixin_57844432/article/details/133675146