androidiosreact-nativecamera-roll

How to fetch random image from camera-roll using react native?


I have requirement where i need to get a random image every time when i click an button. I don't want picker to come up for the camera-roll with images, instead random image should selected from the camera folder and display in the image view. I have followed the official FB tutorial of camera roll. Please find the code as below

_handleButtonPress = () => {
   CameraRoll.getPhotos({
       first: 20,
       assetType: 'Photos',
     })
     .then(r => {
       this.setState({ photos: r.edges });
     })
     .catch((err) => {

     });
   };

But this code will select the recently clicked images and display in the picker. Instead of to randomly select the uri of the image and display in the imageview. Any help is appreciated.

Regards, Sharath


Solution

  • You essentially have the photos and all the necessary metadata once you set the state: this.setState({ photos: r.edges })

    All you have to do is pick a random image from there. Here's how I did it:

    import React, { Component } from 'react';
    import {
      StyleSheet,
      View,
      Image,
      CameraRoll,
      Button
    } from 'react-native';
    
    export default class App extends Component {
      constructor(props) {
        super(props)
    
        this.state = {
          img: null
        }
      }
    
      getRandomImage = () => {
        const fetchParams = {
          first: 25,
        }
    
        CameraRoll.getPhotos(fetchParams)
          .then(data => {
            const assets = data.edges
            const images = assets.map((asset) => asset.node.image)
            const random = Math.floor(Math.random() * images.length)
            this.setState({
              img: images[random]
            })
          })
          .catch(err => console.log)
      }
    
      render() {
        return (
          <View style={styles.container}>
            { this.state.img ?
              <Image
                style={styles.image}
                source={{ uri: this.state.img.uri }}
              />
              : null
            }
            <Button title="Get Random Image from CameraRoll" onPress={this.getRandomImage}/>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      },
      image: {
        width: '100%',
        height: '75%',
        margin: 10,
      }
    });