Created
April 12, 2017 16:38
-
-
Save kyo504/10c7567c5041b56fc11cdd149b1292bb to your computer and use it in GitHub Desktop.
Store base64 image with AsyncStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { | |
AppRegistry, | |
StyleSheet, | |
View, | |
ImageStore, | |
Image, | |
ImageEditor, | |
AsyncStorage, | |
Button, | |
} from 'react-native'; | |
export default class RNImageSample extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
pictureBase64: null, | |
} | |
} | |
getImageFromNetwork() { | |
const imageURL = "https://unsplash.it/300/300?random"; | |
Image.getSize(imageURL, (width, height) => { | |
const imageSize = { | |
size: { | |
width, | |
height | |
}, | |
offset: { | |
x: 0, | |
y: 0, | |
} | |
}; | |
ImageEditor.cropImage(imageURL, imageSize, (imageURI) => { | |
// console.log(imageURI); | |
ImageStore.getBase64ForTag(imageURI, (base64Data) => { | |
// console.log(base64Data); | |
this.setState({ pictureBase64: `data:image/jpg;base64,${base64Data}` }); | |
ImageStore.removeImageForTag(imageURI); | |
}, (reason) => console.log(reason)) | |
}, (reason) => console.log(reason)) | |
}, (reason) => console.log(reason)) | |
} | |
saveImage() { | |
AsyncStorage.setItem('image', this.state.pictureBase64) | |
} | |
loadImage() { | |
AsyncStorage.getItem('image', (error, result) => { | |
this.setState({ pictureBase64: result }); | |
}) | |
} | |
render() { | |
return ( | |
<View style={styles.container}> | |
{this.state.pictureBase64 && ( | |
<Image style={styles.image} source={{ uri: this.state.pictureBase64 }} /> | |
)} | |
<View style={{flexDirection:'row'}}> | |
<Button title='Fetch' onPress={() => this.getImageFromNetwork()} /> | |
<Button title='Load' onPress={() => this.loadImage()} /> | |
<Button title='Save' onPress={() => this.saveImage()} /> | |
</View> | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: 'center', | |
alignItems: 'center', | |
backgroundColor: '#F5FCFF', | |
}, | |
image: { | |
width: 200, | |
height: 200, | |
borderWidth: 1, | |
borderColor: 'red', | |
} | |
}); | |
AppRegistry.registerComponent('RNImageSample', () => RNImageSample); |
Just replying if anyone was arrived here today, you're probably trying to fit a lot of data inside a object and it overflow the quantity of memory you have.
DO NOT store images at AsyncStorage before apply a downscale or another filter and anyway be carefull!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm facing this error while trying this code.
I'll be grateful if I get some help or solution.
Attaching this snapshot for your reference.
Thanks.