Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - How to load local image using the uri in Image Component?

I know we can load the local image with:

<Image source={require('folder/image.png')}/>

But i need to load the image like this:

<Image source={{uri: 'folder/image.png'}}/>

It works for network images but it doesn't work for local images and even it does not give any error for local images and silently does not display the image. Can anyone tell how to load the local image using the uri property?

like image 490
Purple Bytes Avatar asked Dec 14 '18 11:12

Purple Bytes


Video Answer


1 Answers

These are the three ways to render images in react-native , In your case you can encode the image

  • you can require image

    source={require('/react-native/img/favicon.png')}

  • you can get image from web

    source={{uri: 'https://facebook.github.io/react-native/docs/assets/favicon.png'}}

  • or you can encode the image

    source={{uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='}}

as doc suggested as below

export default class DisplayAnImage extends Component {
  render() {
    return (
      <View>
        <Image
          source={require('/react-native/img/favicon.png')}
        />
        <Image
          style={{width: 50, height: 50}}
          source={{uri: 'https://facebook.github.io/react-native/docs/assets/favicon.png'}}
        />
        <Image
          style={{width: 66, height: 58}}
          source={{uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='}}
        />
      </View>
    );
  }
}

or you can create a json file that contains the encoded string of the image image.json

{imageString: '64encodedString'}

them import the file

import image from 'image.json';

then image

<Image source:{{uri:image.imageString}} />
like image 129
NuOne Avatar answered Sep 28 '22 13:09

NuOne