繁体   English   中英

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

[英]React-Native: Convert image url to base64 string

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

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

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

在本机反应中执行此操作的最佳选择是什么?

我使用rn-fetch-blob ,基本上它提供了很多文件系统和网络功能,使传输数据变得非常容易。

不推荐使用react-native-fetch-blob

import RNFetchBlob from "rn-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);
  });

项目维基

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

import RNFS from 'react-native-fs';

RNFS.readFile(this.state.imagePath, 'base64')
.then(res =>{
  console.log(res);
});
 ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => {
      ImageStore.getBase64ForTag(imageURI, (base64Data) => {
          // base64Data contains the base64string of the image
      }, (reason) => console.error(reason));
 }, (reason) => console.error(reason));

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

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

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

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

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

这需要react-native-file

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

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

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

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

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

如果您在托管工作流中使用 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}` }}
/>
If You are using **react-native-image-picker**
Then it includes base64 string in response object

    if you are  using any  other library i.e. **react-native-document-picker**
    then you have to use **react-native-fs** library 
    
    import RNFS from 'react-native-fs';
    
      RNFS.readFile(item.uri, 'base64').then((res) => {
                  //Here in enter code here res you  will get base64 string 
                });

  

我正在使用 react-native-image-crop-picker 添加 includeBase64 prop 它将在 base64 转换后的图像中响应

ImagePicker.openPicker({
  width: 300,
  height: 400,
  includeBase64:true
}).then(image => {
  console.log(image.data);
});

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

import RNFS from 'react-native-fs';

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

这工作正常。

对我来说,将设备上的本地文件中的 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);
        });
import { Platform, ActionSheetIOS } from 'react-native';
import DocumentPicker from 'react-native-document-picker';
import ImagePicker from 'react-native-image-crop-picker';
import RNFS from 'react-native-fs';

对于文档转换:

  pickDocument = async (resolve: (payload: any) => void, reject: (payload: any) => void) => {
    try {
      const result = await DocumentPicker.pick({
        type: [DocumentPicker.types.images, DocumentPicker.types.pdf]
      });
      const fileType = result[0].type;
      const fileExtension = fileType.substr(fileType.indexOf('/') + 1);
      const realURI = Platform.select({ android: result[0].uri, ios: decodeURI(result[0].uri), })
      const b64 = await RNFS.readFile(realURI, "base64")
      const filename = result[0].name.replace(/\s/g, '')
      resolve({ b64, fileType, fileExtension, filename });
    } catch {
      reject(new Error('Action cancelled!'));
    }
  }

对于图像转换:

  pickImage = (resolve: (payload: any) => void, reject: (payload: any) => void) => {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
      cropping: true,
    }).then(async response => {
      const { path: b64Content, mime: fileType, filename:name } = response;
      const b64 = await RNFS.readFile(b64Content, "base64")
      const fileExtension = String(fileType).substr(String(fileType).indexOf('/') + 1);
      const filename = name.replace(/\s/g, '')
      resolve({ b64, fileType, fileExtension, filename });
    }).catch(({message})=>{
      console.log('ERROR',message)
      reject(new Error('Action cancelled!'));
    });
  }

无需库,使用内置 JS 功能

export default async function base64File(url) {
  const data = await fetch(url);
  const blob = await data.blob();
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = () => {
      const base64data = reader.result;
      resolve(base64data);
    };
  });
}
import ImgToBase64 from 'react-native-image-base64';
 
ImgToBase64.getBase64String(trainingRooms)
            .then(base64String => {
                console.log("Sourabh____ ImgToBase64 base64String "+base64String );
            })
            .catch(err => {
                console.log("Sourabh____ ImgToBase64 error "+err);
            })

将url图像转换为base64

const getBase64ImageFromUrl = url => fetch(url).then(response => response.blob()).then( blob => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result); reader.onerror = reject; blob = new Blob([blob], {type: 'image/png'}); reader.readAsDataURL(blob); }), );

await getBase64ImageFromUrl("https://你的图片地址");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM