【问题标题】:Convert image to base64 React Native将图像转换为 base64 React Native
【发布时间】:2022-10-17 20:52:44
【问题描述】:

我正在尝试为我的 react 本机应用程序实现一个头像,其中将图片转换为 base64 以使用 GraphQL 存储在 MongoDb 中。我得到的最远的是使用存储 img uri 路径但想要字符串的 imagePicker。

我已尝试对图像进行编码和解码,但一直出错并且应用程序中断

import React, { useContext, useState } from 'react'
import {
    SafeAreaView,
    Text,
    StyleSheet,
    View,
    Keyboard,
    KeyboardAvoidingView,
    TouchableWithoutFeedback,
    Platform
} from 'react-native'
import { useFonts } from 'expo-font';
import colors from '../../config/colors'
import CustomButton from '../../components/CustomButton';
import { useForm } from 'react-hook-form'
import { useNavigation } from '@react-navigation/core'
import BlueTextInput from '../../components/BlueTextInput';
import AddPicButton from '../../components/AddPicButton';
import * as ImagePicker from 'expo-image-picker';
import AuthContext from '../../context/auth-context'
import { logIn } from '../../util'


const CreateFanProfile = ({ route }) => {
    const [image, setImage] = useState(null);
    const choosePhotoFromLibrary = async () => {
        const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
        if (permissionResult.granted === false) {
            alert("Permission to access camera roll is required!");
            return;
        }
        const pickerResult = await ImagePicker.launchImageLibraryAsync();
        if (!pickerResult.cancelled) {
            setImage(pickerResult.uri);
        }
    }
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const onNextPressed = async (data) => {
        const username = route.params.username;
        setEmail(route.params.email);
        setPassword(route.params.password);
        const role = route.params.role;

        const { name, bio } = data;
        let requestBody = {
            query: `
                mutation {
                    createUser (userInput: {username: "${username}", password: "${password}",
                        email: "${email}", role: "${role}", name: "${name}", bio: "${bio}", 
                        avatar: "${image}", subscription: false}) {
                        _id
                    }
                }
            `
        };
    }
    if (!loaded) {
        return null;
    }
    return (
        <SafeAreaView style={styles.container}>
            <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
                <View style={styles.picContainer}>
                        <AddPicButton
                            onPress={choosePhotoFromLibrary}
                            image={image}
                        />
                        <Text style={styles.bottomText}>ADD A PICTURE</Text>

                    </View>
            </TouchableWithoutFeedback>
        </SafeAreaView>
    )
}
export default CreateFanProfile

【问题讨论】:

  • 这个包可能会帮助npm install react-native-image-base64 --save
  • 对于这种情况,是否有更好的解决方案可以将图像直接存储到 mongodb。
  • 将base64存储到数据库中不是一个好主意,因为它会减慢速度,将它们作为base64发送。然后在服务器端转换回文件。然后将它们存储到磁盘中
  • 有没有比base 64更好的方法来做到这一点 - @ndotie

标签: reactjs mongodb react-native graphql base64


【解决方案1】:

安装后react-native-image-base64 从“react-native-image-base64”导入 ImgToBase64;

ImgToBase64.getBase64String('file://youfileurl') //is is where you put image url from the ImagePicker
  .then(base64String => doSomethingWith(base64String))
  .catch(err => doSomethingWith(err));

当然全部来自文档

【讨论】:

    【解决方案2】:

    Base64 是一个布尔值,您可以从 ImagePicker 中选择它以返回您上传的任何内容的 base64 字符串

    const pickImage = async () => {
        // No permissions request is necessary for launching the image library
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 0,
            base64: true
        });
    
        console.log(result);
    
        if (!result.cancelled) {
            setImage(result.uri);
        }
        console.log(result);
        
    };
    

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 2020-06-01
      相关资源
      最近更新 更多