Convert Captured Image to base64 in React-Native(Expo)

#1

I am new to React-Native(Expo). I want to take Image Capture, convert it to base64 and save it to state.

My code is like this:

return (
        <View style={{ flex: 1 }}>
          <Camera  style={{ flex: 1 }} type={this.state.type}>
            <View
              style={{
                flex: 1,
                backgroundColor: 'transparent',
                flexDirection: 'row',
              }}>
              <TouchableOpacity
                style={{
                  flex: 0.1,
                  alignSelf: 'flex-end',
                  alignItems: 'center',
                }}
                onPress={() => {
                  Camera.takePictureAsync({
                    base64: true,
                  }).then(data => {
                          this.setState({base64:data.base64})
                          });
                }}>
                <Text  style={{color: 'white' }}>
                  Capture
                </Text>
              </TouchableOpacity>
            </View>
          </Camera>
        </View>
      );

It says takePictureAsync() is not a function. Screenshot of my error is:

Does anyone have an idea about what is the problem? How can I Capture Image and save its base64 to state?

#2

takePictureAsync is an instance method, so you should be calling it on your Camera ref, not Camera module itself. I.e. you’d want to do something like

// ...
<Camera ref={ref => { this.camera = ref; }} />
// ...
onPress={async () => {
  if (this.camera) {
    let photo = await this.camera.takePictureAsync();
  }
}}

See docs at https://docs.expo.io/versions/latest/sdk/camera for more info

closed #3

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.