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

一笑奈何 提交于 2021-02-07 14:20:43

问题


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={{ ... }}
/>

回答1:


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



来源:https://stackoverflow.com/questions/48837840/in-react-native-how-to-convert-a-base64-image-to-jpg-then-save-to-temp-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!