React-Native:将图片网址转换为base64字符串

Avi*_*Bar 28 javascript base64 image react-native

我正在构建一个react native应用程序,需要以base64字符串格式存储图像以便离线查看功能.

什么库/函数会给我最好的结果来将图像存储为base64字符串?假设我的网址是" http://www.example.com/image.png ".

另外,在将其存储为字符串之前,是否需要发出http请求才能获取它?我的逻辑是肯定的,但在本机反应中,您可以在<Image>组件上加载图像,而无需先从服务器请求它们.

什么是最好的选择,做反应本机?

小智 32

我使用react-native-fetch-blob,基本上它提供了大量的文件系统和网络功能,使得传输数据非常容易.

import RNFetchBlob from "react-native-fetch-blob";
const fs = RNFetchBlob.fs;
let imagePath = null;
RNFetchBlob.config({
  fileCache: true
})
  .fetch("GET", "http://www.example.com/image.png")
  // the image is now dowloaded to device's storage
  .then(resp => {
    // the image path you can use it directly with Image component
    imagePath = resp.path();
    return resp.readFile("base64");
  })
  .then(base64Data => {
    // here's base64 encoded image
    console.log(base64Data);
    // remove the file from storage
    return fs.unlink(imagePath);
  });
Run Code Online (Sandbox Code Playgroud)

项目Wiki

  • 如何使用像'user/Project/example.png'这样的本地图像? (4认同)

shr*_*tim 15

 ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => {
      ImageStore.getBase64ForTag(imageURI, (base64Data) => {
          // base64Data contains the base64string of the image
      }, (reason) => console.error(reason));
 }, (reason) => console.error(reason));
Run Code Online (Sandbox Code Playgroud)

  • React Native警告开发人员不要再使用ImageEditor:警告:ImageStore已过时,并将在以后的版本中删除。要从本地映像获取以base64编码的字符串,请使用以下第三方库之一:* expo-file-system:`readAsStringAsync(filepath,'base64')`* react-native-fs:`readFile(filepath, 'base64')` (3认同)

Ula*_*ach 12

独立的 expo FileSystem 包使这变得简单:

const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
Run Code Online (Sandbox Code Playgroud)

作为 2019-09-27 这个包同时处理file://content://uri


vij*_*yst 6

要在React native中将映像转换为base64,FileReader实用程序很有用:

const fileReader = new FileReader();
fileReader.onload = fileLoadedEvent => {
  const base64Image = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(imagepath); 
Run Code Online (Sandbox Code Playgroud)

这需要react-native-file.

另一种替代方案,也许是首选替代方案,是使用NativeModules.在中等文章展示了如何.它需要创建一个本机模块.

NativeModules.ReadImageData.readImage(path, (base64Image) => {
  // Do something here.
});
Run Code Online (Sandbox Code Playgroud)


Dav*_*adi 5

有一个更好的方法:如果您还没有安装此react-native-fs,请安装它。

import RNFS from 'react-native-fs';

RNFS.readFile(this.state.imagePath, 'base64')
.then(res =>{
  console.log(res);
});
Run Code Online (Sandbox Code Playgroud)


zem*_*dev 5

react-native-image-picker 在返回的对象中包含一个 base64 数据节点。供参考


She*_*ama 5

您可以使用react-native-image-base64。您必须提供图像 url,它返回图像的 base64 字符串。

ImgToBase64.getBase64String('file://youfileurl')
  .then(base64String => doSomethingWith(base64String))
  .catch(err => doSomethingWith(err));
Run Code Online (Sandbox Code Playgroud)


Hen*_*ron 5

如果您在托管工作流程中使用 expo 并且无法使用react-native-fs,则可以使用该库来完成expo-file-system。下面是一个辅助函数,它只需提供一个图像 URL 即可实现此目的,并返回一个 base64 编码的图像。PS:它不包含base64前缀,您需要根据您拥有的图像类型自行添加它。


import * as FileSystem from 'expo-file-system';


async function getImageToBase64(imageURL) {
  let image;

  try {
    const { uri } = await FileSystem.downloadAsync(
      imageURL,
      FileSystem.documentDirectory + 'bufferimg.png'
    );

    image = await FileSystem.readAsStringAsync(uri, {
      encoding: 'base64',
    });
  } catch (err) {
    console.log(err);
  }

  return image;
}
Run Code Online (Sandbox Code Playgroud)

React Native Image 组件中的用法示例如下:

<Image
  style={{ width: 48, height: 48 }}
  source={{ uri: `data:image/png;base64,${image}` }}
/>
Run Code Online (Sandbox Code Playgroud)