Dancer
Dancer

Reputation: 17671

React Native - CameraRoll - Access base64 version of image

I am using RN Camera Roll (https://facebook.github.io/react-native/docs/cameraroll.html) to access a series of images for selection as part of a form. My question is - does anyone know if it's possible to access the base64 of the image - or the easiest method of conversion in this scenario.

Here is my usePhotos class:

 usePhotos = () => {
  CameraRoll.getPhotos({
      first: 20,
      assetType: 'Photos',
    })
    .then(r => {
      this.setState({ ADModalState:false,
        ADMediaCamera:false, isModalVisible:true, ADphotos: r.edges, ADPhotosBase:r.edges });
    })
    .catch((err) => {
       //Error Loading Images
       console.warn(err);
    });
  };

Upvotes: 1

Views: 1460

Answers (2)

Dancer
Dancer

Reputation: 17671

This was my eventual workaround:

if(Platform.OS === 'ios'){
      if (uriPhoto.startsWith('ph://'))
      {
        imagePATH = uriPhoto.substring(5,41);
        let photoPATH = `assets-library://asset/asset.JPG?id=${imagePATH}&ext=JPG`;

        const dest = `${RNFS.TemporaryDirectoryPath}${Math.random().toString(36).substring(7)}.jpg`;

        RNFS.copyAssetsFileIOS(photoPATH, dest, 500, 500, 1.0, 1.0, 'contain')
          .then(data => {
            RNFS.readFile(data, 'base64')
              .then(base64 => {

                this.state.ADImageArray.push(uriPhoto);
                this.props.encodedImage(base64);

                //TODO - Delete file
              });
          });
      }
    }
    else if(Platform.OS === 'android'){

      RNFS.readFile(uriPhoto, 'base64')
        .then(base64 => {
          this.state.ADImageArray.push(uriPhoto);
          this.props.encodedImage(base64);
        });
    }

Upvotes: 0

Uber
Uber

Reputation: 331

I don't think it is possible with RN Camera Form, but what I used as a solution a year ago was this npm package: https://www.npmjs.com/package/react-native-image-base64 It is stil downloaded quite a lot so I assume it is still functioning

Upvotes: 2

Related Questions