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

Expo调用ImageManipulator.manipulate报TypeError undefined错误

React Native+Expo 拍照上传ImageManipulator报错修复

问题现象

调用图片处理方法对相机拍摄的图片做尺寸调整(resize为640*480、格式转jpg)时,持续抛出如下错误:

[TypeError: undefined is not an object (evaluating '_expo.ImageManipulator.manipulate')]

已确认传入方法的图片路径参数data.uri为有效值,该功能曾正常运行过一次,后续执行到对应代码行必现报错。预期实现逻辑为:拍摄图片后调整图片尺寸,再将处理后的图片上传至后端API接口。

问题复现代码片段

const manipResult = await ImageManipulator.manipulate(
    image,
    [{ resize: { width: 640, height: 480 } }],
    { format: 'jpg' }
);

错误根因

  1. 依赖导入方式错误:Expo SDK 38及以上版本中,ImageManipulator已从expo核心包拆分,成为独立官方依赖,不再通过import { ImageManipulator } from 'expo'导出。旧导入方式拿到的ImageManipulator值为undefined,调用方法时自然抛出类型错误,这也是本次报错的核心原因。
  2. API版本不匹配:独立包中的图片处理方法已更名为manipulateAsync,旧的manipulate方法名已废弃。
  3. 代码存在低级笔误:图片处理完成后赋值时写了不存在的变量manipResult0,且未正确读取处理结果的uri字段,就算导入正确也会触发后续报错。
  4. 相机实例判断逻辑错误:原代码仅判断cameraRef是否存在,未判断ref挂载的实际相机实例cameraRef.current,极端场景下会触发空对象调用错误。

修复步骤

  • 安装独立的expo-image-manipulator依赖
    npx expo install expo-image-manipulator
    
  • 替换原有错误的导入语句
    // 删除原有错误导入:import { ImageManipulator } from 'expo';
    import * as ImageManipulator from 'expo-image-manipulator';
    
  • 修正拍照逻辑中的方法调用、变量笔误、实例判断问题,修正后的takePicture方法代码如下:
    const takePicture = async () => {
      if (cameraRef.current) {
        try {
          const data = await cameraRef.current.takePictureAsync();
          console.log(data);
          // 注意调用的是manipulateAsync方法,不是旧版的manipulate
          const manipResult = await ImageManipulator.manipulateAsync(
            data.uri,
            [{ resize: { width: 640, height: 480 } }],
            { format: ImageManipulator.SaveFormat.JPEG, compress: 0.8 }
          );
          // 正确读取处理结果的uri字段,修正笔误
          setImage(manipResult.uri);
        } catch (error) {
          console.log(error);
        }
      }
    };
    
  • 清缓存重启项目,避免旧依赖缓存导致的异常:
    npx expo start -c
    

其他代码优化点

  • 原代码中uriToBase64、toServer方法缺少const声明,严格模式下会报错,补上关键字即可。
  • 调用uriToBase64时需要加await,否则拿到的是Promise对象而非实际base64字符串。
  • 若不需要base64格式上传,直接用expo-file-system的uploadAsync传本地uri即可,不需要额外转base64,能大幅减少内存占用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:48:22