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

时间:2016-01-20 18:45:20

标签: javascript image base64 react-native

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

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

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

在本地做出反应的最佳选择是什么?

10 个答案:

答案 0 :(得分:26)

我使用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);
  });

来源Project Wiki

答案 1 :(得分:14)

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

答案 2 :(得分:6)

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

const fileReader = new FileReader();
fileReader.onload = fileLoadedEvent => {
  const base64Image = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(imagepath); 

这需要react-native-file

另一种替代方案,也许是首选方案,是使用NativeModules。 Medium article显示了如何。它需要创建native module

NativeModules.ReadImageData.readImage(path, (base64Image) => {
  // Do something here.
});

答案 3 :(得分:3)

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

import RNFS from 'react-native-fs';

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

答案 4 :(得分:2)

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

ImgToBase64.getBase64String('file://youfileurl')
  .then(base64String => doSomethingWith(base64String))
  .catch(err => doSomethingWith(err));

答案 5 :(得分:1)

独立的expo FileSystem软件包使此过程变得简单:

const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });

自2019年9月27日起,此软件包可处理file://content:// uri的

答案 6 :(得分:0)

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

答案 7 :(得分:0)

我使用了另一个软件包:react-native-fs

import RNFS from 'react-native-fs';

var data = await RNFS.readFile( "file://path-to-file", 'base64').then(res => { return res });

这很好。

答案 8 :(得分:0)

对我而言,将设备上的本地文件中的mp4音频文件上传到Facebook或其他社交网站:

var data = await RNFS.readFile( `file://${this.data.path}`, 'base64').then(res => { return res });
        const shareOptions = {
            title: 'iVideo',
            message: 'Share video',
            url:'data:video/mp4;base64,'+ data,
            social: Share.Social.FACEBOOK,
            filename: this.data.name , // only for base64 file in Android 
        };     
        Share.open(shareOptions).then(res=>{
           Alert.alert('Share Success`enter code here`!')
        }).catch(err=>{
            console.log('err share', err);
        });

答案 9 :(得分:0)

如果您在托管工作流中使用 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;
}

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

<Image
  style={{ width: 48, height: 48 }}
  source={{ uri: `data:image/png;base64,${image}` }}
/>
相关问题