Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base64 string to image in react native

Problem

I created a social media app with expo's react native, and wanted to add the ability to upload images. Since expo won't let you convert a file to a blob to upload, I just uploaded the base64 image data as a string to the server database. How can I convert this data into the viewable image again after I download the data from off of the server?

like image 779
GIISE Avatar asked Jan 07 '18 06:01

GIISE


People also ask

How convert base64 to image in react native?

React Native allows image conversion in your app using the Image component. However, you cannot use this component to convert base64 images. In fact, you cannot use the base64 format for images in React Native without a specific API.

How do I get the base64 from image URL in react native?

import RNFS from 'react-native-fs'; var data = await RNFS. readFile( "file://path-to-file", 'base64'). then(res => { return res }); This works fine.

How do I display a binary image in react native?

To display binary data as image in React, we can convert the image's binary data to a base64 URL. Then we can set the src attribute of the img element to the base64 URL. We have the getImg function that makes a GET request to get an image from the imageUrl with fetch .

How do I open base64 PDF in react native?

You can use react-native-pdf package (https://www.npmjs.com/package/react-native-pdf). If you want to show the pdf in your app , this package would be quite helpful as it supports loading PDFs from base64 string for both ios and android .


1 Answers

You can do this:

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

In the base64Icon variable you need to put your base64 data after data:image/png;base64,. Like this:

var base64Icon = 'data:image/png;base64,{PLACE_YOUR_BASE64_DATA_HERE}';
like image 155
Sachin Avatar answered Sep 19 '22 13:09

Sachin