React Native中将图像转换为base64

4
如何在React Native中将本地图像转换为Base64并上传到服务器?请帮助解决这个问题。我已经尝试使用谷歌上可用的库,名称为“image-to-base64”npm。
4个回答

2
最初的回答:
使用Expo API。
import { ImageManipulator } from 'expo';

const response = await ImageManipulator.manipulateAsync("file to local path", [], { base64: true })
console.log('base64res' + JSON.stringify(response));

1

大家好,我们可以使用React Native中的Image Picker获取图像的base64字符串,用于个人资料等多种用途。以下是一段代码片段,可帮助在React Native中使用图像选择器函数获取base64字符串。

    selectPhotoTapped() {
const options = {
  quality: 1.0,
  maxWidth: 500,
  maxHeight: 500,
  storageOptions: {
    skipBackup: true,
  },
};

ImagePicker.showImagePicker(options, response => {
  console.log('Response = ', response.data);

  if (response.didCancel) {
    console.log('User cancelled photo picker');
  } else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  } else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  } else {
    // let source = { uri: response.uri };  <-- here you can get uri of image
    //  var RNFS = require('react-native-fs');
    // You can also display the image using data:
    let source =  'data:image/jpeg;base64,'+ [response.data];  //<-- here you can get image with base64string

    this.setState({
      avatarSource: source,
    });

    // this.setState({
    //   Profile_Picture:this.state.avatarSource
    // })
    // console.log(this.state.Profile_Picture)


  }
});                                                                             

}

在此之后,您可以使用 onPress 事件从您的库中获取图像,但在此之前,您需要授予权限以使用 Android 或 IOS 图像来自本地存储。 安装图像选择器的链接 使用此链接安装 React Native 中的图像选择器


0

唯一的解决方案是react-native-fs

import RNFS from 'react-native-fs';

RNFS.readFile(this.state.imagePath, 'base64')
.then(res =>{
  console.log(res);
});

0
使用 react-native-image-base64
import ImgToBase64 from 'react-native-image-base64';

ImgToBase64.getBase64String('file://path/to/file')
  .then(base64String => {
       // Send the base64String to server
   })
  .catch(err => console.log(err));

先生,您能给我发送一个例子吗? - Janak Naliyapara
非常感谢您,但我已经通过另一种方式解决了。 - Janak Naliyapara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接