Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In react native, how to convert a base64 image to jpg then save to temp path?

In react-native, converting an image to BASE64 format is easy, with a little help of react-native-fetch-blob, I simply do:

RNFetchBlob.fs.readFile(filePath, 'base64')
    .then((data) => console.log(data));

But, what about the other way around? I know there are some packages out there that does it, but I wonder if it's possible to do it with only react-native-fetch-blob or react-native-fs?

What I want is that after converting and saving the BASE64 image to a file, I am able to display it like this:

<Image
    source={{ uri: <path/to/converted/image> }}
    style={{ ... }}
/>
like image 255
K.Wu Avatar asked Feb 17 '18 04:02

K.Wu


1 Answers

Turns out it's not tricky at all, suppose I have a BASE64 image, if I want to convert it to a JPG, just use react-native-fs like so:

import RNFS from 'react-native-fs';

const imageDate = '<some base64 data>';
const imagePath = `${RNFS.TemporaryDirectoryPath}image.jpg`;

RNFS.writeFile(imagePath, imageData, 'base64')
    .then(() => console.log('Image converted to jpg and saved at ' + imagePath));

That's all

like image 160
K.Wu Avatar answered Sep 20 '22 00:09

K.Wu