How to read files starting with ph:// as base64 string with React Native?

Viewed 1207

I'm trying to read image files starting with ph:// and convert them to base64 string with RNFS but unfortunately I get ENOENT: no such file or directory error.

How can I read these files and convert them to base64?

2 Answers

You can use react-native-convert-ph-asset

import RNConvertPhAsset from 'react-native-convert-ph-asset';

const convertLocalIdentifierToAssetLibrary = async (localIdentifier) => {
  return await RNHeicConverter.convert({
    // options
    path: localIdentifier,
  });
};

and then use react-native-fs to convert it to base64

 const base64 = await RNFS.readFile(newpath.path, 'base64');[enter link description here][2]

If you need to use your ph:// uri for an image from your local device, you can use the uri option on the Image component from React-Native. You will see this in action in my code sample, below. But if you need to convert to base64 to get something like a file:/// prefix to your uri then you can still use RNFS.

If you are on iOS, you can do something like the following with RNFS to convert the file path from ph:// to file:///:

<TouchableHighlight
  onPress={async () => {
    const destPath = RNFS.CachesDirectoryPath + '/MyPic.jpg';
    
    try {
      await RNFS.copyAssetsFileIOS(imageUri, destPath, 0, 0);
      console.log('destPath', destPath);
      } catch (error) {console.log(error);} 

      navigation.navigate('SelectedPicture', {
        uri: 'file://' + destPath,
          });
   }}>
    <Image source={{uri: imageUri}} style={styles.image} />
</TouchableHighlight>

Note that the path may not begin with "file://" so I added it in manually.

See here for more detail: https://github.com/itinance/react-native-fs#ios-only-copyassetsvideoiosvideouri-string-destpath-string-promisestring

I believe RNFS.copyAssetsFileIOS does something similar to react-native-convert-ph-asset under the hood.

Related