Img 标签 src 调用 API 返回 base64 字符串的解决办法
在前端开发过程中,我们经常会遇到动态加载图片的需求。一种常见的方法是通过 JavaScript 向后端 API 发送请求,获取图片数据并将其转换为 Base64 字符串来显示。本文将详细介绍如何实现这一功能,并提供多个示例代码片段来帮助开发者更好地理解这一过程。
基本概念与作用
在 Web 开发中,<img>
标签用于展示图像。当图像源(src
属性)指向一个 Base64 编码的字符串时,浏览器会直接解析该字符串并在页面上显示对应的图像。这种方式非常适用于较小的图像文件,如图标、Logo 或者简单的图形,因为可以减少 HTTP 请求的数量,从而提高页面加载速度。
示例一:使用 Fetch API 获取 Base64 图像
代码示例
// 示例:使用 Fetch API 从服务器获取 Base64 编码的图像数据
async function fetchImage() {
const response = await fetch('https://api.example.com/image');
if (!response.ok) {
throw new Error(`Failed to fetch image: ${
response.statusText}`);
}
// 将 Blob 对象转换为 Base64 字符串
const blob = await response.blob();
const urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL(blob);
// 在 <img> 标签中显示图像
const imgElement = document.createElement('img');
imgElement.src = imageUrl;
document.body.appendChild(imgElement);
}
fetchImage().catch(console.error);
说明
这段代码使用了 Fetch API 来请求图像数据,并将响应体转换为 Blob 对象。Blob 对象接着被转换成一个 URL,这个 URL 可以直接设置为 <img>
元素的 src
属性。
示例二:使用 XMLHttpRequest 获取 Base64 图像
代码示例
function fetchImageXhr() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/image',