在React Native中,如何将base64图像转换为jpg,然后保存到临时路径?
在 react-native
中,在 react-native-fetch-blob
的帮助下,将图像转换为 BASE64
格式很容易.,我只是这样做:
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));
但是,反过来呢?我知道有一些软件包可以做到这一点,但我想知道是否有可能仅使用 react-native-fetch-blob
或 react-native-fs
?
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
?
我想要的是将 BASE64
图像转换并保存到文件后,我能够像这样显示它:
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={{ ... }}
/>
原来,这并不是一件棘手的事情,假设我有一个 BASE64
图像,如果我想将其转换为JPG
,只需像这样使用 react-native-fs
:
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));
仅此而已