如何在本机中保存和显示图像?

时间:2019-09-06 16:05:24

标签: image react-native store

我有一个关于本机的问题。我使用名为“ react-native-image-picker” 的模块来拾取图像并将其显示在我的应用中。

现在,我想要将其存储在某个地方(数据库或本地存储),当我再次打开该应用程序时,我选择的图像应该在那里。但是我不知道什么是最好的选择。

我已经试过阅读诸如react-native-fs和fetch-blob之类的东西,但是我想这对我没有帮助。

什么是最好的选择?

谢谢。

2 个答案:

答案 0 :(得分:2)

首先,根据条件渲染视图。例如,如果图像可用,则仅显示图像,否则显示TouchableOpacity,这将有助于选择图片:

import React, { Component } from React;
import { View, TouchableOpacity, Text, Image } from 'react-native';
import ImagePicker from 'react-native-image-picker';
import AsyncStorage from '@react-native-community/async-storage';


class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isImageAvailable: false,
            profilePic: null
        }
    }

    componentDidMount = () => {
        this.getImage();
    }

    getImage = async () => {
        const profilePic = await AsyncStorage.getItem("profilePic");
        if (profilePic) {
            this.setState({
                isImageAvailable: true,
                profilePic: JSON.parse(profilePic)
            });
        }
    }

    selectProfilePic = () => {
        const options = {
            title: 'Select Avatar',
            storageOptions: {
                skipBackup: true,
                path: 'images',
            },
        };

        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled image picker');
            } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            } else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            } else {
                const source = { uri: response.uri };

                // You can also display the image using data:
                // const source = { uri: 'data:image/jpeg;base64,' + response.data };
                AsyncStorage.setItem("profilePic", JSON.stringify(source));
                this.setState({
                    profilePic: source,
                    isImageAvailable: true
                });
            }
        });
    }

    render() {
        return (
            <View>
                {
                    this.state.isImageAvailable && (
                        <Image source={this.state.profilePic} style={{ width: 200, height: 200 }} />

                    )
                }

                {
                    !this.state.isImageAvailable && (
                        <TouchableOpacity onPress={this.selectProfilePic}>
                            <Text>Choose Profile Pic</Text>
                        </TouchableOpacity>
                    )
                }
            </View>
        )
    }
} 

希望它会对您有所帮助。

答案 1 :(得分:0)

您可以使用realmdb作为Asyncstorage的替代。