arc*_*oor 2 javascript png svelte vite
根据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/进行转换File。
原始加载程序似乎不适合二进制数据。当我尝试时,我最终\xef\xbf\xbd在数据中出现了替换字符 ( )。
您可以轻松编写自己的插件,根据需要对图像进行编码,例如十六进制字符串:
\n/** @type {import(\'vite\').Plugin} */\nconst hexLoader = {\n name: \'hex-loader\',\n transform(code, id) {\n const [path, query] = id.split(\'?\');\n if (query != \'raw-hex\')\n return null;\n\n const data = fs.readFileSync(path);\n const hex = data.toString(\'hex\');\n\n return `export default \'${hex}\';`;\n }\n};\nRun Code Online (Sandbox Code Playgroud)\n可以在 vite 配置中添加,例如
\nconst config = {\n plugins: [hexLoader, sveltekit()],\n // ...\n}\nRun Code Online (Sandbox Code Playgroud)\n然后您可以使用 a 导入path/file.png?raw-hex并转换数据。
| 归档时间: |
|
| 查看次数: |
3006 次 |
| 最近记录: |