public static GetSvgInfoFormUrl = (src: string): Promise<any> =>
new Promise((resolve, reject) => {
request({ url: src }).then((res: any) => {
const { data } = res;
const r1: RegExp = /(?:[\S\s]+)?<svg(?=.*(height)="(\d+)(?:[^"]+)?")(?=.*(width)="(\d+)(?:[^"]+)?")(?:[\S\s]+)?/;
const r2: RegExp = /(?:[\S\s]+)?viewBox="\d+ \d+ (\d+) (\d+)"(?:[\S\s]+)?/;
const r3: RegExp = /(?:[\S\s]+)?(?:<svg[^>]+style="(?=.*(height):(\d+)(?:[^>]+)?)(?=.*(width):(\d+)(?:[^>]+)?))(?:[\S\s]+)?/;
let str: string = '{}';
let info: { width: number; height: number } = { width: 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数据'));
});
});
本文作者:Joe_du
本文链接:https://www.cnblogs.com/dygood/p/12937624.html
版权声明:本作品采用 MIT License 许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步