Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Image to base64 in react native

I have used react-native-image-picker and now I select image from the Photo library. To send the that image to API I have to convert it first into base64 and then into byte array. I have the filepath in response.uri. How do I do it?

When I did console.log(response) I am getting this in result

'Response = ', {
  fileSize: 6581432,
  longitude: -17.548928333333333,
  uri: 'file:///Users/shubhamb/Library/Developer/CoreSimulator/Devices/B58314DF-F0A9-48D2-B68A-984A02271B72/data/Containers/Data/Application/63143214-8A03-4AC8-A79C-42EC9B82E841/tmp/2AACBC57-0C07-4C98-985E-154668E6A384.jpg',
  fileName: 'IMG_0003.JPG',
  latitude: 65.682895,
  origURL: 'assets-library://asset/asset.JPG?id=9F983DBA-EC35-42B8-8773-B597CF782EDD&ext=JPG',
  type: 'image/jpeg',
  height: 2002,
  width: 3000,
  timestamp: '2012-08-08T18:52:11Z',
  isVertical: false,
}

like image 948
user11426267 Avatar asked Dec 14 '22 11:12

user11426267


2 Answers

Since you're using react-native-image-picker, it already returns the Base64 value in its response

ImagePicker.showImagePicker(options, (response) => {
  const base64Value = response.data;
});

Documentation for the response

like image 56
rabbit87 Avatar answered Jan 12 '23 06:01

rabbit87


I suddenly ran into this issue while updating my app. What I found is that previous react-native-image-picker used to provide base64 as response.data. But now there is an includeBase64 in the options object so that you can control whether you need the base64 data or not. So my code became something like the following

captureTradeLicenseImage() {
    let options = {
        maxHeight: 250,
        maxWidth: 350,
        includeBase64: true //add this in the option to include base64 value in the response
    }
    ImagePicker.launchCamera(options, (response)  => {
        console.log('Response = ', response)
        if (response.didCancel) {
            console.log('User cancelled image picker')
        }
        else if (response.error) {
            console.log('ImagePicker Error: ', response.error)
        }
        else if (response.customButton) {
            console.log('User tapped custom button: ', response.customButton)
        }
        else if (response.fileSize > 5242880) {
            Alert.alert(
                "Nilamhut Say\'s",
                "Oops! the photos are too big. Max photo size is 4MB per photo. Please reduce the resolution or file size and retry",
                [
                    { text: "OK", onPress: () => console.log('ok Pressed') }
                ],
                { cancelable: false }
            )
        }
        else {
            this.setState({tradeLicenseImageData: response.base64}) //access like this
        }
    })
}
like image 44
masud_moni Avatar answered Jan 12 '23 06:01

masud_moni