ts在工具类里封装动态导入本地图片的方法
时间: 2023-11-28 22:47:58 浏览: 31
在 TypeScript 中,可以使用 `import` 语句动态导入本地图片。具体实现如下:
```typescript
/**
* 将指定路径下的图片动态导入为 base64 格式的字符串
* @param imagePath 图片路径,相对于项目根目录
* @returns Promise<string> 返回 base64 格式的字符串
*/
export async function importImage(imagePath: string): Promise<string> {
try {
const imageModule = await import(`../${imagePath}`);
const imageBlob = await fetch(imageModule.default).then((response) => response.blob());
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result as string;
resolve(base64String);
};
reader.readAsDataURL(imageBlob);
});
} catch (error) {
console.error(error);
return '';
}
}
```
这里通过 `import` 语句动态导入了指定路径下的图片模块,然后使用 `fetch` 函数获取图片的二进制数据,并将其转换为 `Blob` 对象。接着使用 `FileReader` 对象将 `Blob` 对象转换为 base64 格式的字符串,最后返回该字符串。需要注意的是,这里使用了 `Promise` 对象来异步处理导入和读取图片的过程,并且在发生异常时返回了空字符串。