React-Native: Convert image url to base64 string

前端 未结 9 514
轻奢々
轻奢々 2020-12-08 19:03

I\'m building a react native app that needs to store images at base64 string format for offline viewing capabilities.

What library / function would give me the best

相关标签:
9条回答
  • 2020-12-08 19:37

    You can use react-native-image-base64. You have to give image url and it returns the base64 string of image.

    ImgToBase64.getBase64String('file://youfileurl')
      .then(base64String => doSomethingWith(base64String))
      .catch(err => doSomethingWith(err));
    
    0 讨论(0)
  • 2020-12-08 19:38

    The standalone expo FileSystem package makes this simple:

    const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
    
    • https://docs.expo.io/versions/latest/sdk/filesystem/
    • https://github.com/expo/expo/tree/master/packages/expo-file-system

    As 2019-09-27 this package handles both file:// and content:// uri's

    0 讨论(0)
  • 2020-12-08 19:42

    There is a better way: Install this react-native-fs, IF you don't already have it.

    import RNFS from 'react-native-fs';
    
    RNFS.readFile(this.state.imagePath, 'base64')
    .then(res =>{
      console.log(res);
    });
    
    0 讨论(0)
  • 2020-12-08 19:44

    To convert image to base64 in React native, the FileReader utility is helpful:

    const fileReader = new FileReader();
    fileReader.onload = fileLoadedEvent => {
      const base64Image = fileLoadedEvent.target.result;
    };
    fileReader.readAsDataURL(imagepath); 
    

    This requires react-native-file.

    Another alternative, and probably the preferred alternative, is to use NativeModules. The Medium article shows how. It requires creating a native module.

    NativeModules.ReadImageData.readImage(path, (base64Image) => {
      // Do something here.
    });
    
    0 讨论(0)
  • 2020-12-08 19:45

    I use rn-fetch-blob, basically it provides lot of file system and network functions make transferring data pretty easy.

    react-native-fetch-blob is deprecated

    import RNFetchBlob from "rn-fetch-blob";
    const fs = RNFetchBlob.fs;
    let imagePath = null;
    RNFetchBlob.config({
      fileCache: true
    })
      .fetch("GET", "http://www.example.com/image.png")
      // the image is now dowloaded to device's storage
      .then(resp => {
        // the image path you can use it directly with Image component
        imagePath = resp.path();
        return resp.readFile("base64");
      })
      .then(base64Data => {
        // here's base64 encoded image
        console.log(base64Data);
        // remove the file from storage
        return fs.unlink(imagePath);
      });
    

    source Project Wiki

    0 讨论(0)
  • 2020-12-08 19:53

    I used another package: react-native-fs

    import RNFS from 'react-native-fs';
    
    var data = await RNFS.readFile( "file://path-to-file", 'base64').then(res => { return res });
    

    This works fine.

    0 讨论(0)
提交回复
热议问题