gpt4 book ai didi

javascript - 使用vite将原始图像数据导入到脚本中

转载 作者:行者123 更新时间:2023-12-03 08:02:04 24 4
gpt4 key购买 nike

根据Vite Docs ,可以将文件作为原始数据字符串导入。

在一个精简的项目中,我不仅需要使用 URL,还需要使用整个图像数据。因此,我尝试 import image from "@/assets/image.png?raw" 。但是,无论我尝试什么,我都无法将其转换为 Uint8Array 。我尝试过使用 string.charCodeAt(0) , string.codePointAt(0)以及其他各种东西。我预计第一个字节是 137, 80, 78, 71, 13, 10, 26, 10因为那是PNG header ,但它总是返回为 253, 80, 78, 71, 13, 10, 26, 10 。这些差异贯穿整个字符串。

我不知道它是什么编码,因此不知道如何将其再次解码为图像数据。我之前尝试过使用 fetch() ,但由于我的来源使用 Basic-Auth这也不起作用(凭据因用户而异,我想避免让他们在其他地方再次输入它 - 我使用 https://user:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7000110303071f0214301508111d001c155e131f1d" rel="noreferrer noopener nofollow">[email protected]</a> 作为 URL 表示法)。

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, ...]

如何在不使用 fetch 之类的情况下将实际图像数据获取到我的脚本中?格式几乎可以是任何格式,我都将其用作 Uint8Array和一个 base64字符串,我可以在两者之间进行转换。我还可以从 Blob 进行转换/File .

最佳答案

原始加载器似乎不适合二进制数据。当我尝试时,我最终在数据中出现了替换字符 ()。

您可以轻松编写自己的插件,根据需要对图像进行编码,例如作为十六进制字符串:

/** @type {import('vite').Plugin} */
const hexLoader = {
name: 'hex-loader',
transform(code, id) {
const [path, query] = id.split('?');
if (query != 'raw-hex')
return null;

const data = fs.readFileSync(path);
const hex = data.toString('hex');

return `export default '${hex}';`;
}
};

可以在vite配置中添加,例如

const config = {
plugins: [hexLoader, sveltekit()],
// ...
}

然后您可以使用 path/file.png?raw-hexconvert the data 进行导入.

关于javascript - 使用vite将原始图像数据导入到脚本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73847316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com