我刚开始使用原生react,我正在练习将图像转换为二进制文件。我从网上随机下载了这张照片。我正在尝试将图像转换为二进制文件,通过API上传到服务器。服务器将输入作为二进制文件。我附上了下面的代码。我在网上搜索了一下,但找不到解决办法。
import React from 'react'
import {
View,
Text,
StyleSheet,
Image,
Button,
Alert
} from 'react-native'
let imagePath = './src/image/macTest.jpeg'
const imageToBinary = (imagePath) => {
//Alert.alert(imagePath)
// this function needs to convert image into the binary file
}
const App = () => {
return (
<View>
<Text style={styles.headerStyle}> Image </Text>
<Image
style={styles.imageStyle}
source= {require('./src/image/macTest.jpeg')}
/>
<Button
title="Binary Value"
onPress={() => imageToBinary(imagePath)}
/>
<View style= {styles.binaryStyle}>
<Text>
// binary value of the image
</Text>
</View>
</View>
)
}
const styles = StyleSheet.create({
headerStyle:{
fontSize: 20,
textAlign: 'center',
margin: 15
},
imageStyle:{
alignItems: 'center',
height: 300,
width: 450,
},
binaryStyle: {
borderWidth: 1,
borderColor: 'black',
width: 400,
height: 250,
margin: 5
}
})
export default App;
如果您使用Expo,则有FileSystem
:
https://docs.expo.dev/versions/latest/sdk/filesystem/#filesystemreadasstringasyncfileuri-选项
示例:
const img = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
另一种选择是react-native-image-picker
:
https://www.npmjs.com/package/react-native-image-picker