根据Vite 文档,可以将文件作为原始数据字符串导入。
在一个精简的项目中,我不仅需要使用 URL,还需要使用整个图像数据。因此,我尝试着import image from "@/assets/image.png?raw"。但是,无论我尝试什么,我都无法将其转换为Uint8Array. 我尝试过使用string.charCodeAt(0)和string.codePointAt(0)各种其他东西。我希望第一个字节是137, 80, 78, 71, 13, 10, 26, 10PNG标头,但它总是返回为253, 80, 78, 71, 13, 10, 26, 10. 这些差异贯穿整个字符串。
我不知道它是什么编码,因此不知道如何将其再次解码为图像数据。我之前尝试过使用fetch(),但由于我的来源使用Basic-Auth它也不起作用(凭据会因用户而异,我想避免让他们在其他地方再次输入它 - 我用作https://user:password@example.comURL 表示法)。
import image from "@/assets/image.png?raw";
let data = Uint8Array.from([..image].map(x => x.codePointAt(0)));
console.log(data);
// [253, 80, 78, 71, 13, 10, 26, 10, ...]
Run Code Online (Sandbox Code Playgroud)
如何在不使用 fetch 之类的情况下将实际图像数据放入我的脚本中?格式几乎可以是任何东西,我将它用作 aUint8Array和base64字符串,并且可以在两者之间进行转换。我还可以从Blob/进行转换 …