You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Svelte项目中如何通过Vite正确获取图片原始数据并转为Uint8Array

解决方案

问题出在你用?raw导入二进制文件——Vite会把?raw的内容按UTF-8文本解析,但PNG这类二进制文件包含大量非UTF-8兼容的字节,解析时这些无效字节会被替换为占位字符,导致转成Uint8Array后数据损坏。

下面是两种无需fetch的正确方案:

方案1:直接导入为Uint8Array(推荐)

使用Vite的?binary后缀导入,它会直接返回原始二进制数据的Uint8Array,不需要手动转换:

import imageData from "@/assets/image.png?binary";

// 直接使用Uint8Array格式的原始数据
console.log(imageData); // 输出正确的PNG文件头:[137, 80, 78, 71, 13, 10, 26, 10, ...]

// 转base64字符串
const base64 = btoa(String.fromCharCode(...imageData));

// 转Blob
const blob = new Blob([imageData], { type: "image/png" });

方案2:导入为base64格式的URL

如果需要base64格式,可以用?url后缀导入,Vite会自动将小体积资产转为data:开头的base64 URL(体积阈值可通过vite.config.js的assetInlineLimit配置调整),之后可以提取出纯base64内容并转换:

import imageUrl from "@/assets/image.png?url";

if (imageUrl.startsWith("data:")) {
  // 提取base64部分
  const base64 = imageUrl.split(",")[1];
  
  // 将base64转为Uint8Array
  const binaryString = atob(base64);
  const uint8Array = Uint8Array.from(binaryString, char => char.charCodeAt(0));
  
  // 转Blob
  const blob = new Blob([uint8Array], { type: "image/png" });
}

这两种方案都是在编译阶段完成资产处理,完全避开了fetch的Basic Auth问题。

内容的提问来源于stack exchange,提问作者arckoor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:01:01