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

如何将expo-image-picker的Base64/URI数据转换为二进制文件?

解决Expo Image Picker转二进制文件失败的问题

两种实用转换方案

1. 基于Base64结果转换二进制

Expo Image Picker返回的Base64字符串默认带有data:image/xxx;base64,前缀,直接用atob会解析失败,需要先剥离前缀再处理:

import * as ImagePicker from 'expo-image-picker';

const pickImage = async () => {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    quality: 1,
    base64: true, // 开启Base64返回
  });

  if (!result.canceled) {
    // 提取纯Base64字符串(移除前缀)
    const pureBase64 = result.assets[0].base64.replace(/^data:image\/\w+;base64,/, '');
    // 转换为Uint8Array格式的二进制数据
    const binaryData = Uint8Array.from(atob(pureBase64), char => char.charCodeAt(0));
    
    // 此处可使用binaryData完成上传、存储等后续操作
  }
};

2. 基于文件URI读取二进制(更稳定)

如果Base64转换仍有问题,直接通过Expo File System读取文件URI获取二进制:

import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';

const pickImageAndGetBinary = async () => {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    quality: 1,
  });

  if (!result.canceled) {
    // 读取文件为Base64格式,再转二进制数组
    const fileBase64 = await FileSystem.readAsStringAsync(result.assets[0].uri, {
      encoding: FileSystem.EncodingType.Base64,
    });
    const binaryData = Uint8Array.from(atob(fileBase64), char => char.charCodeAt(0));
    
    // 使用binaryData进行后续业务操作
  }
};

直接用atob/btoa无效的原因

  • Expo返回的Base64包含MIME类型前缀,atob无法解析带前缀的字符串,必须先剥离。
  • atob返回的是ASCII字符串,并非真正的二进制数据,需要通过Uint8Array将每个字符的ASCII码转换为二进制字节。

内容的提问来源于stack exchange,提问作者Nguyen The Son

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:32:17