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

在React Native中使用react-native-image-picker如何压缩图片至指定尺寸与大小

解决方案

方案说明

react-native-image-picker 本身内置了分辨率限制、质量压缩参数,无需额外引入第三方图片处理库,直接修改配置项即可满足需求:

  • 配置maxWidth、maxHeight为1024:选中的图片会自动等比缩放到最长边不超过1024,不会拉伸变形
  • 配置quality参数:调整JPG压缩质量,取值范围0~1,建议初始设为0.7,若压缩后仍超过900KB可适当下调
  • 强制指定图片格式为JPG:避免PNG无损格式无法有效压缩体积

修改后的完整代码

import {launchImageLibrary} from 'react-native-image-picker';


const Upload = ({navigation}) => {
  const options = {
    title: 'Load Photo',
    customButtons: [
      {name: 'button_id_1', title: 'CustomButton 1'},
      {name: 'button_id_2', title: 'CustomButton 2'},
    ],
    storageOptions: {
      skipBackup: true,
      path: 'images',
    },
    // 新增压缩配置
    maxWidth: 1024,
    maxHeight: 1024,
    quality: 0.7,
    mediaType: 'photo',
    includeBase64: false, // 不需要base64的话关闭减少内存占用
  };


  const showCameraRoll = () => {
    launchImageLibrary(options, (response) => {
      if (response.error) {
        // 错误处理逻辑
        console.log('图片选择错误:', response.error);
        return;
      }
      if (response.didCancel) {
        // 用户取消选择处理
        return;
      }
      // 注意:新版react-native-image-picker返回的资源在assets数组中
      const asset = response.assets?.[0];
      if (!asset?.uri) return;

      setImageSource(asset.uri);
      const form = new FormData();
      form.append('image', {
        name: 'SampleFile.jpg',
        uri: asset.uri,
        type: asset.type || 'image/jpg',
      });
      // 后续上传逻辑
    });
  };
}

补充说明

  • 如果调整quality到0.6后体积仍超过900KB,可继续下调到0.5,正常1024边长的JPG图片0.5质量基本都在500KB以内,符合要求
  • 若你使用的是4.x以下的旧版本react-native-image-picker,返回的资源没有assets封装,直接取response.uri即可

内容的提问来源于stack exchange,提问作者jack volten

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:00:01