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

React Native如何从URL获取图片并转换为Base64格式

解决方案

直接使用React Native内置的Blob和FileReaderAPI即可实现需求,无需依赖任何第三方包,不存在组件废弃、停止维护的问题。完整实现代码如下:

const fetchAvatarToBase64 = async (accountId) => {
  try {
    const response = await fetch(
      `${BACKEND_URL}/api/visitors/getAvatar/${accountId}`
    );
    // 从响应中提取图片Blob对象
    const imageBlob = await response.blob();
    
    // 使用FileReader将Blob转为Base64格式
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      // 读取完成回调
      fileReader.onload = () => {
        // 返回的result为带媒体类型前缀的完整Base64内容,可直接传入Image组件使用
        resolve(fileReader.result);
      };
      // 读取失败回调
      fileReader.onerror = (error) => reject(error);
      // 启动读取,转换为DataURL格式(即带前缀的Base64)
      fileReader.readAsDataURL(imageBlob);
    });
  } catch (error) {
    console.error("头像获取及转Base64失败:", error);
    throw error;
  }
}

注意事项

  • 上述代码返回的结果默认带data:image/png;base64,前缀,可直接作为uri参数传入Image组件渲染:<Image source={{uri: base64Avatar}} style={{width: 100, height: 100}}/>
  • 如果你需要无前缀的纯Base64字符串,只需对返回结果做分割处理即可:const pureBase64 = fileReader.result.split(',')[1]
  • 该方案兼容React Native 0.60及以上所有版本,无需额外做原生端配置。

内容的提问来源于stack exchange,提问作者Ali Yar Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:06:10