React-Native:将图像 url 转换为 base64 字符串
React-Native: Convert image url to base64 string
我正在构建一个 React 本机应用程序,它需要以 base64 字符串格式存储图像以实现离线查看功能。
将图像存储为 base64 字符串的最佳结果是什么库/函数?假设我的 url 是“http://www.example.com/image.png”。
此外,在将其存储为字符串之前,我是否需要发出 http 请求来获取它?我的逻辑是肯定的,但是在本机反应中,您可以在 组件上加载图像,而无需先从服务器请求它们。
在 React Native 中执行此操作的最佳选择是什么?
要在 React native 中将图像转换为 base64,FileReader 实用程序很有帮助:
const fileReader = new FileReader();
fileReader.onload = fileLoadedEvent => {
const base64Image = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(imagepath);
另一种可能是首选的替代方法是使用 NativeModules。 Medium article shows how. It requires creating a native module.
NativeModules.ReadImageData.readImage(path, (base64Image) => {
// Do something here.
});
我用rn-fetch-blob,基本上它提供了很多文件系统和网络功能,使数据传输非常容易。
react-native-fetch-blob is deprecated
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);
});
ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => {
ImageStore.getBase64ForTag(imageURI, (base64Data) => {
// base64Data contains the base64string of the image
}, (reason) => console.error(reason));
}, (reason) => console.error(reason));
有一个更好的方法:
安装此 react-native-fs,如果您还没有安装它。
import RNFS from 'react-native-fs';
RNFS.readFile(this.state.imagePath, 'base64')
.then(res =>{
console.log(res);
});
独立的 expo 文件系统包使这变得简单:
const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
- https://docs.expo.io/versions/latest/sdk/filesystem/
- https://github.com/expo/expo/tree/master/packages/expo-file-system
作为 2019-09-27,此包处理 file://
和 content://
uri 的
react-native-image-picker 在返回的对象中包含一个 base64 数据节点。仅供参考
我使用了另一个包: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);
});
您可以使用 react-native-image-base64。你必须给图像 url 并且它 returns 图像的 base64 字符串。
ImgToBase64.getBase64String('file://youfileurl')
.then(base64String => doSomethingWith(base64String))
.catch(err => doSomethingWith(err));
如果您在托管工作流中使用 expo 而无法使用 react-native-fs
,您可以使用 expo-file-system
库来实现。这是一个辅助函数,它将通过仅提供图像 URL 并将 return 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}` }}
/>
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!'));
});
}
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
});
无需库,使用内置 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);
};
});
}
我正在构建一个 React 本机应用程序,它需要以 base64 字符串格式存储图像以实现离线查看功能。
将图像存储为 base64 字符串的最佳结果是什么库/函数?假设我的 url 是“http://www.example.com/image.png”。
此外,在将其存储为字符串之前,我是否需要发出 http 请求来获取它?我的逻辑是肯定的,但是在本机反应中,您可以在
在 React Native 中执行此操作的最佳选择是什么?
要在 React native 中将图像转换为 base64,FileReader 实用程序很有帮助:
const fileReader = new FileReader();
fileReader.onload = fileLoadedEvent => {
const base64Image = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(imagepath);
另一种可能是首选的替代方法是使用 NativeModules。 Medium article shows how. It requires creating a native module.
NativeModules.ReadImageData.readImage(path, (base64Image) => {
// Do something here.
});
我用rn-fetch-blob,基本上它提供了很多文件系统和网络功能,使数据传输非常容易。
react-native-fetch-blob is deprecated
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);
});
ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => {
ImageStore.getBase64ForTag(imageURI, (base64Data) => {
// base64Data contains the base64string of the image
}, (reason) => console.error(reason));
}, (reason) => console.error(reason));
有一个更好的方法: 安装此 react-native-fs,如果您还没有安装它。
import RNFS from 'react-native-fs';
RNFS.readFile(this.state.imagePath, 'base64')
.then(res =>{
console.log(res);
});
独立的 expo 文件系统包使这变得简单:
const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
- https://docs.expo.io/versions/latest/sdk/filesystem/
- https://github.com/expo/expo/tree/master/packages/expo-file-system
作为 2019-09-27,此包处理 file://
和 content://
uri 的
react-native-image-picker 在返回的对象中包含一个 base64 数据节点。仅供参考
我使用了另一个包: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);
});
您可以使用 react-native-image-base64。你必须给图像 url 并且它 returns 图像的 base64 字符串。
ImgToBase64.getBase64String('file://youfileurl')
.then(base64String => doSomethingWith(base64String))
.catch(err => doSomethingWith(err));
如果您在托管工作流中使用 expo 而无法使用 react-native-fs
,您可以使用 expo-file-system
库来实现。这是一个辅助函数,它将通过仅提供图像 URL 并将 return 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}` }}
/>
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!'));
});
}
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
});
无需库,使用内置 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);
};
});
}