如何在本机中保存和显示图像? [英] How to save and display and image in react-native?
问题描述
我有一个关于本机的问题.我使用名为"react-native-image-picker" 的模块来拾取图像并将其显示在我的应用中.
I have a question in react-native. Im using a module called "react-native-image-picker" to pick an image and display it on my app.
现在我想要的是将其存储在某个地方(数据库或本地存储),当我再次打开该应用程序时,我选择的图像应该在那里.但是我不知道什么是最好的选择.
Now what i want is to store it somewhere (database, or local storage) and when i open again the app, the image that i choosed should be there. But i dont know what is the best option to do it.
我已经试过阅读诸如react-native-fs和fetch-blob之类的东西,但是我想这对我没有帮助.
I've already tryied to read some stuff like react-native-fs and fetch-blob but it doesnt help me, i guess.
什么是最好的选择?
谢谢.
推荐答案
首先,根据条件渲染视图.例如,如果图像可用,则仅显示图像,否则显示TouchableOpacity,这将有助于选择图片:
First, renders view according to condition. For example if image is available then simply display the image else display TouchableOpacity which will help use to select pictures :
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>
)
}
}
希望它会对您有所帮助.
Hope it will help you.
这篇关于如何在本机中保存和显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!