将svg转换为base64格式

/**
 * 使用Blob方式将SVG转换为base64(推荐)
 * @param {string} svgPath - SVG图片的本地路径
 * @returns {Promise<string>}
 */
export async function svgToBase64WithBlob(svgPath) {
  try {
    const response = await fetch(svgPath);
    const svgText = await response.text();
    
    return new Promise((resolve, reject) => {
      // 创建Blob对象
      const blob = new Blob([svgText], { type: 'image/svg+xml' });
      const reader = new FileReader();
      
      reader.onloadend = () => resolve(reader.result);
      reader.onerror = reject;
      
      // 读取为Data URL
      reader.readAsDataURL(blob);
    });
  } catch (error) {
    console.error('SVG转换失败:', error);
    throw error;
  }
}

使用注意: 
采用import 的方式导入

import myIcon from "../assets/image/logo.svg";
const base64 = await svgToBase64WithBlob(myIcon);
     console.log(base64);

 

posted @ 2026-02-27 10:55  龙卷风吹毁停车场  阅读(1)  评论(0)    收藏  举报