Mertcan Seğmen
Mertcan Seğmen

Reputation: 933

React Native - Convert base64 encoded image to URI

I'm holding a list of objects that contains base64 encoded image data as a state, so I can show them to the user in a list component. Something like this:

[
    {
        id: "23789373",
        address: "92 West Sunnyslope Street Woodhaven, NY 11421",
        thumbnail: "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYA...",
    },
    {
        id: "91501148",
        address: "62 North St Severn, MD 21144",
        thumbnail: "yblAAAAHElEQVQI12P4//8/w38GE0DHxljNB...",
    },
    //...
]

The thing is, it seems like base64 encoded data is way too long, so after having about 5 objects, the app starts to really slow down.

I've found that someone having the same problem as mine on a React-Redux app wrote a medium article. She explains it like this:

The overwhelming amount of data would clutter your state unnecessarily, all of this because you are storing the full base64 image in your store. While I was using this approach just to “get it done”, I soon realized that my debugging experience was getting out of hand. With the support of a co worker we started using this nice little thing called createObjectURL . What this does is create a DOMString containing a URL that references the image. This way in our store we could simply save this normal URL-like reference instead of a gigantic blob of data!

Since there is no createObjectURL method in React Native, is there a way I can store the images in memory, and use the URI as the state?

Upvotes: 1

Views: 2460

Answers (2)

Gaurav Roy
Gaurav Roy

Reputation: 12235

I've faced a similiar challenge in my past experience, from what my final conclusion was,handling multiple images with the base64 will be troublesome.

Even though you can display it,

var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANS...';
<Image style={{width: 50, height: 50}} source={{uri: base64Icon}}/>

but having 1000s of images will cause issues and there will be challenges like :

  1. Mobile phones has limitations on the RAM and processor speed.Sending 100 image base64 in a flatlist and rendering will slow down your phone and app significantly-- so not recommended.
  2. Your app , in such scenarios will consume a lot of memory, and to process that proportionally fast phone memory is required -- so its not recommended
  3. Your overall UI/UX will be very bad , as if apps are slow and dont give the feel of native, your ratings and downloads will drop.

So it's best that you host your images from the backend in cloudinary etc, and just send the URI in thumbnail instead of the whole base64.

Hope that helps. feel free for doubts

Upvotes: 1

ebyte
ebyte

Reputation: 1517

RNFS.writeFile ?

import RNFS from 'react-native-fs';

RNFS.writeFile(RNFS.CachesDirectoryPath + '/a.jpeg', base64, 'base64')

// RNFS.CachesDirectoryPath + '/a.jpeg'

Upvotes: 3

Related Questions