Javascript React-Native:将图像 url 转换为 base64 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34908009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:01:56  来源:igfitidea点击:

React-Native: Convert image url to base64 string

javascriptimagebase64react-native

提问by Avishay Bar

I'm building a react native app that needs to store images at base64 string format for offline viewing capabilities.

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

What library / function would give me the best result to store the image as base64 string? assuming my url is "http://www.example.com/image.png".

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

Also, do I need to make http request to get it before storing it as a string? my logic says yes, but in react native you can load images on the <Image> component without request them first from the server.

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

What would be the best option to do this in react native?

在 React Native 中执行此操作的最佳选择是什么?

回答by Ven Jest

I use react-native-fetch-blob, basically it provides lot of file system and network functions make transferring data pretty easy.

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

source Project Wiki

项目维基

回答by shrutim

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

回答by vijayst

To convert image to base64 in React native, the FileReader utility is helpful:

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

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

This requires react-native-file.

这需要react-native-file

Another alternative, and probably the preferred alternative, is to use NativeModules. The Medium articleshows how. It requires creating a native module.

另一种选择,可能也是首选的选择,是使用 NativeModules。在中等文章显示了如何。它需要创建一个本地模块

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

回答by David Madi

There is a better way: Install this react-native-fs, IF you don't already have it.

有一个更好的方法:安装这个react-native-fs,如果你还没有的话。

import RNFS from 'react-native-fs';

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

回答by Ulad Kasach

The standalone expo FileSystem package makes this simple:

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

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

As 2019-09-27 this package handles both file://and content://uri's

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

回答by zematdev

react-native-image-picker includes a base64 data node in the returned object. fyi

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

回答by Gilshaan Jabbar

I used another package: react-native-fs

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

import RNFS from 'react-native-fs';

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

This works fine.

这工作正常。

回答by TranVanThaiSon

For me upalod file mp4 from local file on devies to Facebook or another social:

对我来说,将设备上的本地文件中的 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);
        });

回答by Shehzad Osama

You can use react-native-image-base64. You have to give image url and it returns the base64 string of image.

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

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