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

如何将Base64文本解码为二进制图片?解决前端解码损坏问题

解决Base64解码图片损坏的问题

你遇到的问题根源是:window.atob解码后得到的是字符串,直接将字符串存入Blob时,浏览器会按UTF-8编码重新处理,破坏了图片原有的二进制数据结构。正确的做法是把Base64解码后的内容转换成Uint8Array(二进制数组),再创建Blob。

前端正确解码代码

// 假设data是后端返回的JSON对象,包含image字段(Base64字符串)
const base64Str = data.image;
// 解码Base64为二进制数组
const binaryStr = window.atob(base64Str);
const length = binaryStr.length;
const uint8Array = new Uint8Array(length);
for (let i = 0; i < length; i++) {
  uint8Array[i] = binaryStr.charCodeAt(i);
}
// 创建Blob并生成URL,需替换为实际图片的MIME类型(如image/png、image/jpeg)
const blob = new Blob([uint8Array], { type: 'image/jpeg' });
const imageUrl = URL.createObjectURL(blob);
// 将生成的URL赋值给img标签即可显示图片
document.querySelector('img').src = imageUrl;

后端优化建议

为了让前端能准确指定图片的MIME类型,建议后端存储图片时同时保存文件的MIME类型:

app.post('/image', multer().single('image'), (req, res) => {
    const image = Buffer.from(req.file.buffer).toString('base64');
    const mimeType = req.file.mimetype; // 获取文件原生MIME类型
    database.collection('images').insertOne({ image, mimeType });
    // 返回数据时带上mimeType
    res.json({ image, mimeType });
});

这样前端可以直接使用后端返回的mimeType创建Blob,无需手动猜测:

const blob = new Blob([uint8Array], { type: data.mimeType });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:27:41