zoukankan      html  css  js  c++  java
  • 微信小程序,获取网络SVG图片宽高算法

    该算法来源于小程序开发社区一位大佬帮我搞的.

    /**
       * 获取网络SVG图片宽高
       * @param src SVG网络资源链接
       */
      public static GetSvgInfoFormUrl = (src: string): Promise<any> =>
        new Promise((resolve, reject) => {
          request({ url: src }).then((res: any) => {
            const { data } = res;
            // <svg height="" width=""
            const r1: RegExp = /(?:[Ss]+)?<svg(?=.*(height)="(d+)(?:[^"]+)?")(?=.*(width)="(d+)(?:[^"]+)?")(?:[Ss]+)?/;
            // <svg viewBox="0 0 1103 711"
            const r2: RegExp = /(?:[Ss]+)?viewBox="d+ d+ (d+) (d+)"(?:[Ss]+)?/;
            // <svg style="height:***px;***px"
            const r3: RegExp = /(?:[Ss]+)?(?:<svg[^>]+style="(?=.*(height):(d+)(?:[^>]+)?)(?=.*(width):(d+)(?:[^>]+)?))(?:[Ss]+)?/;
            let str: string = '{}';
            let info: {  number; height: number } = {  0, height: 0 };
            let isSuccess: boolean = false;
            try {
              str = data
                .replace(r1, '{"$1":$2,"$3":$4}')
                .replace(/$(2|4)/, '0')
                .replace(/$1/, 'height')
                .replace(/$3/, 'width');
              if (str.length > 45) isSuccess = false;
              else {
                isSuccess = true;
                info = JSON.parse(str);
              }
              if (!isSuccess) {
                str = data.replace(r2, '{"width":$1,"height":$2}').replace(/$(1|2)/, '0');
                if (str.length > 45) isSuccess = false;
                else {
                  isSuccess = true;
                  info = JSON.parse(str);
                }
                console.log('r2', info);
              }
              if (!isSuccess) {
                str = data
                  .replace(r3, '{"$1":$2,"$3":$4}')
                  .replace(/$(2|4)/, '0')
                  .replace(/$1/, 'height')
                  .replace(/$3/, 'width');
                if (str.length > 45) isSuccess = false;
                else {
                  isSuccess = true;
                  info = JSON.parse(str);
                }
                console.log('r3', info);
              }
            } catch (error) {
              console.log(error);
              reject(error);
            }
            if (isSuccess) resolve(info);
            else reject(new Error('无法正确解析SVG数据'));
          });
        });
  • 相关阅读:
    Java导出Excel和CSV(简单Demo)
    ffmepg命令行参数
    VLC命令参数(转载)
    深入Java虚拟机读书笔记第五章Java虚拟机
    JS常用方法记录
    记一次数据库的优化
    Infobright数据库使用
    Mysql连接驱动8.0版本改动
    Eclipse新建SrpingBoot项目Pom.xml文件报错
    SpringBoot 热部署开发
  • 原文地址:https://www.cnblogs.com/dygood/p/12937624.html
Copyright © 2011-2022 走看看