Skip to content

Instantly share code, notes, and snippets.

@kyo504
Created April 12, 2017 16:38
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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);
@Reshmigovekar
Copy link

I'm facing this error while trying this code.

JSON value '<null>' of type NSNull cannot be converted to NSString
reactConsoleErrorHandler @ 192.168.1.102.xip.io:8081/index.bundle?platform=ios&dev=true&minify=false:7010

I'll be grateful if I get some help or solution.
Attaching this snapshot for your reference.

img_0031

Thanks.

@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