Search code examples
iosreact-nativeimage-rotationrn-fetch-blob

Rotate image and save in React-Native


I am going to rotate the image in react–native and I would like to get base64 of rotated image. I used several libraries

  1. react-native-image-rotate: It's working well on Android but on iOS I get rct-image-store://1 as url so I tried getting base64 using rn-fetch-blob but it throws error that can't recognize that url.

  2. react-native-image-resizer: I used this but the response is not good in iOS. If I set -90 then rotate -180, if I set -180 then it's rotating as -270.

Please help me on this problem, how can I rotate the image in iOS.

I need to rotate the image as -90, -180, -270, -360(original).


Solution

  • Finally, I found answer.

    import ImageRotate from 'react-native-image-rotate';
    import ImageResizer from 'react-native-image-resizer';
    import RNFetchBlob from 'rn-fetch-blob';
    
    ImageRotate.rotateImage(
            this.state.image.uri,
            rotateDegree,
            uri => {
              if (Platform.OS === 'android') {
                console.log('rotate', uri);
                RNFetchBlob.fs.readFile(uri, 'base64').then(data => {
                  const object = {};
                  object.base64 = data;
                  object.width = this.state.image.height;
                  object.height = this.state.image.width;
                  object.uri = uri;
                  this.setState({image: object, spinner: false});
                });
              } else {
                console.log(uri);
                const outputPath = `${RNFetchBlob.fs.dirs.DocumentDir}`;
    
                ImageResizer.createResizedImage(
                  uri,
                  this.state.image.height,
                  this.state.image.width,
                  'JPEG',
                  100,
                  0,
                  outputPath,
                ).then(response => {
                  console.log(response.uri, response.size);
                  let imageUri = response.uri;
                  if (Platform.OS === 'ios') {
                    imageUri = imageUri.split('file://')[1];
                  }
                  RNFetchBlob.fs.readFile(imageUri, 'base64').then(resData => {
                    const object = {};
                    object.base64 = resData;
                    object.width = this.state.image.height;
                    object.height = this.state.image.width;
                    object.uri = response.uri;
                    this.setState({image: object, spinner: false});
                  });
                });
              }
            },
            error => {
              console.error(error);
            },
          );
        }