简体   繁体   中英

react-native-camera convert Image base64 to jpeg

I've managed to use react-native-camera to take an image then display it in the <Image> element, then send the image's base64 string back to my back-end, however, I can't manage to display the image once it is on my back-end because it's in base64, the image is displayed properly in the <Image> element with the src attribute set in the data:image/jpeg;base64,{BASE64_HERE} format.

Could you guide me through to make this work?

Here's my code

'use strict';

import React, { PureComponent } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Image,
} from 'react-native';
import {RNCamera} from 'react-native-camera';
import RNFS from 'react-native-fs';

class App extends PureComponent {

    state = {
        img: false,
        b64: null,
    }

  render() {
    return (

      <View style={styles.container}>

        <RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          style={styles.preview}
          type={RNCamera.Constants.Type.front}
          flashMode={RNCamera.Constants.FlashMode.off}
          androidCameraPermissionOptions={{
            title: 'Permission to use camera',
            message: 'We need your permission to use your camera',
            buttonPositive: 'Ok',
            buttonNegative: 'Cancel',
          }}
          androidRecordAudioPermissionOptions={null}
          onGoogleVisionBarcodesDetected={null}
        />

        <View style={{flex: 0, flexDirection: 'row', justifyContent: 'center'}}>
          <TouchableOpacity
            onPress={this.takePicture.bind(this)}
            style={styles.capture}>
            <Text style={{fontSize: 14}}> SNAP </Text>
          </TouchableOpacity>

        </View>

        {this.state.img ? (
                <Image
                    source={{
                        isStatic: true,
                        uri: this.state.b64,
                    }}
                    style={{height: 100, width:100}}
        /> ) : null }

      </View>
    );
  }

    takePicture = async () => {
        if (this.camera) {
            const options = {quality: 0.5, base64: true};
            const data = await this.camera.takePictureAsync(options);

            var request = new XMLHttpRequest();

            request.onreadystatechange = (e) => {
                if (request.readyState !== 4) {
                    return;
                }

                if (request.status === 200) {
                    alert('success');
                } else {
                    alert('error' + JSON.stringify(e));
                }
            };



            request.open('POST', 'http://myurl/get_img.php');
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


            var filepath = data.uri.split('//')[1];
            var imageUriBase64 = await RNFS.readFile(filepath, 'base64');


            this.setState({b64: 'data:image/jpeg;base64,' + imageUriBase64, img: true});

            request.send('data=' + imageUriBase64);



        }

    }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'black',
  },
  preview: {
    justifyContent: 'flex-end',
    alignItems: 'center',
    width: 200,
    height: 200,
  },
  capture: {
    flex: 0,
    backgroundColor: '#fff',
    borderRadius: 5,
    padding: 15,
    paddingHorizontal: 20,
    alignSelf: 'center',
    margin: 20,
  },
});


export default App;


It may be due to the fact that you are trying to access the data.uri property when base64 option is set to true . Can you check the value of data.uri ?

It's possible that data.uri is undefined when base64 is true, which leads RNFS.readFile to fail.

如果从后端获取图像时无法显示图像(此处未提供代码片段),则可能是压缩形式,或者您可能未添加前缀'data:image/jpeg;base64,'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM