代码之家  ›  专栏  ›  技术社区  ›  Bad Coder

在React Native中将图像转换为二进制文件

  •  0
  • Bad Coder  · 技术社区  · 3 年前

    我是一个新的本地反应,我正在练习将图像转换为二进制文件。我从网上随机下载了这张图片。我正在尝试将图像转换为二进制文件,通过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;
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   GʀᴜᴍᴘʏCᴀᴛ    3 年前

    如果你在使用Expo,有 FileSystem :

    https://docs.expo.dev/versions/latest/sdk/filesystem/#filesystemreadasstringasyncfileuri-options

    例子:

    const img = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
    

    另一种选择是 react-native-image-picker :

    https://www.npmjs.com/package/react-native-image-picker