Skip to content

Instantly share code, notes, and snippets.

@kyo504
Created April 12, 2017 16:38
Show Gist options
  • Save kyo504/10c7567c5041b56fc11cdd149b1292bb to your computer and use it in GitHub Desktop.
Save kyo504/10c7567c5041b56fc11cdd149b1292bb to your computer and use it in GitHub Desktop.
Store base64 image with AsyncStorage
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);
@bleszerd
Copy link

bleszerd commented May 1, 2021

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